text
stringlengths
180
608k
[Question] [ Given a string as input find the longest *contiguous* substring that does not have any character twice or more. If there are multiple such substrings you may output either. You may assume that the input is on the printable ASCII range if you wish. ## Scoring Answers will first be ranked by the length of their own longest non-repeating substring, and then by their total length. Lower scores will be better for both criteria. Depending on the language this will probably feel like a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge with a source restriction. ## Triviality In some languages achieving a score of **1, x** (lenguage) or **2, x** (Brain-flak and other turing tarpits) is pretty easy, however there are other languages in which minimizing the longest non-repeating substring is a challenge. I had a lot of fun getting a score of 2 in Haskell, so I encourage you to seek out languages where this task is fun. ## Test cases ``` "Good morning, Green orb!" -> "ing, Gre" "fffffffffff" -> "f" "oiiiiioiiii" -> "io", "oi" "1234567890" -> "1234567890" "11122324455" -> "324" ``` ## Scoring submission You can score your programs using the following snippet: ``` input.addEventListener("input", change); // note: intentionally verbose :) function isUnique(str) { var maxCount = 0; var counts = {}; for(var i = 0; i < str.length; i++) { var c = str.charAt(i); counts[c] |= 0; counts[c]++; if(maxCount < counts[c]) { maxCount = counts[c]; } } return maxCount <= 1; } function maximizeSubstring(str, pred, cost) { var mostExpensive = -1; // iterate over substrings function iterate(start, end) { var slice = str.slice(start, end); if(pred(slice)) { var profit = cost(slice); if(profit > mostExpensive) { mostExpensive = profit; } } end++; if(start >= str.length) { return; } else if(end > str.length) { start++; iterate(start, start); } else { iterate(start, end); } } iterate(0, 0); return mostExpensive; } function size(x) { return x.length; } function longestNonRepeatingSize(str) { return maximizeSubstring(str, isUnique, size); } function change() { var code = input.value; output.value = "Your score is: " + longestNonRepeatingSize(code); } change(); ``` ``` * { font-family: monospace; } ``` ``` Input code here: <br> <textarea id="input"></textarea> <br> <textarea id="output"></textarea> ``` [Answer] # C, score 2, ~~747~~ ~~720~~ 662 bytes ``` L [ 1 << 7 ] , * q , * r , l , d , i , c , j , s , t , k = 1 << 7 ; h ( ) { q = s + i + j ++ ; * q % k && ! L [ * q % k ] ++ && h ( ++ c ) ; } g ( ) { q = s + i ; * q % k ? z ( k ) , h ( j = c = 0 ) , c > d && ( d = c ) && ( l = i ) , g ( ++ i ) : 0 ; } f ( S , T ) { s = S ; l = i = d = 0 ; g ( t = T ) ; p ( i = 0 ) ; } p ( ) { q = s + l + i ; r = t + i ; i ++ < d ? p ( * r = * q ) : ( * r = 0 ) ; } z ( i ) { L [ -- i ] = 0 ; i && z ( i ) ; } ``` Works at least on 32-bit MinGW (with optimizations disabled). Doesn't use a single keyword. Works apparently on TIO with gcc and clang, too: [Try it online!](https://tio.run/##7VM9b8IwFNz5FQdSUSCJxFdLW0gZWbrBhjJQQ4IhJDRJFxB/vSk519RqhVg74OHJvnfv7vklFm4oRFG8AjOgDQyHQB/wAQdoAu96k3ITMS4YJaNgXDNmjDnjBvBMxQGwAiygARyo67HAppBNCdsmT9neUaNeB6qA6s9M@Ipe5pVueRKUP0kcgfCy2y@PEbAneUO@oxXXrBKMLZ06HV84gdLZ4s7Txt9QREjqivDcnoKeqaaaDJibkDfV3Wasn5Bz1vK0lapVojmRqb71jqA0GlYuuwujiIyBpMRzA5Gq6SGNR1qlqalqguo@Jm4a73VDylt9Rdcl5Bu3kWp2Jr0UKGScYzuXsdWoHCo4LbGap8jydNZudXr@oEIwsGrjJFlgm6SxjEMH43S5jJGkb9WaU7IbA/J2H3lmqaOuC37WNWoiy8V4jdrudHv3D/3Hp9Y15u3d3d7d/3t3tb8/7LH4FEE0D7PC3XY7Xw) (Thanks @Dennis!) **Call with:** ``` int main() { char str[1024]; f("Good morning, Green orb!", str); puts(str); f("fffffffffff", str); puts(str); f("oiiiiioiiii", str); puts(str); f("1234567890", str); puts(str); f("L [ 1 << 7 ] , * q , * r , l , d , i , c , j , s , t , k = 1 << 7 ; h ( ) { q = s + i + j ++ ; * q % k && ! L [ * q % k ] ++ && h ( ++ c ) ; } g ( ) { q = s + i ; * q % k ? z ( k ) , h ( j = c = 0 ) , c > d && ( d = c ) && ( l = i ) , g ( ++ i ) : 0 ; } f ( S , T ) { s = S ; l = i = d = 0 ; g ( t = T ) ; p ( i = 0 ) ; } p ( ) { q = s + l + i ; r = t + i ; i ++ < d ? p ( * r = * q ) : ( * r = 0 ) ; } z ( i ) { L [ -- i ] = 0 ; i && z ( i ) ; }"); puts(str); } ``` **Output:** [![](https://i.stack.imgur.com/M8KyW.png)](https://i.stack.imgur.com/M8KyW.png) **The code with slightly more readable formatting:** ``` L[1<<7], *q, *r, l, d, i, c, j, s, t, k=1<<7; h() { q = s+i+j++; *q%k && !L[*q%k]++ && h(++c); } g() { q = s+i; *q%k ? z(k), h(j=c=0), c>d && (d=c) && (l=i), g(++i) : 0; } f(S, T) { s = S; l = i = d = 0; g(t=T); p(i=0); } p() { q = s+l+i; r = t+i; i++<d ? p(*r=*q) : (*r=0); } z(i) { L[--i] = 0; i && z(i); } ``` And this can be used to generate proper spacing to get to the formatting with score 2: [Try it online!](https://tio.run/##XVFNb8IwDL3nV3hIIKcxUrcdJg0Cf4Ab3BAHlEJr6FBbOk1i4rd3dkthwlJafzw/vzhhnIbQNHyq4WvLJ7Tm14BYyLaVfAiKyseTNvWTcb4DxJCBh3RXKwSthdFIgDCD2Lawrl@N94Bt5f3N3pNqRfXipSCNRTWLYS4/EbDHAcAwDEjoLHxC8d2NkGhiHq0yPGRd4mquTbNYv06nHxsyUUkQVQQ5QULAQkNwIDgT1ARHr6iJMdn9iqUwnR27g3MdXVQOjyrqZbFWd@OcRhk6F0TB1Zj0ufdf3xwueLQk8IMPPhYvzBLtx8SHdkmYe5Z0Knys94tbzj0uCVY971l4lx1rLi7LSeTcXiDF2q9uyyiQZUpLUTzJynthuqu6D9i5aaK7xqjyUakK1LtxXJB7ksV6PObNYyqreK0L8A8) --- # C, score 3, 309 bytes ``` i , j , l , c , d ; f ( \ c\ \ h\ \ a\ \ r * s ) { \ f\ \ o\ \ r \ ( i = l = d = 0 ; s [ i ] ; c > d && ( d = c ) && ( l = i ) , ++ i ) \ f\ \ o\ \ r ( \ c\ \ h\ \ a\ \ r L [ \ 1\ \ 2\ \ 8 \ ] = { j = c = 0 } ; s [ i + j ] && ! L [ s [ i + j ++ ] ] ++ ; ++ c ) ; \ w\ \ r\ \ i\ \ t\ \ e ( 1 , s + l , d ) ; } ``` [Try it online!](https://tio.run/##jVFNT8JAEL3PrygcSLGYUPzCNPXqxX/g9IAL1TU4NS3GA@lvxzezLqDBxIV9O1/73szWnT87t9t5mtAr9hrbYS@poJpSYnIMeFFYKLR0Rh2NaQu71kATooxiTyUISlwuaQqCjh4Rq2A5ukN0NEKRJh0IzNFqD2dCWWbGT9KT@vQAWqZcvZnCHLsC0RYTKLeK93v5DNFK1QZ28RCEYoUfjkJBeyrA9GkqCl5ho7BCJzma7HBxba@jtf3OyyZ5W3hJ9T0SrDod3jfNMnlrWvHyPEnu29VKkqZ9GgzHxfvHpkuHMGJtfVin0o3XZXgqnc8uLq@ub@a3032WheXcFstRpWeZsLwarg2d4ZKlYKlZUlxkjXIwXqKxiEbLcsbSsYxZtiFUx1xzVKQH2KBYmlZpKsCpaYHg0bKVuWjjzgpGI7sWSp2pfIcCh7cQWs6y6PzZwr@GYXmwVtTNY3wWjXk4KtPe2tOFvsIg/c9ZMiuoQsuDyPwrrY1X9lerCEeYtAhqn4f2vg0fjU00VjZebk/RGfU6fslA1Otn73df) [Answer] # [Haskell](https://www.haskell.org/), score 2, ~~492~~ ... ~~307~~ ~~224~~ ~~212~~ ~~209~~ 207 bytes ``` ((yy:yyy))??ss|ss==yy = "" | yy==yy=yy:yyy??ss ss??sss=ss ss""="" ss((ff:fff)) = ff : ss fff??ff ff""="" ff((xxx:xx)) = ss((xxx:xx))##ff xx xx##xxx | ((((xx>>xx))<)) $ xxx>>xx=xxx|xx==xx=xx ``` [Try it online!](https://tio.run/##3Y9RasRADEP/cwoz6YcD7R4g1MlZQoh2lqbpUgdqQ87edDzdXqJfEuJJ2HnSt2VdzyzAyezeu3vXjaPqoSriTiREKREdRO6RyC8VTKMaolJtSpJSUwwz0APoutoGiHoi1bAYR6ABHjDAbGa92QOO9l/QtlE1a8zatoT1COYAhiGA1yg9BVIDKXoUkWrP9@m2lcnbti@f07wXUPPHF12I12W77nkYhJ/LwoXyf/v9e8Y6XfV8me/3Hw "Haskell – Try It Online") Golfed literally hundreds of bytes thanks to [W W](https://codegolf.stackexchange.com/users/56656/heeby-jeeby-man) and [Ørjan Johansen](https://codegolf.stackexchange.com/users/66041/%c3%98rjan-johansen)! ### Explanation The function `(??)` takes a character `c` and a string `s` and returns the longest prefix of `s` that does not contain `c`. Ungolfed and not optimized for score: ``` c ?? (y:s) | c==y = "" | True = y : c ?? s c ?? s = s ``` The function `ss` uses `(??)` to find the longest prefix of unique chars of a given string: ``` ss (x:r) = x : (x ?? ss r) ss "" = "" ``` `(##)` is a function which takes two strings and returns the longer one. The length comparison works by repeating the string `x` as often as `x` is long (`x>>y`) and as `y` is long (`y>>x`) and checking which of the resulting strings is lexicographically larger. ``` x ## y | (x>>x) < (y>>x) = y | True = x ``` Finally `ff` recurses over the input string, generates the longest prefix with `ss`, recursively determines the longest non-repeating substring of the tail of the string and returns the longer of the two with `(##)`: ``` ff "" = "" ff (x:r) = ss(x:r) ## ff r ``` [Answer] # Lua, score 3, 274 bytes ``` g='g'..'s'..'u'..'b' _G [ 'l'..'o'..'a'..'d' ]( g[g ]( "s =...f o r d = # s - 1 , 0 , - 1 d o f or r = 1 , # s - d d o t = s :s ub (r ,r +d )i f n ot t: fi nd '( .) .* %1 't he n p ri nt (t )r et ur n en d e n d e nd "," ",""))(...) ``` Note: Lua 5.2 or Lua 5.3 is required Usage: ``` $ lua lnrs.lua "Good morning, Green orb!" ing, Gre $ lua lnrs.lua "fffffffffff" f $ lua lnrs.lua "oiiiiioiiii" oi $ lua lnrs.lua "1234567890" 1234567890 $ lua lnrs.lua "11122324455" 324 ``` Main idea: interleave everything with spaces, insert `" "` (two spaces) to split long identifiers Ungolfed code: ``` g = "gsub" _G["load"]( g[g]( -- g[g] == string.gsub - a function for substitution of substrings "The source of actual program, but two-space sequences were inserted in some places", " ", -- we are replacing all two-space substrings "" -- with an empty string ) )(...) ``` Actual program (after removing all pairs of spaces): ``` s = ... for d = #s - 1, 0, -1 do for r = 1, #s - d do t = s:sub(r, r+d) if not t:find"(.).*%1" then print(t) return end end end ``` BTW, the JS snippet for calculating the score fails on my code. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 37 bytes, score 9 ``` . $&$'¶ (.)(?<=\1.+).* O#$^` $.& 1G` ``` [Try it online!](https://tio.run/##K0otycxL/H9oG1f8fz0uFTUVdSBTQ09Tw97GNsZQT1tTT4uLy19ZJS6BS0VPjcvQPeF/PNehbUSqBQA "Retina 0.8.2 – Try It Online") The direct translation of this answer to Retina 1 saves a byte by using `N` instead of `O#`. However, if you naïvely golf the Retina 1 answer down to 28 bytes, its score actually rises to 10! Explanation: ``` . $&$'¶ ``` Generate all suffixes of the input. ``` (.)(?<=\1.+).* ``` For each suffix, take the prefix up to the first duplicated character. ``` O#$^` $.& ``` Sort the remaining strings in reverse order of length (i.e. longest first). ``` 1G` ``` Take the longest. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), score 2, 14 bytes ``` Ẇµµff Q € Ṫ ``` *Thanks to @JonathanAllan for score -1, +7 bytes and for noticing a bug.* [Try it online!](https://tio.run/##y0rNyan8///hrrZDWw9tTUtTUAhUUHjUtEZB4eHOVf8f7t5yuB3Ii/z/3z0/P0UhN78oLzMvXUfBvSg1NU8hvyhJkSsNAbjyM0EATHIZGhmbmJqZW1gacBkaGhoZGRuZmJiacmG3CQA "Jelly – Try It Online") ### How it works ``` Ẇµµff Q € Ṫ Main link. Argument: s (string) Ẇ Window; yield all substrings of s, sorted by length. µ Begin a new chain. Argument: A (array of substrings) µ Begin a new chain. Argument: A (array of substrings) f Filter A by presence in itself. Does nothing. Q € Unique each; deduplicate all strings in A. f Filter A by presence in the array of deduplicated substrings, keeping only substrings composed of unique characters. Ṫ Tail; take the last (longest) kept substring. ``` [Answer] # [Clean](https://clean.cs.ru.nl), score ~~7~~ 5, 276 bytes ``` @[ss:s]=rr(pp[][ss:s])((@s)) @s=s ee x[rr:xx]|e x rr=True=ee x xx ee x xx=f f=e'e'' ' e::! Char ! Char ->Bool e _ _= code { eqC } pp p[r:rr]|ee r p=p=pp(a r p)rr pp a _=a a x[ll:l]=[ll:a x l] a l ll=[l] l[]rr=e'l''l' l ff[]=f l[r:rr][ss:ll]=l rr ll rr x y|l x y=y=x ``` [Try it online!](https://tio.run/##PU/RasMwDHzXV9yenMD6AwGPsA7KYA@D7c2Y4qVOV1BiT2nBZd2vL1PWMSSk05mzTh3HMM5D2p04YgiHcW7dNDWTtyJVzs5fp7qq2qmuqZ3sRDGiOJGmFH9RCBH7KqdoFx6l0F@3PfU2mmgMDMWmuQHW70GAf7C6u0@JKQJbbC3QpZ3iT6L4saYvyhnZSSOiayIE2WrkKiywFlneg@oCBagh5oa9XVrQ9WCvNINZKU/svLqMho0mMfreefWn/O//y5GsatZbVEJaC84XXqo92zK/HIMcYdHCmU1KOwxJxsO4v8VGYhyR5O3G@Pm76znsp3n1@DQ/nMcwHLrr8Mzh2CcZfgA "Clean – Try It Online") Thanks to [@Οurous](https://codegolf.stackexchange.com/users/18730/%ce%9furous) for showing me that it is possible to call ABC machine code directly from within Clean. This allows to get rid of the previous bottle-neck `import` which set the minimal score to 7, but needs the keyword `code` which sets the minimal score to 5 for this approach. An ungolfed and not score-optimized version of the above code can be found here: [Try it online!](https://tio.run/##RVHBasMwDL37K9RTW1jpPdCtrGNlsMNgu4UQvERJDY6dyg4kbPv1ZbLjshxkPVl61nupNEozd7YeNEInlZn3@3hCM5jKK2vEEfICDhxCNmYuANr0eRHBdnMEtxWCx1BjJxBhhHzKqBDA3zcEPPHIBw0YSweIPbS0loyfpXYYKaqLJMDrILXyk0DIMlidQm2Ju3t4tFbzRRkHK1sjfEVWvJ7ET@TQ1rToPAxGXQeEnrBRo@jBhe3/1wqPO@Zwaal@I0NlS7G1jDeBTvY9mlrIm6xgxZQFyFwyKcjHIjYrBxpN6y98OAc2iXkQOphY3mzQnEZTF@V8WQZmjtFdDZQeJ/QDmUUS1zwp0woKjiYZOrk7JRXj/O4lec74Z63P1tbQWTI8dgdnQjS80@dqXcy/VaNl6@bdy@v8NBnZqWoBb1r6xlL3Bw "Clean – Try It Online") --- ### Previous version with score 7, ~~158~~ ~~154~~ 130 bytes ``` import StdEnv @[xx:rr]=c(%[][xx:rr])(@rr) @e=e c s b| length s< length b=b=s %s[xx:r]| isMember xx s=s= %(s++[xx])r %r _=r ``` [Try it online!](https://tio.run/##RY7NSsQwFIX3eYrjokzLjC8gBrpQBmEEYZYlSJLeqYH8yL1RKvjsxqKCu/NxvgPHR7K5pTK/RUKyIbeQXgtX4Fzn@/wOqHFa1xtmo33fTeYPhn5kHtRImpSHwH0CkfJSXwC5/c9OOy2qk5@Z2aQgj5QcMdYVokWj62W/32ozsOoYz5rbudrtgcaIaXcsZUYqnENeDjgyUUZhd7Uz7ctfol2kXT@c2t1Htin4X3iKtl4Kp28 "Clean – Try It Online") With the `import` the score cannot go below 7. Without the import one would need to implement equality on strings or chars without any library functions which is ~~probably not~~ possible, as can be seen in the new version above. [Answer] # [Python 3](https://docs.python.org/3/), score 4, 155 bytes ``` exec(('l=la''mbd''a f'',e=en''ume''rat''e:m''ax''([f[ j :k] for j,i in e ( f)f''or k,i in e ( f )if len ( { *''f[j'':k]''})==k-''j],''key''=le''n)')) ``` This defines a function `l`. *Thanks to @xnor for pointing out that strings of length 3 don't raise the score, saving 32 bytes.* [Try it online!](https://tio.run/##TY/LbsIwEEXX5Sumi@jayKASHm0jpVs@oEvEIiRjcB52ZIIEqvrt1I5Q21lYOtf2mZn@NpycXd7vfOVSCLR5WwDdoQIK0oDinC1w6RjwxQBw1oWrKyB2ekc1UdbsibTzRLUyZCwxCdIy/I1Z8y8jaTRRy5YCfdEU0LsaCALgW@Z5MwPqvQIavgF5G1paCSnv0X6OGmydq6hz3hp7VLT1HGTOH56hCPqvIjoTazwjLtLlar15fXt/GWmxSNNlulqt18gmT703dhBIZunG0@yDEg9KSJwVteIspZxMumIoT5QHdj1bgXnpKp4PxkHOPRdVayyL@PCh@iyd54ySSxSFlcUokIo89/4XtGk5SB/Kig@X4@gMExZx8R8 "Python 3 – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), score 2, 19 bytes ``` s ᶠ l ᵒ ≠ ˢ t ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompoe7Omsfbp3wv1hB4eG2BQoKOUB66yQFhUedQM7pRQoKJf//Ryu55@enKOTmF@Vl5qXrKLgXpabmKeQXJSkq6SgopSEAiJufCQJgEsQ1NDI2MTUzt7A0APMMDY2MjI1MTExNQVzclirFAgA "Brachylog – Try It Online") Just a boring old "space everything out" answer. At least I learnt that metapredicates can be spaced away from the predicates and still work (and the (parametric) subscripts and superscripts can't). `s ᶠ` - find all substrings of the given string `l ᵒ` - order them by their length (ascending by default) `≠ ˢ` - select those that have all distinct elements `t` - get the tail (last element) of that - the one with the biggest length [Answer] # [Pyth](https://github.com/isaacg1/pyth), 11 bytes, score 4 -4 score thanks to Dennis ``` e lD {I# .: ``` --- ``` elD{I#.:Q Full program, inputs "string" from stdin and outputs to stdout e The last element of the list generated by taking .:Q All substrings of the input # Filtered for {I Being invariant over deduplicate i.e. being "non-repeating" lD and sorted by length ``` [Try it online!](https://tio.run/##K6gsyfj/P1Uhx0Wh2lNZQc/q/3@ljMzKxEQlAA "Pyth – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), score 2, 10 bytes ``` ►IIËII≠IIQ ``` [Try it online!](https://tio.run/##yygtzv7//9G0XZ6eh7s9PR91LvD0DPz//7@SoaGhkZGxkYmJqakSAA "Husk – Try It Online") ## Explanation The program is equivalent to this: ``` ►Ë≠Q Implicit input. Q List of substrings. ► Find one that maximizes: Ë all ordered pairs ≠ are inequal. ``` The built-in `Ë` evaluates `≠` on all ordered pairs of its argument `x`, and returns `length(x)+1` if every result is truthy, otherwise `0`. When we maximize this, we find the longest string that has no repeated characters. In the submission, I just insert the identity function `I` between each function, twice. Since `IË` is the same as `Ë`, `I≠` is the same as `≠` and so on, this does not change the semantics. The only danger is that a higher order function could decide to use one of the `I`s as its argument, but luckily that leads to a type error in our program, so it doesn't happen. [Answer] ## Clojure, score 4 ``` #( let [N (fn [[_ & r]] r) R (fn R [f v c] (if c (R f (f v ( nth c 0)) ( N c)) v)) C (fn C ( [i] (C ( seq i) 0)) ( [i n] (if i (C ( N i ) ( inc n)) n))) J (fn [c i] (assoc c (C c) i)) I (fn F [f i n R] (if ( = (C R) n) R (F f (f i) n ( J R (f i)))))] ( apply str (R ( fn [a b] ( if (< (C a) (C b)) b a )) "" ( for [k (I N % (C % ) [])] (R ( fn [ t c ] ( if ( or ( = t ( str t) ) (( set t)c))(apply str t) ( J t c)))[]k))))) ``` Oh man this was painful! `N` implements `next`, `R` is `reduce`, `C` is `count`, `J` is `conj` (works only for vectors) and `I` is `iterate`. `apply str` is there twice because otherwise "aaaa" input wouldn't return a string but a vector `[\a]`. Luckily I got to use `apply` and `assoc`, I didn't know you could assoc one index beyond a vector's last element :o [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), score 5, 10 bytes ``` ẆµQQ⁼µÐfµṪ ``` [Try it online!](https://tio.run/##y0rNyan8///hrrZDWwMDHzXuObT18IS0Q1sf7lz1/3D7o6Y1kf//Ryu55@enKOTmF@Vl5qXrKLgXpabmKeQXJSkq6XApKKUhAJifnwkCYBLMNzQyNjE1M7ewNABzsVmlFAsA "Jelly – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), score 4, 317 bytes ``` exec(('%s' *58 %( 's=','in','pu','t(',');','pr','in','t(','so','rt','ed','((s','[i',':j',']f','or',' j',' i','n ','ra','ng','e(','1,','le','n(','s)','+1',')f','or',' i',' i','n ','ra','ng','e(','j)','if',' l','en','(s','et','(s','[i',':j',']))','==l','en','(s','[i',':j',']))',',k','ey','=l','en',')[','-1','])'))) ``` [Try it online!](https://tio.run/##7ZDNCsIwEIRfZS8lWa2HIIIofZLiQTRqaklLk4J9@roTqH8HL169fGx2ZybLtkO8NH45jvZmD1qrLCii2WpNlGkiFQqVK@cFbS@IWsBbPLtpkHqhEXRRYI8CrYOwdIJNJdidBA0shCdh4AmWPaozfIgxuaC26KVUFswN/nwGuG8BFRwOYqrRw4JpFxun6mUrhroo3pWf8/yK8QDlQ8ilYGGSRjHz/3w/ne8O) Unexeced code: ``` s=input();print(sorted((s[i:j]for j in range(1,len(s)+1)for i in range(j)if len(set(s[i:j]))==len(s[i:j])),key=len)[-1]) ``` `lambda a` contains `mbda` which has score 5, and a function needs `return` which apparently can't be `exec`ed (so takes a score of at least 5 for `eturn`), so a full program was necessary. It's probably possible to golf down the unexeced code size quite a bit, but I can't see a quick clear improvement. [Answer] # [Alice](https://github.com/m-ender/alice), 40 bytes ``` /ii..nn$$@@BBww..DD~~FF..!!nn$$KK??oo@@ ``` (Trailing newline) [Try it online!](https://tio.run/##S8zJTE79/18/M1NPLy9PRcXBwcmpvFxPz8Wlrs7NTU9PUREk6u1tb5@f7@DA9f@/e35@ikJuflFeZl66joJ7UWpqnkJ@UZIiAA "Alice – Try It Online") The instruction pointer moves diagonally in ordinal mode, so only every other character is executed. ``` [[email protected]](/cdn-cgi/l/email-protection)~F.!n$K?o@ i take input .n$@ terminate if empty B push all nonempty substrings, with the longest on the top of the stack w push return address (start main loop) . make copy of current substring D deduplicate characters ~ swap: this places the original above the deduplicated copy F Push the original string if it is a substring of the deduplicated copy (which can only happen if they're equal); otherwise push empty string .! place a copy on the tape n$K if the empty string was pushed, return to start of loop o output @ terminate ``` [Answer] # [Perl 6](https://perl6.org), score: ~~15 10~~ 8, length: ~~46 55~~ 62 bytes ``` {~m:ov/(.+)<!{$0.comb.repeated}>/.max(&chars)} ``` [Test it](https://tio.run/##fVBLbsIwEN37FIOVQtL8SPi0JRB1xwW6oyxCYtpIiW05AYFQcph2yRnY9EIcIXUMpV11FqOn9@Zp3gwnIhs3m4LAduzEAcr30I1ZQmDWHOp8wrau7pjGtHPQ@k7M8pUjCCdRSZIqdJ082und@D0ShVE10vlckqKEGWQpJYVuSJ1P4IAAclc2gPPpA59Pn1DfkD61F3gZmobSXwsTenbYa4EiFv84libcwQJ6Vjt@D0tpcAPZaq1vQUT3UH8dNQ9VqD3uRQYLEM8iCqZKGaA1E9fAdgi6llK@KS2N7DiJ5XmGyp0WdkIIz/bQ/uQ6ZFhwG5NQcQ6XfwxQ1eA5YwnkTNCUvlkwF4RQYGLVwe0a/ENihNe/ddHWkmRpW6pfDQxbIGmpef5gOBo/PD71MSjtDyFVz/P9gT8cjkYXp8T4Gw "Perl 6 – Try It Online") ``` {~m:ov/(..*)<!{(($0)).comb.repeated}>{{}}/.max(&chars)} ``` [Test it](https://tio.run/##fVBLcoJAEN3PKdopIozAIPhJIkpl5wWyMy4QxoQqYKYALS0KDpMscwY3uZBHIAMak1V60fXqvX4zr1uwLJ42u5zBfkoDFyVH6Ac8ZLBoyjqZ8b2lUTog816pacqQEBrwZEMzJphfsLDyyrKqLJr4B60fvPlZTqpGPvFUsLyABcRRynKNSF3MoEQAiSUbwPn0js@nD6hvSJubK7z2dNLpL7kOqumpLeiI1T@OtQ53sALVaMcHsJYGy5WtVoYG@OkR6q9PxUYVard8lsFcJGI/Bb1L6aItz66BTQ80JUrFrjAUdhAskCuSLneUmyFjIj5Ce5zrEDHgNiZhx1EhD@qiqsFLzkNIeJZG6asBy4yxFHi26eH2G/xDYoS3v3XRtpLkUVtdvxo4NkDSUrOd0XgyvX94HGLotD@EVG3bcUbOeDyZXJwS428 "Perl 6 – Try It Online") ``` {m:ov:i/(..*)<!{(($0)).comb.repeated}>{{}}/.max((&chars)).Str} ``` [Test it](https://tio.run/##fVBLbsIwEN37FFMrBYf8SPi0JRB1xwHaHWUREtNGSmLLCQgUhcO0y56BTS/EEVLHUNpVZzF6eu@N/WY4Fem42RQUtmM78lG2h07EYgqzpsombDtJHGLbPX16UxGi9XXdjli2sgXlNCxpXAdVVdeOnYU7QjrRWygKaXkqRd3Ilx5LWpQwgzTJaUF06eITqBBA5sgGcDq@49PxAw5XRKbWAi8DQ1f6S2FA1wq6LVDE4p@JpQG3sICu2dp7sJQDji/bQeubEOZ7OHx9ai6qUbvsswzmI56GORgqpY/WTFwCWwEQLcn5pjQ1uuM0kovqKndSWDGlPN1De6OLSTfhapNQcTaXd/VR3eA5YzFkTORJ/mrCXFCaAxOrG9x@g39IjPD6t87aWpIsaUv1ywDDJkhaaq43GI7Gd/cPfQxK@0NI1XU9b@ANh6PReVJi/A0 "Perl 6 – Try It Online") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 m # match (implicitly against 「$_」) :overlap # in every single way possible :ignorecase # add a 「:」 to break up substring / (..*) # match at least one character <!{ (($0)).comb.repeated # backtrack if there were repeats }> {{}} # anon hash in code block (no-op) / .max((&chars)) # get the longest .Str # coerce to a Str (from a Match object) } ``` [Answer] # Java 8, score ~~9 (384 B)~~ 7 (401 B) ``` S -> { int s = 0 , e = 0 , l = 0 , x = 0 , y = 0 , b [ ] = new int [ 256 ] ; for ( ; x <S. length & y <S. length & l <S. length - x ; x ++ ) { b [S[x]] = 1 ; for ( y ++ ; y <S. length && b [S[y]] < 1 ; b [S[y ++]] = 1 ) ; if ( l < y - x ) { s = x ; e = y ; l = y - x ; } for ( ; y <S. length && x < y & S[x] != S[y ];)b [S[x ++]] = 0 ; } String g=""; for( ; s<e ; g+= S[s++]); return g;} ``` * ~~Initial version. Will go down from here. Score is 9 due to `"ubstring "`, so `substring` will be the first part to replace.~~ * Score is now 7 due to `" length"`, which I probably won't be able to reduce further.. I doubt it is possible to drop the four uses of `length`. If it is possible, `" eturn"` (6) might lower the score by 1 as final improvement, but I guess this is it (except maybe a small reduce in byte-count..) [Try it online.](https://tio.run/##7VTBbptAEL33K172YLEiRjaxk7bYlaqoyqmpVI42B0zWhJTsWss6NYr87c4MkLRJFClceipid9jZee/NMgw36V06NBulb65@HbIyrSp8Twt9/wEotFN2nWYKl7wEYmcLnSPzsuvULhJUMiL/ngbdlUtdkeESGnMcYgy/4J4pUNF6hGOozpad3XW27uwKCyT0rNXvBrdAOD0lT4S1sfDI7jCLA6BUOnfXwICgLxzlc8eQIAzzfUjKhhTixS5hkfETbc270SuqQRtdU/SsiW6XFNzhJfmKNRGQJqFZijX4tCzKp63Jlo1tE9k/neS12q5hGYATxNEcrIUkkm3Oj7KjhuWxEPlciOYYTFnNFM25z9CKwmUEWOW2VgN5tD9EbZk221VJZeqqdWeKK9xSvb2WcpGksqt1XTl1G5itCza040rt6SDzxIUxhDBWU/QxLqxSGsaujkTgzDl9Fl@tTWtPyubTeJtm/efqiTQFX83cEzkOTybT07OPn0Z9geNxGJ6Ek8l02hNJb0nx6AkrTVnxeD@Mdv5uUct9xEz/@/Cf9OFSLN/diS@L@mZNRXz@4@e3zxC@DdoMPekLeEtBHp8Upeh@wPvDAw) [Answer] # [Haskell](https://www.haskell.org/), score 7 *-4 thanks to Laikoni.* ``` import Data.List f s=snd $ maximum [ (0<$i ,i)|i<- tails =<<inits s, nub i==i] ``` [Try it online!](https://tio.run/##pY0xDsIwEAR7XrGKUiSSQTzA7ij5AaE4REJW2EeUcyQK/m78ADq6WWm0M4s9xxhLYVpeawZOkuVwplXcTbBgekeLJG@mLeGC7uhbwrH/0O@BLIwGBO@pzAZz0O0GhsBrSUJFwLJScz3pXF@9OOojz3VOaH5EB/2z2pQv "Haskell – Try It Online") [Answer] ## Mathematica, score ~~11~~ 9 ``` Length@Last@Select[Subsequences[Characters@#],#==DeleteDuplicates @#&]& ``` Shaving a couple of bytes off of the longest nonrepeating string by obscuring the function's name: ``` Length@Last@Select[Subsequences[Characters @#],#==( ToExpression@ StringJoin@@FromCharacterCode@{{68},{101},{108},{101},{116},{101},{68},{117}, {112},{108},{105},{99},{97},{116},{101},{115}}))@#&]& ``` [Answer] # [Kotlin](https://kotlinlang.org), score: ~~11~~ ~~10~~ 9 bytes, length: ~~227~~ ~~246~~ 245 bytes ``` indices .flatMap { p -> indices . map { p to p + it } } . filter { (r,i) -> i < length } .map { ( s , a )->substring ( s, a ) } . filter { it . groupBy { it } . none { ( k , v )->v . size>1 } } .maxBy { it.length } ``` The longest is `ubstring`, which is 9 chars It is called like this: ``` val c = "Good morning, Green orb!" fun String.c(): String? = indices .flatMap { p -> indices . map { p to p + it } } . filter { (r,i) -> i < length } .map { ( s , a )->substring ( s, a ) } . filter { it . groupBy { it } . none { ( k , v )->v . size>1 } } .maxBy { it.length } fun main(args: Array<String>) { val text = """indices .flatMap { p -> indices . map { p to p + it } } . filter { (r,i) -> i < length } .map { ( s , a )->substring ( s, a ) } . filter { it . groupBy { it } . none { ( k , v )->v . size>1 } } .maxBy { it.length }""" val message = text.c()!! println(message) println(text.length) println(message.length) println(c.c()) } ``` [Answer] # [Pyth](https://pyth.readthedocs.io), score 3 (~~18~~ 14 bytes) ``` e fq T{T .: ``` **[Try it online!](https://pyth.herokuapp.com/?code=e++fq++T%7BT++.%3A&input=%22Good+morning%2C+Green+orb%21%22&debug=0)** The longest non-repeating substrings is `.:`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes | Score: 2 ``` Œ ʒ D Ù Q } é ¤ ``` *-1 score + 7 bytes thanks to HeebyJeeby* [Try it online!](https://tio.run/##MzBNTDJM/f//6CQFhVNA7KKgcHimgkKggkItkLVSQeHQkv//DQ0NjYyMjUxMTE0B "05AB1E – Try It Online") --- # [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes | Score: 3 ``` Œ ʒ D Ù Q } é ¤ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//6CSFU5MUXBQOz1QIVKhVOLxS4dCS//8NDQ2NjIyNTExMTQE "05AB1E – Try It Online") --- # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes | Score: 8 ``` ŒʒDÙQ}é¤ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//6KRTk1wOzwysPbzy0JL//w0NDY2MjI1MTExNAQ "05AB1E – Try It Online") --- 05AB1E can actually do something rather cheap... adding whitespace into 05AB1E does nothing. If there is a rule against this, I can also use `´` and like 7 other chars. ]
[Question] [ Write a program or a function that will output a given string in a staircase fashion, writing each part of a word that starts with a vowel one line below the previous part. For example: ``` Input: Programming Puzzles and Code Golf Output: Pr P C G ogr uzzl and od olf amm es e ing ``` # Input A string containing nothing but letters and spaces. The string can be passed via `STDIN` or function arguments or anything equivalent. Letters can be lowercase or uppercase. Inputs are always assumed to follow those rules, you don't need to check for incorrect inputs. # Output Each time a vowel (that is, `a`, `e`, `i`, `o`, `u` or `y`) is encountered in a word, you must output the rest of the word on the next line (the encountered vowel included), at the correct horizontal position. This rule is recursive, which means that if there are n vowels in the word, it will be written on n+1 lines. * The vowel should be written at the beginning of the next line, and not at the end of the previous line when one is encountered. * Each word starts on the first line, and should thus be formatted independently from other words. Two words are separated by a space. * If a word starts with a vowel, you have to write it starting on the second line. # Test cases * Input: `Programming Puzzles and Code Golf` Output: ``` Pr P C G ogr uzzl and od olf amm es e ing ``` * Input: `The quick brown fox jumps over the lazy dog` Output: ``` Th q br f j th l d e u own ox umps ov e az og ick er y ``` * Input: `aeiouy` Output: ```   a e i o u y ``` * Input: `YEAh UppErcAsE VOwEls` Output: ``` V Y Upp Ow E Erc Els Ah As E ``` * Input: `If you only knew the power of the Dark Side` Output: ``` kn th p th D S If y onl ew e ow of e ark id o y er e u ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins. [Answer] # [Retina](https://github.com/mbuettner/retina), ~~50~~ ~~44~~ ~~34~~ ~~(+10)~~ ~~32~~ 30 bytes Thanks to Dennis for saving 14 bytes by using actual control characters. ``` i`[aeiouy] <VT>$0# +`#(\S*) $1<ESC>[A ``` [Based on this answer](https://codegolf.stackexchange.com/a/49118/8478), I'm using ANSI escape codes to move the terminal cursor vertically. The `<ESC>` should be replaced with the control character 0x1B, and `<VT>` with the vertical tab `0x0B`. For simpler testing, you can also replace `<ESC>` with `\e`, `<VT>` with `\v` and feed the output through `printf`. For counting purposes, each line goes in a separate file. However, for convenience it's simpler to just paste the code into a single file and invoke Retina with the `-s` option. The first replacement surrounds each vowel in `\v...#`, where the `\v` shifts the cursor downward and the `#` is a marker for the second step. The `i`` is Retina's notation for case-insensitive matching. The second step then repeatedly (`+``) removes a `#` from a word and puts a `e\[A` at the end of the word which shifts the cursor upward. This stops once the string stops changing, i.e. when there are no more `#` markers in the string. [Answer] # CJam, ~~39~~ 36 bytes ``` 0000000: 6c 7b 5f 65 6c 22 61 65 69 6f 75 79 22 l{_el"aeiouy" 000000d: 26 7b 22 1b 5b 41 22 27 0b 6f 5c 7d 26 &{".[A"'.o\}& 000001a: 5f 53 26 7b 5d 7d 26 6f 7d 2f _S&{]}&o}/ ``` The above is a reversible xxd dump, since the source code contains the unprintable character VT (code point 0x0b) and ESC (code point 0x1b). Like [this answer](https://codegolf.stackexchange.com/a/52482), it uses vertical tabs and [ANSI escape sequences](https://en.wikipedia.org/wiki/ANSI_escape_code). This requires a supporting video text terminal, which includes most non-Windows terminal emulators. ### Test run Before executing the actual code, we'll disable the prompt and clear the screen. ``` $ PS1save="$PS1" $ unset PS1 $ clear ``` This makes sure the output is shown properly. ``` echo -n Programming Puzzles and Code Golf | cjam <(xxd -ps -r <<< 6c7b5f656c226165696f757922267b221b5b4122270b6f5c7d265f53267b5d7d266f7d2f) Pr P C G ogr uzzl and od olf amm es e ing ``` To restore the prompt, execute this: ``` PS1="$PS1save" ``` ### How it works We insert a vertical tab before each vowel to move the cursor down and sufficient copies of the byte sequence **1b 5b 41** (`"\e[A"`) after each space to move the cursor back to the first row. ``` l e# Read a line from STDIN. { e# For each character C: _el e# Push lowercase(C). "aeiouy"& e# Intersect with "aeiouy". { e# If the intersection is non-empty: ".[A" e# Push "\e[A" (will be printed later). '.o e# Print "\v". \ e# Swap "\e[A" with C. }& e# _S& e# Intersect C with " ". { e# If the intersection is non-empty: ] e# Wrap the entire stack in an array. }& o e# Print C or the entire stack. }/ e# ``` [Answer] # Java, 428 bytes ``` void s(String s){int l=s.length(),m=0;char[][]c=new char[l][];for(int i=0;i<c.length;java.util.Arrays.fill(c[i++],' '))c[i]=new char[l];String v="aeiouyAEIOUY";String[]a=s.split(" ");for(int r=0,p=0;r<a.length;r++){String u=a[r]+" ";int o=v.indexOf(u.charAt(0))>=0?1:0,x=p;for(;x<u.length()-1+p;o+=v.indexOf(u.charAt(x++-~-p))>=0?1:0)c[o][x]=u.charAt(x-p);p+=u.length();m=m<o?o:m;}for(int i=0;i<=m;i++)System.out.println(c[i]);} ``` I know, it's horrible. There's probably some chars that can be shaved of, but I'm too lazy to do that. [Answer] # Perl, 31 bytes ``` 0000000: 24 5c 3d 22 1b 5b 41 22 78 20 73 2f 5b 61 $\=".[A"x s/[a 000000e: 65 69 6f 75 79 5d 2f 0b 24 26 2f 67 69 eiouy]/.$&/gi ``` The above is a reversible xxd dump, since the source code contains the unprintable character VT (code point 0x0b) and ESC (code point 0x1b). The code is 27 bytes long and requires the switches `040p` (4 bytes). The program requires a video text terminal that supports vertical tabs and [ANSI escape sequences](https://en.wikipedia.org/wiki/ANSI_escape_code), which includes most non-Windows terminal emulators. ### Test run Before executing the actual code, we'll disable the prompt and clear the screen. ``` $ PS1save="$PS1" $ unset PS1 $ clear ``` This makes sure the output is shown properly. ``` echo -n Programming Puzzles and Code Golf | perl -040pe "$(xxd -ps -r <<< 245c3d221b5b41227820732f5b6165696f75795d2f0b24262f6769)" Pr P C G ogr uzzl and od olf amm es e ing ``` To restore the prompt, execute this: ``` PS1="$PS1save" ``` ### How it works * `perl -040p` automatically reads the input as space-separated tokens (`-040`), saves each token in `$_` (`-p`) and executes the program. * `s/[aeiouy]/.$&/gi` performs a global, case-insensitive search in `$_` for vowels and replaces each vowel by the control character VT (moves the cursor down), followed by the vowel itself. * `s` returns the number of replacements it made, so `$\=".[A"x s...` saves multiple copies of the byte sequence **1b 5b 41** (moves the cursor up) in `$\`, one for each vowel. * At the end of the program, Perl automatically prints `"$_$\"`, because of the `-p` switch. [Answer] # C, ~~200~~ 190 bytes ``` i,j,k,l,M;f(char*s){M=strlen(s)+1;char t[M*M];for(;i<M*M;++i)t[i]=(i+1)%M?32:10;for(i=0;i<M-1;++i)k=(strspn(s+i,"aeiouyAEIOUY")?++j:s[i]==32?j=0:j)*M+i,l<k?l=k:0,t[k]=s[i];t[l+1]=0;puts(t);} ``` ### Ungolfed: ``` i,j,k,l,M; f(char *s){ M = strlen(s)+1; char t[M*M]; for(; i<M*M; ++i) t[i] = (i+1)%M ? 32 : 10; for(i=0; i<M-1; ++i) k = (strspn(s+i,"aeiouyAEIOUY") ? ++j : s[i]==32 ? j=0 : j) * M + i, l<k ? l=k : 0, t[k] = s[i]; t[l+1]=0; puts(t); } ``` It allocates a rectangular buffer (actually square), fills it with spaces and newlines, then traverses the given string. At the end it adds a null character to prevent trailing newlines. Technically it's not a function since it contains globals; in fact it can't be called more than once (`j` and `l` must be 0 at the start). To comply, `i,j,k,l,M;` could be moved to `int i,j=0,k,l=0,M;` at the start of the function. [Answer] # CJam, 47 Yeah, it's a bit long, but it's not "cheating" with ANSI codes :) ``` q_{_S&!\el"aeiouy"-!U+*:U}%_0|$])\zff{~@-S@?}N* ``` [Try it online](http://cjam.aditsu.net/#code=q_%7B_S%26!%5Cel%22aeiouy%22-!U%2B*%3AU%7D%25_0%7C%24%5D)%5Czff%7B~%40-S%40%3F%7DN*&input=Programming%20Puzzles%20and%20Code%20Golf) The idea is to calculate a line number for each character (starting at 0, incrementing at vowels and jumping back to 0 at space), and then for each line, repeat the string but replace the characters that have a different line number with a space. [Answer] # K, ~~81~~ ~~72~~ ~~70~~ 66 bytes Well, it's a start: ``` `0:{+{(-z)!y,x#" "}[|/s].'x,'s:,/{+\{12>"aeiouyAEIOUY"?x}'x}'(0,&~{" "?x}'x)_ x} ``` Usage Examples: ``` `0:{+{(-z)!y,x#" "}[|/s].'x,'s:,/{+\{12>"aeiouyAEIOUY"?x}'x}'(0,&~{" "?x}'x)_ x} "Programming Puzzles and Code Golf" Pr P C G ogr uzzl and od olf amm es e ing `0:{+{(-z)!y,x#" "}[|/s].'x,'s:,/{+\{12>"aeiouyAEIOUY"?x}'x}'(0,&~{" "?x}'x)_ x} "YEAh UppErcAsE VOwEls" V Y Upp Ow E Erc Els Ah As E ``` ## Edit 1: Better. Made some surface level improvements: ``` `0:{+{(-z)!y,x#" "}[|/s].'x,'s:,/{+\{12>"aeiouyAEIOUY"?x}'x}'(0,&~{" "?x}'x)_ x} `0:{+{(-z)!y,x#" "}[|/s].'x,'s:,/(+\12>?["aeiouyAEIOUY"]')'_[0,&" "=x]x} ``` Notably, I inverted the arguments for `?` when I perform the vowel search and thus eliminated the need for a lambda, did the same inversion with `_` where I split words on whitespace, and I realized that `~{" "?x}'x` is a really silly, overcomplicated way of saying `" "=x`. ## Edit 2: Another surface level tweak- negate `s` before applying it to the lambda, saving parens inside: ``` `0:{+{(-z)!y,x#" "}[|/s].'x,'s:,/(+\12>?["aeiouyAEIOUY"]')'_[0,&" "=x]x} `0:{+{z!y,x#" "}[|/s].'x,'-s:,/(+\12>?["aeiouyAEIOUY"]')'_[0,&" "=x]x} ``` ## Edit 3: OK, let's take a different approach to calculating the offset for each character. Instead of splitting the sequence at spaces and calculating a running sum (`+\`) of the positions of vowels, we can operate on the whole input string in one pass, multiplying the running sum by 0 whenever we encounter a space. I need the negation of this sequence, so I can subtract instead of adding as I scan and use number-of-distinct (`#?`) instead of max (`|/`) when I calculate the amount of vertical padding. ``` `0:{+{z!y,x#" "}[|/s].'x,'-s:,/(+\12>?["aeiouyAEIOUY"]')'_[0,&" "=x]x} `0:{+{z!y,x#" "}[#?s].'x,'s:1_0{(~" "=y)*x-12>"aeiouyAEIOUY"?y}\x} ``` That saves another 4 characters. Phew! [Answer] # Ruby: ~~135~~ ~~131~~ ~~124~~ ~~115~~ 112 characters ``` a=[] y=l=0 gets.split(r=/(?=[aeiouy ])/i).map{|w|w=~r&&y+=1 w<?A&&y=0 a[y]='%*s%s'%[-l,a[y],w] l+=w.size} puts a ``` Sample run: ``` bash-4.3$ ruby staircase.rb <<< 'Programming Puzzles and Code Golf' Pr P C G ogr uzzl and od olf amm es e ing ``` [Answer] # C, 192 bytes ``` f(char*s){int l=0,r=1,v,c;for(;r;l=1){v=l;r=0;char*p;for(p=s;*p;++p){c=*p;if(c==' ')v=l,putchar(c);else if((strchr("aoeuiyAOEUIY",c)?--v:v)<0)r=1,putchar(' ');else*p=' ',putchar(c);}puts(p);}} ``` This iterates through the string, blanking characters as it prints them. It repeats until there are no non-space characters left to print. It's portable C, making no assumptions about character encoding. ### Readable version ``` f(char *s) { int l=0, /* true if we've done the first line (no vowels) */ r=1, /* true if characters remain in buffer */ v, /* how many vowels to print from current word */ c; /* current character value */ for (l=0; r; l=1) { v = l; r = 0; char *p; for (p=s;*p;++p) { c=*p; if (c==' ') { /* a space - reset vowel counter */ v=l; putchar(c); } else if ((strchr("aoeuiyAOEUIY",c)?--v:v)<0) { /* vowel conter exceeded - print a space */ putchar(' '); r=1; } else { /* print it, and obliterate it from next line of output */ putchar(c); *p=' '; } } puts(p); /* p points at the NUL, so this just prints a newline */ } } ``` [Answer] # Python 3, 265 207 202 185 177 characters ``` i=input() w,e=i.split(" "),lambda:[[" "]*len(i)] o,x=e(),0 for p in w: y=0 for c in p: if c in"AEIOUYaeiouy":o+=e();y+=1 o[y][x],x=c,x+1 x+=1 for l in o:print("".join(l)) ``` This is terrible and I'm not proud. I know this can be made shorter, but I thought I'd post anyway. Inspired by the C version, it creates a list which is then filled while traversing the input string. [Answer] # GNU Sed, 151 + 1 (+1 as it needs the `-r` flag) ``` s/^/ /;h;s/[aoeuiy]/_/ig;:a;s/_[^ _]/__/;ta;y/_/ /;g;:x;:b;s/ [^ aoeuiy]/ /i;tb;h;s/([^ ])[aoeuiy]/\1_/ig;:c;s/_[^ _]/__/;tc;y/_/ /;g;s/ [^ ]/ /ig;tx ``` I thought that sed would be the tool for this job, but found it surprisingly hard. ### Readable version: ``` #!/bin/sed -rf # make sure the string starts with a space s/^/ / h # print leading consonants, if any s/[aoeuiy]/_/ig :a s/_[^ _]/__/ ta y/_/ / p g :x # strip the consonants just printed :b s/ [^ aoeuiy]/ /i tb h s/([^ ])[aoeuiy]/\1_/ig :c s/_[^ _]/__/ tc y/_/ / p g # remove leading vowel of each word s/ [^ ]/ /ig tx ``` [Answer] # Python 2, ~~145~~ 142 Bytes Probably isn't as competitive as some other methods, but I thought this was a cool way of using regex. ``` import re;s=I=input()[::-1]+" ";i=0 while s.strip()or i<2:s=re.sub("(?!([^aeiouy ]*[aeiouy]){%s}[^aeiouy]* )."%i," ",I,0,2)[::-1];print s;i+=1 ``` The regex `(?!([^aeiouy ]*[aeiouy]){N}[^aeiouy]* ).` matches any single character *not* within the N-th group of letters from the end of a word. Since it counts from the end of the world I reverse the string before and afterward, and I also have to add a space at the end, but after that it becomes a simple matter of using `re.sub` to replace every instance of these characters with a space. It does this for every value of N until the string is empty. [Answer] # Octave, 132 129 characters ``` p=1;x=[];y=input(0);for j=1:numel(y);if regexpi(y(j),'[aeiouy]');p+=1;elseif y(j)==" ";p=1;end;x(p,j)=y(j);end;x(x==0)=32;char(x) ``` ### Test **Input:** `"YEAh UppErcAsE VOwEls"` **Output:** ``` V Y Upp Ow E Erc Els Ah As E ``` [Answer] # [Gema](http://gema.sourceforge.net/): ~~53~~ 48 characters ``` /[aeiouyAEIOUY]/=@append{u;^[[A}^K$1 = $u@set{u;} ``` Note that `^[` (x1b) and `^K` (x0b) are single characters. (In the below sample run I use their copy-paste friendly `\e` and `\v` equivalents, in case you want to try it out.) Sample run: ``` bash-4.3$ gema '/[aeiouyAEIOUY]/=@append{u;\e[A}\v$1; = $u@set{u;}' <<< 'Programming Puzzles and Code Golf' Pr P C G ogr uzzl and od olf amm es e ing ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 42 bytes ``` Ḳµe€Øyœṗ⁸⁶ṁ$;¥\z⁶Zµ€µḷ/⁶ṁW⁸;ḣ®µ€L€Ṁ©$¡ZK€Y ``` [Try it online!](https://tio.run/##y0rNyan8///hjk2HtqY@alpzeEbl0ckPd05/1LjjUeO2hzsbVawPLY2pArKjDm0Fyh/a@nDHdn2IVDhQkfXDHYsPrQNL@QDxw50Nh1aqHFoY5Q3kRP7//z@gKD@9KDE3NzMvXSGgtKoqJ7VYITEvRcE5PyVVwT0/Jw0A "Jelly – Try It Online") Why Jelly, why? :-( ]
[Question] [ > > **This contest is over.** > > > Due to the nature of [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenges, the cops challenge becomes a lot easier when the interest in the associated robbers challenge has diminished. Therefore, while you can still post hash functions, your answer will not get accepted or form part of the leaderboard. > > > This challenge is a search for the shortest implementation of a [hash function](http://en.wikipedia.org/wiki/Cryptographic_hash_function "Cryptographic hash function - Wikipedia, the free encyclopedia") that is [collision resistant](http://en.wikipedia.org/wiki/Collision_resistance "Collision resistance - Wikipedia, the free encyclopedia"), i.e., it should be infeasible to find two different messages with the same hash. As a cop, you try to invent and implement a hash function finding the best compromise between code size and collision resistance. Use too many bytes and another cop will outgolf you! As a robber, you try to foil the cops' attempts by cracking their functions, proving that they are unsuitable. This will force them to use more bytes to strengthen their algorithms! ## Cops challenge ### Task Implement a cryptographic hash function **H : I -> O** of your choice, where **I** is the set of all non-negative integers below 2230 and **O** is the set of all non-negative integers below 2128. You can either implement **H** as an actual function that accepts and returns a single integer, a string representation of an integer or an array of integers or a full program that reads from STDIN and prints to STDOUT in base 10 or 16. ### Scoring * **H** that it has to resist the *robbers challenge* defined below. If a robber defeats your submission in the first 168 hours after posting it, it is considered *cracked*. * The implementation of **H** should be as short as possible. *The shortest uncracked submission will be the winner of the cops challenge.* ### Additional rules * If you implement **H** as a function, please provide a wrapper to execute the function from within a program that behaves as explained above. * Please provide at least three test vectors for your program or wrapper (example inputs and their corresponding outputs). * **H** can be your novel design (preferred) or a well-known algorithm, as long as you implement it yourself. It is forbidden to use any kind in-built hash function, compression function, cipher, PRNG, etc. Any built-in commonly used to *implement* hashing functions (e.g., base conversion) is fair game. * The output of your program or function must be deterministic. * There should be a free (as in beer) compiler/interpreter that can be run on a x86 or x64 platform or from within a web browser. * Your program or function should be reasonably efficient and has to hash any message in **I** below 2219 in less than a second. For edge cases, the (wall) time taken on my machine (Intel Core i7-3770, 16 GiB of RAM) will be decisive. * Given the nature of this challenge, it is forbidden to change the code of your answer in any way, whether it alters the output or not. If your submission has been cracked (or even if it hasn't), you can post an additional answer. If your answer is invalid (e.g., it doesn't comply with the I/O specification), please delete it. ### Example > > # Python 2.7, 22 bytes > > > > ``` > def H(M): > return M%17 > > ``` > > ### Wrapper > > > > ``` > print H(int(input())) > > ``` > > ## Robbers challenge ### Task Crack any of the cops' submissions by posting the following in the [robbers' thread](https://codegolf.stackexchange.com/q/51069): two messages **M** and **N** in **I** such that **H(M) = H(N)** and **M ≠ N**. ### Scoring * Cracking each cop submissions gains you one point. The robber with the most points wins. In the case of a tie, the tied robber that cracked the longest submission wins. ### Additional rules * Every cop submission can only be cracked once. * If a cop submission relies on implementation-defined or undefined behavior, you only have to find a crack that works (verifiably) on your machine. * Each crack belongs to a separate answer in the robbers' thread. * Posting an invalid cracking attempt bans you from cracking that particular submission for 30 minutes. * You may not crack your own submission. ### Example > > # Python 2.7, 22 bytes by user8675309 > > > > ``` > 1 > > ``` > > and > > > > ``` > 18 > > ``` > > # Leaderboard ### Safe submissions 1. [CJam, 21 bytes by eBusiness](https://codegolf.stackexchange.com/a/51210) 2. [C++, 148 bytes by tucuxi](https://codegolf.stackexchange.com/a/51155) 3. [C++, 233(?) bytes by Vi.](https://codegolf.stackexchange.com/a/51089) ### Uncracked submissions You can use this Stack Snippet to get a list of not yet cracked answers. ``` function g(p){$.getJSON('//api.stackexchange.com/2.2/questions/51068/answers?page='+p+'&pagesize=100&order=desc&sort=creation&site=codegolf&filter=!.Fjs-H6J36w0DtV5A_ZMzR7bRqt1e',function(s){s.items.map(function(a){var h=$('<div/>').html(a.body).children().first().text();if(!/cracked/i.test(h)&&(typeof a.comments=='undefined'||a.comments.filter(function(b){var c=$('<div/>').html(b.body);return /^cracked/i.test(c.text())||c.find('a').filter(function(){return /cracked/i.test($(this).text())}).length>0}).length==0)){var m=/^\s*((?:[^,(\s]|\s+[^-,(\s])+)\s*(?:[,(]|\s-).*?([0-9]+)/.exec(h);$('<tr/>').append($('<td/>').append($('<a/>').text(m?m[1]:h).attr('href',a.link)),$('<td class="score"/>').text(m?m[2]:'?'),$('<td/>').append($('<a/>').text(a.owner.display_name).attr('href',a.owner.link))).appendTo('#listcontent');}});if(s.length==100)g(p+1);});}g(1); ``` ``` table th, table td {padding: 5px} th {text-align: left} .score {text-align: right} table a {display:block} ``` ``` <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"><table><tr><th>Language</th><th class="score">Length</th><th>User</th></tr><tbody id="listcontent"></tbody></table> ``` [Answer] # Python, 109 bytes [[cracked](https://codegolf.stackexchange.com/a/51084/8478), [and again](https://codegolf.stackexchange.com/a/51086/4162)] ``` def f(n,h=42,m=2**128): while n:h+=n&~-m;n>>=128;h+=h<<10;h^=h>>6;h%=m h+=h<<3;h^=h>>11;h+=h<<15;return h%m ``` I tried implementing [Jenkins' one-at-a-time](http://en.wikipedia.org/wiki/Jenkins_hash_function) function as-is, with the only difference being the seed and the number of bits. Fun fact: Apparently [Perl used the Jenkins' hash at some point](https://stackoverflow.com/questions/11214270/what-hashing-function-algorithm-does-perl-use). ## Wrapper ``` print(f(int(input()))) ``` ## Examples ``` >>> f(0) 12386682 >>> f(1) 13184902071 >>> f(2**128-1) 132946164914354994014709093274101144634 >>> f(2**128) 13002544814292 >>> f(2**128+1) 13337372262951 >>> f(2**(2**20)) 290510273231835581372700072767153076167 ``` [Answer] # CJam, 21 bytes ``` 1q3*{i+_E_#*^26_#)%}/ ``` Takes a string of bytes as input. In pseudocode: ``` hash = 1 3 times: for i in input: hash = hash + i hash = hash xor hash * 14^14 hash = hash mod (26^26 + 1) output hash ``` Example hashes: "" (empty string) -> 1 "Test" -> 2607833638733409808360080023081587841 "test" -> 363640467424586895504738713637444713 It may be a bit on the simple side, the output range is only a little more than 122 bits, the triple iteration strengthening is already a bit broken as it does exactly the same thing every time, so input that hash to 1 in the first iteration will be a full break. But it is short, and there is no fun in being too safe. [Answer] # C++, 148 bytes ``` typedef __uint128_t U;U h(char*b,U n,U&o){U a=0x243f6a8885a308d,p=0x100000001b3;for(o=a;n--;)for(U i=27;--i;){o=(o<<i)|(o>>(128-i));o*=p;o^=b[n];}} ``` [\_\_uint128\_t](https://gcc.gnu.org/onlinedocs/gcc/_005f_005fint128.html#g_t_005f_005fint128) is a GCC extension, and works as expected. The hash is based on iterating [FNV hash](http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function) (I've borrowed their prime, although `a` is the first digits of Pi in hex) with a [sha1-like](https://code.google.com/p/smallsha1/source/browse/trunk/sha1.cpp?spec=svn2&r=2) rotation at the start of each iteration. Compiling with `-O3`, hashing a 10MB file takes under 2 seconds, so there is still margin for upping the iterations in the inner loop - but I'm feeling generous today. De-uglified (changed variable names, added comments, whitespace and a pair of braces) for your cracking pleasure: ``` typedef __uint128_t U; U h(char* input, U inputLength, U &output){ U a=0x243f6a8885a308d,p=0x100000001b3; for(output=a;inputLength--;) { // initialize output, consume input for(U i=27;--i;) { // evil inner loop output = (output<<i)|(output>>(128-i)); // variable roll output *= p; // FNV hash steps output ^= input[inputLength]; } } // computed hash now available in output } ``` Golfing suggestions are welcome (even if I don't get to improve the code based on them). **edit:** fixed typos in de-uglified code (golfed version remains unchanged). [Answer] # CJam, 44 bytes [[cracked](https://codegolf.stackexchange.com/a/51169/25180)] ``` lW%600/_z]{JfbDbGK#%GC#[md\]}%z~Bb4G#%\+GC#b ``` Input is in base 10. CJam is slow. I hope it runs in 1 second in some computer... ### Explanations ``` lW%600/ e# Reverse, and split into chunks with size 600. _z e# Duplicate and swap the two dimensions. ]{ e# For both versions or the array: JfbDb e# Sum of S[i][j]*13^i*19^j, where S is the character values, e# and the indices are from right to left, starting at 0. GK#%GC#[md\] e# Get the last 32+48 bits. }% z~ e# Say the results are A, B, C, D, where A and C are 32 bits. Bb4G#% e# E = the last 32 bits of A * 11 + C. \+GC#b e# Output E, B, D concatenated in binary. ``` Well, the two dimensional things seemed to be a weakness... It was intended to make some slow calculations faster at the beginning. But it cannot run in a second no matter what I do, so I removed the slow code finally. It should be also better if I have used binary bits and higher bases. ## C version ``` __uint128_t hash(unsigned char* s){ __uint128_t a=0,b=0; __uint128_t ar=0; __uint128_t v[600]; int l=0,j=strlen(s); memset(v,0,sizeof v); for(int i=0;i<j;i++){ if(i%600) ar*=19; else{ a=(a+ar)*13; ar=0; } if(i%600>l) l=i%600; v[i%600]=v[i%600]*19+s[j-i-1]; ar+=s[j-i-1]; } for(int i=0;i<=l;i++) b=b*13+v[i]; a+=ar; return (((a>>48)*11+(b>>48))<<96) +((a&0xffffffffffffull)<<48) +(b&0xffffffffffffull); } ``` [Answer] ## C++, 182 characters (+ about 51 characters of boilerplate) ``` h=0xC0CC3051F486B191;j=0x9A318B5A176B8125;char q=0;for(int i=0;i<l;++i){char w=buf[i];h+=((w<<27)*257);j^=(h+0x5233);h+=0xAA02129953CC12C3*(j>>32);j^=(w+0x134)*(q-0x16C552F34);q=w;} ``` Boilerplate: ``` void hash(const unsigned char* buf, size_t len, unsigned long long *hash1, unsigned long long *hash2) { unsigned long long &h=*hash1; unsigned long long &j=*hash2; size_t l = len; const unsigned char* b = buf; // code here } ``` ## Runnable program with a golfed function ``` #include <stdio.h> // The next line is 227 characters long int hash(char*b,int l,long long&h,long long&j){h=0xC0CC3051F486B191;j=0x9A318B5A176B8125;char q=0;for(int i=0;i<l;++i){char w=b[i];h+=((w<<27)*257);j^=(h+0x5233);h+=0xAA02129953CC12C3*(j>>32);j^=(w+0x134)*(q-0x16C552F34);q=w;}} int main() { char buf[1024]; int l = fread(buf, 1, 1024, stdin); long long q, w; hash(buf, l, q, w); printf("%016llX%016llX\n", q, w); } ``` [Answer] # Pyth, 8 [Cracked](https://codegolf.stackexchange.com/a/51075/31625) ``` sv_`.lhQ ``` [Try it online](https://pyth.herokuapp.com/?code=sv_%60.lhQ&input=123456789&debug=0) A bit of a silly answer, I'll explain how it works because most people can't read Pyth. This takes the natural log of one plus the input, and then converts that to a string. That string is reversed, and then evaluated and then converted to an integer. A python translation would look like: ``` import math n = eval(input()) + 1 rev = str(math.log(n))[::-1] print(int(eval(rev))) ``` [Answer] # Python 3, 216 bytes [[cracked](https://codegolf.stackexchange.com/a/51134/21487)] ``` def f(m): h=1;p=[2]+[n for n in range(2,102)if 2**n%n==2];l=len(bin(m))-2;*b,=map(int,bin((l<<(l+25)//26*26)+m)[2:]) while b: h*=h for P in p: if b:h=h*P**b.pop()%0xb6ee45a9012d1718f626305a971e6a21 return h ``` Due to an incompatibility with the spec I can think of at least one *slight* vulnerability, but other than that I think this is at least brute-force proof. I've checked the first 10 million hashes, among other things. In terms of golf this would be shorter in Python 2, but I've sacrificed some bytes for efficiency (since it's probably not going to win anyway). Edit: This was my attempt at implementing the [Very Smooth Hash](http://en.wikipedia.org/wiki/Very_smooth_hash), but unfortunately 128-bits was far too small. ## Wrapper ``` print(f(int(input()))) ``` ## Examples ``` >>> f(0) 2 >>> f(123456789) 228513724611896947508835241717884330242 >>> f(2**(2**19)-1) 186113086034861070379984115740337348649 >>> f(2**(2**19)) 1336078 ``` ## Code explanation ``` def f(m): h=1 # Start hash at 1 p=[2]+[n for n in range(2,102)if 2**n%n==2] # p = primes from 2 to 101 l=len(bin(m))-2 # l = bit-length of m (input) *b,=map(int,bin((l<<(l+25)//26*26)+m)[2:]) # Convert bits to list, padding to # a multiple of 26 then adding the # bit-length at the front while b: # For each round h*=h # Square the hash for P in p: # For each prime in 2 ... 101 if b:h=(h*P**b.pop() # Multiply by prime^bit, popping # the bit from the back of the list %0xb6ee45a9012d1718f626305a971e6a21) # Take mod large number return h # Return hash ``` An example of the padding for `f(6)`: ``` [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0] (len 3)(------------------ 23 zeroes for padding -------------------------)(input 6) (---------------------------- length 26 total ------------------------------) ``` [Answer] # C, 87 bytes [[cracked](https://codegolf.stackexchange.com/a/51174/11006)] This is the complete program; no wrapper required. Accepts binary input via stdin, and outputs a hexadecimal hash to stdout. ``` c;p;q;main(){while((c=getchar())+1)p=p*'foo+'+q+c,q=q*'bar/'+p;printf("%08x%08x",p,q);} ``` This only calculates a 64-bit hash, so I'm taking a bit of a gamble here. In case anyone's wondering, the two constants `'foo+'` and `'bar/'` are the prime numbers 1718578987 and 1650553391. --- ### Examples: Ignores leading zeroes: ``` echo -ne '\x00\x00\x00\x00' |./hash 0000000000000000 ``` Single-byte inputs: ``` echo -ne '\x01' |./hash 0000000100000001 echo -ne '\xff' |./hash 000000ff000000ff ``` Multi-byte inputs: ``` echo -ne '\x01\x01' |./hash 666f6f2dc8d0e15c echo -ne 'Hello, World' |./hash 04f1a7412b17b86c ``` [Answer] # J - 39 bytes - [cracked](https://codegolf.stackexchange.com/a/51093/5138) Function taking a string as input and returning an integer < 2128. I am assuming we have to name our function to be valid, so drop another 3 chars from the count if we can submit anonymous functions. ``` H=:_8(".p:@+5,9:)a\(a=.(2^128x)&|@^/@)] ``` For those of you that don't read hieroglyphics, here's a rundown of what I'm doing. * `a=.(2^128x)&|@^/@` This is a subroutine\* which takes an array of numbers, and then treats it as a power tower, where exponentiation is taken mod 2128. By "power tower", I mean if you gave it the input `3 4 5 6`, it would calculate `3 ^ (4 ^ (5 ^ 6))`. * `(".p:@+5,9:)a` This function takes a string, converts it to the number *N*, and then calculates the (*n*+5)-th and (*n*+9)-th prime numbers, and then throws the `a` from before on it. That is, we find `p(n+5) ^ p(n+9)` mod 2128 where `p(k)` is the `k`-th prime. * `H=:_8...\(a...)]` Perform the above function on 8-character subblocks of the input, and then `a` all the results together and call the resulting hash function `H`. I use 8 characters because J's "`k`-th prime" function fails when `p(k)` > 231, i.e. `k=105097564` is the largest safe `k`. Have some sample outputs. You can try this yourself online at [tryj.tk](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=H%3D%3A_8%28%22.p%3A%40%2B5%2C9%3A%29a%5C%28a%3D.%282%5E128x%29%26%7C%40%5E%2F%40%29%5D), but I really recommend doing this at home by downloading the interpreter from [Jsoftware](http://www.jsoftware.com/stable.htm). ``` H=:_8(".p:@+5,9:)a\(a=.(2^128x)&|@^/@)] H '88' 278718804776827770823441490977679256075 H '0' 201538126434611150798503956371773 H '1' 139288917338851014461418017489467720433 H '2' 286827977638262502014244740270529967555 H '3' 295470173585320512295453937212042446551 30$'0123456789' NB. a 30 character string 012345678901234567890123456789 H 30$'0123456789' 75387099856019963684383893584499026337 H 80$'0123456789' 268423413606061336240992836334135810465 ``` \* Technically, it's not a function in and of itself, it attaches to other functions and acts on their output. But this is a semantic issue of J, not a conceptual difference: the program flow is as I described it above. [Answer] # Python 3, 118 bytes [[cracked](https://codegolf.stackexchange.com/questions/51069/cryptographic-hash-golf-robbers/51160#51160)] ``` def H(I): o=0;n=3;M=1<<128 for c in I:i=ord(c);o=(o<<i^o^i^n^0x9bb90058bcf52d3276a7bf07bcb279b7)%M;n=n*n%M return o ``` Indentation is a single tab. Simple hash, haven't really tested it thoroughly yet. Call as follows: ``` print(H("123456789")) ``` result: `73117705077050518159191803746489514685` [Answer] # C++, 239 bytes My very first code golf! [*Please be gentle*] ``` #define r(a,b) ((a<<b)|(a>>(64-b))) typedef uint64_t I;I f(I*q, I n, I&h){h=0;for(I i=n;--i;)h=r(h^(r(q[i]*0x87c37b91114253d5,31)*0x4cf5ad432745937f),31)*5+0x52dce729;h^=(h>>33)*0xff51afd7ed558ccd;h^=(h>>33)*0xc4ceb9fe1a85ec53;h^=(h>>33);} ``` Ungolfed version: ``` I f(I* q, I n, I& h) // input, length and output { h = 0; // initialize hashes for (I i=n;--i;) { q[i] *= 0x87c37b91114253d5; q[i] = rotl(q[i], 31); q[i] *= 0x4cf5ad432745937f; h ^= q[i]; // merge the block with hash h *= rotl(h, 31); h = h * 5 + 0x52dce729; } h ^= h>>33; h *= 0xff51afd7ed558ccd; h ^= h>>33; h *= 0xc4ceb9fe1a85ec53; // avalanche! h ^= h>>33; } ``` Not the best hash, and definitely not the shortest code in existence. Accepting golfing tips and hoping to improve! ## Wrapper Probably not the best in the world, but a wrapper nonetheless ``` I input[500]; int main() { string s; getline(cin, s); memcpy(input, s.c_str(), s.length()); I output; f(input, 500, output); cout << hex << output << endl; } ``` [Answer] # Java, ~~299~~ ~~291~~ 282 bytes, [cracked.](https://codegolf.stackexchange.com/questions/51069/cryptographic-hash-golf-robbers/51088#51088) ``` import java.math.*;class H{public static void main(String[]a){BigInteger i=new java.util.Scanner(System.in).nextBigInteger();System.out.print(BigInteger.valueOf(i.bitCount()*i.bitLength()+1).add(i.mod(BigInteger.valueOf(Long.MAX_VALUE))).modPow(i,BigInteger.valueOf(2).pow(128)));}} ``` Does some operations on BigIntegers, then takes the result modulo 2128. [Answer] # C, 128 bytes [[cracked](https://codegolf.stackexchange.com/a/51216/11006)] ``` p;q;r;s;main(c){while((c=getchar())+1)p=p*'foo+'+s^c,q=q*'bar/'+p,r=r*'qux3'^q,s=s*'zipO'+p;printf("%08x%08x%08x%08x",p,q,r,s);} ``` This is more or less the same algorithm as [my last effort](https://codegolf.stackexchange.com/a/51146/11006) [(cracked by Vi.)](https://codegolf.stackexchange.com/a/51174/11006), but now has enough hamster wheels to generate proper 128-bit hashes. The four prime constants in the code are as follows: ``` 'foo+' = 1718578987 'bar/' = 1650553391 'qux3' = 1903523891 'zipO' = 2053730383 ``` As before, this is a complete program with no need for a wrapper. The integer **I** is input via stdin as raw binary data (big-endian), and the hash **O** is printed in hex to stdout. Leading zeroes in **I** are ignored. ## Examples: ``` echo -ne '\x00' |./hash 00000000000000000000000000000000 echo -ne '\x00\x00' |./hash 00000000000000000000000000000000 echo -ne '\x01' |./hash 00000001000000010000000100000001 echo -ne 'A' |./hash 00000041000000410000004100000041 echo -ne '\x01\x01' |./hash 666f6f2dc8d0e15cb9a5996fe0d8df7c echo -ne 'Hello, World' |./hash da0ba2857116440a9bee5bb70d58cd6a ``` [Answer] # C, 122 bytes [[cracked](https://codegolf.stackexchange.com/a/51354/101)] ``` long long x,y,p;main(c){for(c=9;c|p%97;c=getchar()+1)for(++p;c--;)x=x*'[3QQ'+p,y^=x^=y^=c*x;printf("%016llx%016llx",x,y);} ``` Nested loops, half-assed LCGs, and variable swapping. What's not to love? Here's a ungolf'd version to play around with: ``` long long x,y,p; int main(int c){ // Start with a small number of iterations to // get the state hashes good and mixed because initializing takes space // Then, until we reach the end of input (EOF+1 == 0) // and a position that's a multiple of 97 for (c=9;c|p%97;c=getchar()+1) { // For each input c(haracter) ASCII value, iterate down to zero for (++p;c--;) { // x will act like a LCG with a prime multiple // partially affected by the current input position // The string '[3QQ' is the prime number 0x5B335151 x=x*'[3QQ'+p; // Mix the result of x with the decrementing character y^=c*x; // Swap the x and y buffers y^=x^=y; } } // Full 128-bit output printf("%016llx%016llx",x,y); return 0; } ``` This is a fully self-contains program that reads from STDIN and prints to STDOUT. Example: ``` > echo -n "Hello world" | ./golfhash b3faef341f70c5ad6eed4c33e1b55ca7 > echo -n "" | ./golfhash 69c761806803f70154a7f816eb3835fb > echo -n "a" | ./golfhash 5f0e7e5303cfcc5ecb644cddc90547ed > echo -n "c" | ./golfhash e64e173ed4415f7dae81aae0137c47e5 ``` In some simple benchmarks, it hashes around 3MB/s of text data. The hash speed depends on the input data itself, so that should probably be taken into consideration. [Answer] # PHP 4.1, 66 bytes [[cracked](https://codegolf.stackexchange.com/a/51121/14732)] I'm just warming up. I hope you find this insteresting. ``` <?for($l=strlen($b.=$a*1);$i<40;$o.=+$b[+$i]^"$a"/$a,$i++);echo$o; ``` I've tried it numbers as large as 999999999999999999999999999. The output seemed to be within the 2128 range. --- PHP 4.1 is required because of the [`register_globals`](http://php.net/manual/en/ini.core.php#ini.register-globals) directive. It works by automatically creating local variables from the session, POST, GET, REQUEST and cookies. It uses the key `a`. (E.G.: access over `http://localhost/file.php?a=<number>`). If you want to test it with PHP 4.2 and newer, try this: ``` <?for($l=strlen($b.=$a=$_REQUEST['a']*1);$i<40;$o.=+$b[+$i]^"$a"/$a,$i++);echo$o; ``` This version only works with POST and GET. --- Example output: ``` 0 -> 0000000000000000000000000000000000000000 9 -> 8111111111111111111111111111111111111111 9999 -> 8888111111111111111111111111111111111111 1234567890 -> 0325476981111111111111111111111111111111 99999999999999999999999999999999999999999999999999999999999999999999999999999999 -> 0111191111111111111111111111111111111111 ``` (I assure you that there are numbers that produce the same hash). [Answer] # **C, 134 bytes, [Cracked](https://codegolf.stackexchange.com/a/51095/11006)** This is complete C program. ``` long long i=0,a=0,e=1,v,r;main(){for(;i++<323228500;r=(e?(scanf("%c",&v),e=v>'/'&&v<':',v):(a=(a+1)*7)*(7+r)));printf("0x%llx\n", r);} ``` What it does: The idea is to take input as byte array and append pseudo random (but deterministic) bytes at the end to make the length equal to about 2230 (a bit more). The implementation reads input byte by byte and starts using pseudo random data when it finds the first character that isn't a digit. As builtin PRNG isn't allowed I implemented it myself. There is undefined/implementation defined behavior that makes the code shorter (the final value should be unsigned, and I should use different types for different values). And I couldn't use 128 bit values in C. Less obfuscated version: ``` long long i = 0, prand = 0, notEndOfInput = 1, in, hash; main() { for (; i++ < 323228500;) { if (notEndOfInput) { scanf("%c", &in); notEndOfInput = in >= '0' && in <= '9'; hash = in; } else { prand = (prand + 1)*7; hash = prand*(7 + hash); } } printf("0x%llx\n", hash); } ``` [Answer] **Python 2.X - 139 bytes** [[[Cracked](https://codegolf.stackexchange.com/a/51180/36885)]] This is quite similar to all the other (LOOP,XOR,SHIFT,ADD) hashes out here. Come get your points robbers ;) I'll make a harder one after this one is solved. ``` M=2**128 def H(I): A=[1337,8917,14491,71917];O=M-I%M for z in range(73): O^=A[z%4]**(9+I%9);O>>=3;O+=9+I**(A[z%4]%A[O%4]);O%=M return O ``` Wrapper (expects one argument in base-16 also known as hexadecimal): ``` import sys if __name__ == '__main__': print hex(H(long(sys.argv[1], 16)))[2:][:-1].upper() ``` [Answer] **Python 2.7 - 161 bytes [[[Cracked](https://codegolf.stackexchange.com/a/51197/25180 "Cracked")]]** Well since I managed to change my first hash function into an useless version before posting it, I think I will post another version of a similar structure. This time I tested it against trivial collisions and I tested most of the possible input magnitudes for speed. ``` A=2**128;B=[3,5,7,11,13,17,19] def H(i): o=i/A for r in range(9+B[i%7]): v=B[i%7];i=(i+o)/2;o=o>>v|o<<128-v;o+=(9+o%6)**B[r%6];o^=i%(B[r%6]*v);o%=A return o ``` Wrapper (not counted in the bytecount) ``` import sys if __name__ == '__main__': arg = long(sys.argv[1].strip(), 16) print hex(H(arg))[2:][:-1].upper() ``` Run example (input is always a hexadecimal number): ``` $ python crypt2.py 1 3984F42BC8371703DB8614A78581A167 $ python crypt2.py 10 589F1156882C1EA197597C9BF95B9D78 $ python crypt2.py 100 335920C70837FAF2905657F85CBC6FEA $ python crypt2.py 1000 B2686CA7CAD9FC323ABF9BD695E8B013 $ python crypt2.py 1000AAAA 8B8959B3DB0906CE440CD44CC62B52DB ``` [Answer] # Ruby, 90 Bytes ``` def H(s);i=823542;s.each_byte{|x|i=(i*(x+1)+s.length).to_s.reverse.to_i%(2**128)};i;end ``` A highly random hash algorithm I made up without looking at any real hashes...no idea if it is good. it takes a string as input. ### Wrapper: ``` def buildString(i) if(i>255) buildString(i/256)+(i%256).chr else i.chr end end puts H buildString gets ``` [Answer] # Mathematica, 89 bytes, [cracked](https://codegolf.stackexchange.com/a/51081/8478) ``` Last@CellularAutomaton[(a=Mod)[#^2,256],{#~IntegerDigits~2,0},{#~a~99,128}]~FromDigits~2& ``` Not the shortest. [Answer] # PHP, 79 Bytes (cracked. With a comment): ``` echo (('.'.str_replace('.',M_E*$i,$i/pi()))*substr(pi(),2,$i%20))+deg2rad($i); ``` This does alot of scary things via type-conversions in php, which makes it hard to predict ;) (or at least I hope so). It's not the shortest or most unreadable answer, however. To run it you can use [PHP4 and register globals](https://codegolf.stackexchange.com/a/51118/32753) (with ?i=123) or use the commandline: ``` php -r "$i = 123.45; echo (('.'.str_replace('.',M_E*$i,$i/pi()))*substr(pi(),2,$i%20))+deg2rad($i);" ``` [Answer] # C# - 393 bytes [cracked](https://codegolf.stackexchange.com/a/51277/11180) ``` using System;class P{static void Main(string[]a){int l=a[0].Length;l=l%8==0?l/8:l/8+1;var b=new byte[l][];for(int i=0;i<l;i++){b[i]=new byte[8];};int j=l-1,k=7;for(int i=0;i<a[0].Length;i++){b[j][k]=Convert.ToByte(""+a[0][i],16);k--;if((i+1)%8==0){j--;k=7;}}var c=0xcbf29ce484222325;for(int i=0;i<l;i++){for(int o=0;o<8;o++){c^=b[i][o];c*=0x100000001b3;}}Console.WriteLine(c.ToString("X"));}} ``` Ungolfed: ``` using System; class P { static void Main(string[]a) { int l = a[0].Length; l = l % 8 == 0 ? l / 8 : l / 8 + 1; var b = new byte[l][]; for (int i = 0; i < l; i++) { b[i] = new byte[8]; }; int j = l-1, k = 7; for (int i = 0; i < a[0].Length; i++) { b[j][k] = Convert.ToByte(""+a[0][i], 16); k--; if((i+1) % 8 == 0) { j--; k = 7; } } var c = 0xcbf29ce484222325; for (int i = 0; i < l; i++) { for (int o = 0; o < 8; o++) { c ^= b[i][o]; c *= 0x100000001b3; } } Console.WriteLine(c.ToString("X")); } } ``` I have never touched cryptography or hashing in my life, so be gentle :) It's a simple implementation of an [FNV-1a](http://www.isthe.com/chongo/tech/comp/fnv/index.html) hash with some array pivoting on the input. I am sure there is a better way of doing this but this is the best I could do. It might use a bit of memory on long inputs. [Answer] # Python 2, 115 bytes [[Cracked already!](https://codegolf.stackexchange.com/a/51316/25180)] OK, here's my last effort. Only 115 bytes because the final newline isn't required. ``` h,m,s=1,0,raw_input() for c in[9+int(s[x:x+197])for x in range(0,len(s),197)]:h+=pow(c,257,99**99+52) print h%4**64 ``` This is a complete program that inputs a decimal integer on stdin and prints a decimal hash value on stdout. Extra leading zeroes will result in different hash values, so I'll just assume that the input doesn't have any. This works by stuffing 197-digit chunks of the input number through a modular exponentiation. Unlike some languages, the `int()` function always defaults to base 10, so `int('077')` is 77, not 63. ### Sample outputs: ``` $ python hash.py <<<"0" 340076608891873865874583117084537586383 $ python hash.py <<<"1" 113151740989667135385395820806955292270 $ python hash.py <<<"2" 306634563913148482696255393435459032089 $ python hash.py <<<"42" 321865481646913829448911631298776772679 $ time python hash.py <<<`python <<<"print 2**(2**19)"` 233526113491758434358093601138224122227 real 0m0.890s <-- (Close, but fast enough) user 0m0.860s sys 0m0.027s ``` ]
[Question] [ Now that everyone has developed their (often amazing) low level coding expertise for [How slow is Python really? (Or how fast is your language?)](https://codegolf.stackexchange.com/questions/26323/how-slow-is-python-really-or-how-fast-is-your-language) and [How Slow Is Python Really (Part II)?](https://codegolf.stackexchange.com/questions/26371/how-slow-is-python-really-part-ii) it is time for a challenge which will also stretch your ability to improve an algorithm. The following code computes a list of length 9. Position `i` in the list counts the number of times at least `i` consecutive zeros were found when computing the inner products between `F` and `S`. To do this exactly, it iterates over all possible lists `F` of length `n` and lists `S` of length `n+m-1`. ``` #!/usr/bin/python import itertools import operator n=8 m=n+1 leadingzerocounts = [0]*m for S in itertools.product([-1,1], repeat = n+m-1): for F in itertools.product([-1,1], repeat = n): i = 0 while (i<m and sum(map(operator.mul, F, S[i:i+n])) == 0): leadingzerocounts[i] +=1 i+=1 print leadingzerocounts ``` The output is > > [4587520, 1254400, 347648, 95488, 27264, 9536, 4512, 2128, 1064] > > > If you increase n to 10,12,14,16,18,20 using this code it very rapidly becomes far too slow. **Rules** * The challenge is to give the correct output for as large an n as possible. Only even values of n are relevant. * If there is a tie, the win goes to the fastest code on my machine for the largest n. * I reserve the right not to test code that takes more than 10 minutes. * You may change the algorithm in any way you like as long as it gives the correct output. In fact **you will have to** change the algorithm to make any decent progress toward winning. * The winner will be awarded one week from when the question was set. * The bounty will be awarded when it is due which is a little after when the winner will be awarded. **My Machine** The timings will be run on my machine. This is a standard ubuntu install on an AMD FX-8350 Eight-Core Processor. This also means I need to be able to run your code. As a consequence, only use easily available free software and please include full instructions how to compile and run your code. **Status**. * **C**. n = 12 in 49 seconds by @Fors * **Java**. n = 16 in 3:07 by @PeterTaylor * **C++**. n = 16 in 2:21 by @ilmale * **Rpython**. n = 22 in 3:11 by @primo * **Java**. n = 22 in 6:56 by @PeterTaylor * **Nimrod**. n = 24 in 9:28 seconds by @ReimerBehrends ## **The winner was Reimer Behrends with an entry in Nimrod!** As a check, the output for n = 22 should be `[12410090985684467712, 2087229562810269696, 351473149499408384, 59178309967151104, 9975110458933248, 1682628717576192, 284866824372224, 48558946385920, 8416739196928, 1518499004416, 301448822784, 71620493312, 22100246528, 8676573184, 3897278464, 1860960256, 911646720, 451520512, 224785920, 112198656, 56062720, 28031360, 14015680]`. --- The competition is now over but... I will offer **200 points** for every submission that increases n by 2 (within 10 minutes on my computer) until I run out of points. This offer is open **forever**. [Answer] # Nimrod (N=22) ``` import math, locks const N = 20 M = N + 1 FSize = (1 shl N) FMax = FSize - 1 SStep = 1 shl (N-1) numThreads = 16 type ZeroCounter = array[0..M-1, int] ComputeThread = TThread[int] var leadingZeros: ZeroCounter lock: TLock innerProductTable: array[0..FMax, int8] proc initInnerProductTable = for i in 0..FMax: innerProductTable[i] = int8(countBits32(int32(i)) - N div 2) initInnerProductTable() proc zeroInnerProduct(i: int): bool = innerProductTable[i] == 0 proc search2(lz: var ZeroCounter, s, f, i: int) = if zeroInnerProduct(s xor f) and i < M: lz[i] += 1 shl (M - i - 1) search2(lz, (s shr 1) + 0, f, i+1) search2(lz, (s shr 1) + SStep, f, i+1) when defined(gcc): const unrollDepth = 1 else: const unrollDepth = 4 template search(lz: var ZeroCounter, s, f, i: int) = when i < unrollDepth: if zeroInnerProduct(s xor f) and i < M: lz[i] += 1 shl (M - i - 1) search(lz, (s shr 1) + 0, f, i+1) search(lz, (s shr 1) + SStep, f, i+1) else: search2(lz, s, f, i) proc worker(base: int) {.thread.} = var lz: ZeroCounter for f in countup(base, FMax div 2, numThreads): for s in 0..FMax: search(lz, s, f, 0) acquire(lock) for i in 0..M-1: leadingZeros[i] += lz[i]*2 release(lock) proc main = var threads: array[numThreads, ComputeThread] for i in 0 .. numThreads-1: createThread(threads[i], worker, i) for i in 0 .. numThreads-1: joinThread(threads[i]) initLock(lock) main() echo(@leadingZeros) ``` Compile with ``` nimrod cc --threads:on -d:release count.nim ``` (Nimrod can be downloaded [here](http://nimrod-lang.org/download.html).) This runs in the allotted time for n=20 (and for n=18 when only using a single thread, taking about 2 minutes in the latter case). The algorithm uses a recursive search, pruning the search tree whenever a non-zero inner product is encountered. We also cut the search space in half by observing that for any pair of vectors `(F, -F)` we only need to consider one because the other produces the exact same sets of inner products (by negating `S` also). The implementation uses Nimrod's metaprogramming facilities to unroll/inline the first few levels of the recursive search. This saves a little time when using gcc 4.8 and 4.9 as the backend of Nimrod and a fair amount for clang. The search space could be further pruned by observing that we only need to consider values of S that differ in an even number of the first N positions from our choice of F. However, the complexity or memory needs of that do not scale for large values of N, given that the loop body is completely skipped in those cases. Tabulating where the inner product is zero appears to be faster than using any bit counting functionality in the loop. Apparently accessing the table has pretty good locality. It looks as though the problem should be amenable to dynamic programming, considering how the recursive search works, but there is no apparent way to do that with a reasonable amount of memory. Example outputs: N=16: ``` @[55276229099520, 10855179878400, 2137070108672, 420578918400, 83074121728, 16540581888, 3394347008, 739659776, 183838720, 57447424, 23398912, 10749184, 5223040, 2584896, 1291424, 645200, 322600] ``` N=18: ``` @[3341140958904320, 619683355033600, 115151552380928, 21392898654208, 3982886961152, 744128512000, 141108051968, 27588886528, 5800263680, 1408761856, 438001664, 174358528, 78848000, 38050816, 18762752, 9346816, 4666496, 2333248, 1166624] ``` N=20: ``` @[203141370301382656, 35792910586740736, 6316057966936064, 1114358247587840, 196906665902080, 34848574013440, 6211866460160, 1125329141760, 213330821120, 44175523840, 11014471680, 3520839680, 1431592960, 655872000, 317675520, 156820480, 78077440, 39005440, 19501440, 9750080, 4875040] ``` For purposes of comparing the algorithm with other implementations, N=16 takes about 7.9 seconds on my machine when using a single thread and 2.3 seconds when using four cores. N=22 takes about 15 minutes on a 64-core machine with gcc 4.4.6 as Nimrod's backend and overflows 64-bit integers in `leadingZeros[0]` (possibly not unsigned ones, haven't looked at it). --- Update: I've found room for a couple more improvements. First, for a given value of `F`, we can enumerate the first 16 entries of the corresponding `S` vectors precisely, because they must differ in exactly `N/2` places. So we precompute a list of bit vectors of size `N` that have `N/2` bits set and use these to derive the initial part of `S` from `F`. Second, we can improve upon the recursive search by observing that we always know the value of `F[N]` (as the MSB is zero in the bit representation). This allows us to predict precisely which branch we recurse into from the inner product. While that would actually allow us to turn the entire search into a recursive loop, that actually happens to screw up branch prediction quite a bit, so we keep the top levels in its original form. We still save some time, primarily by reducing the amount of branching we are doing. For some cleanup, the code is now using unsigned integers and fix them at 64-bit (just in case someone wants to run this on a 32-bit architecture). Overall speedup is between a factor of x3 and x4. N = 22 still needs more than eight cores to run in under 10 minutes, but on a 64-core machine it's now down to about four minutes (with `numThreads` bumped up accordingly). I don't think there's much more room for improvement without a different algorithm, though. N=22: ``` @[12410090985684467712, 2087229562810269696, 351473149499408384, 59178309967151104, 9975110458933248, 1682628717576192, 284866824372224, 48558946385920, 8416739196928, 1518499004416, 301448822784, 71620493312, 22100246528, 8676573184, 3897278464, 1860960256, 911646720, 451520512, 224785920, 112198656, 56062720, 28031360, 14015680] ``` Updated again, making use of further possible reductions in search space. Runs in about 9:49 minutes for N=22 on my quadcore machine. Final update (I think). Better equivalence classes for choices of F, cutting runtime for N=22 down to ~~3:19 minutes~~ 57 seconds (edit: I had accidentally run that with only one thread) on my machine. This change makes use of the fact that a pair of vectors produces the same leading zeros if one can be transformed into the other by rotating it. Unfortunately, a fairly critical low-level optimization requires that the top bit of F in the bit representation is always the same, and while using this equivalence slashed the search space quite a bit and reduced runtime by about one quarter over using a different state space reduction on F, the overhead from eliminating the low-level optimization more than offset it. However, it turns out that this problem can be eliminated by also considering the fact that F that are inverses of one another are also equivalent. While this added to the complexity of the calculation of the equivalence classes a bit, it also allowed me to retain the aforementioned low-level optimization, leading to a speedup of about x3. One more update to support 128-bit integers for the accumulated data. To compile with 128 bit integers, you'll need `longint.nim` from [here](https://bitbucket.org/behrends/nimlongint) and to compile with `-d:use128bit`. N=24 still takes more than 10 minutes, but I've included the result below for those interested. N=24: ``` @[761152247121980686336, 122682715414070296576, 19793870419291799552, 3193295704340561920, 515628872377565184, 83289931274780672, 13484616786640896, 2191103969198080, 359662314586112, 60521536552960, 10893677035520, 2293940617216, 631498735616, 230983794688, 102068682752, 48748969984, 23993655296, 11932487680, 5955725312, 2975736832, 1487591936, 743737600, 371864192, 185931328, 92965664] ``` --- ``` import math, locks, unsigned when defined(use128bit): import longint else: type int128 = uint64 # Fallback on unsupported architectures template toInt128(x: expr): expr = uint64(x) const N = 22 M = N + 1 FSize = (1 shl N) FMax = FSize - 1 SStep = 1 shl (N-1) numThreads = 16 type ZeroCounter = array[0..M-1, uint64] ZeroCounterLong = array[0..M-1, int128] ComputeThread = TThread[int] Pair = tuple[value, weight: int32] var leadingZeros: ZeroCounterLong lock: TLock innerProductTable: array[0..FMax, int8] zeroInnerProductList = newSeq[int32]() equiv: array[0..FMax, int32] fTable = newSeq[Pair]() proc initInnerProductTables = for i in 0..FMax: innerProductTable[i] = int8(countBits32(int32(i)) - N div 2) if innerProductTable[i] == 0: if (i and 1) == 0: add(zeroInnerProductList, int32(i)) initInnerProductTables() proc ror1(x: int): int {.inline.} = ((x shr 1) or (x shl (N-1))) and FMax proc initEquivClasses = add(fTable, (0'i32, 1'i32)) for i in 1..FMax: var r = i var found = false block loop: for j in 0..N-1: for m in [0, FMax]: if equiv[r xor m] != 0: fTable[equiv[r xor m]-1].weight += 1 found = true break loop r = ror1(r) if not found: equiv[i] = int32(len(fTable)+1) add(fTable, (int32(i), 1'i32)) initEquivClasses() when defined(gcc): const unrollDepth = 4 else: const unrollDepth = 4 proc search2(lz: var ZeroCounter, s0, f, w: int) = var s = s0 for i in unrollDepth..M-1: lz[i] = lz[i] + uint64(w) s = s shr 1 case innerProductTable[s xor f] of 0: # s = s + 0 of -1: s = s + SStep else: return template search(lz: var ZeroCounter, s, f, w, i: int) = when i < unrollDepth: lz[i] = lz[i] + uint64(w) if i < M-1: let s2 = s shr 1 case innerProductTable[s2 xor f] of 0: search(lz, s2 + 0, f, w, i+1) of -1: search(lz, s2 + SStep, f, w, i+1) else: discard else: search2(lz, s, f, w) proc worker(base: int) {.thread.} = var lz: ZeroCounter for fi in countup(base, len(fTable)-1, numThreads): let (fp, w) = fTable[fi] let f = if (fp and (FSize div 2)) == 0: fp else: fp xor FMax for sp in zeroInnerProductList: let s = f xor sp search(lz, s, f, w, 0) acquire(lock) for i in 0..M-1: let t = lz[i].toInt128 shl (M-i).toInt128 leadingZeros[i] = leadingZeros[i] + t release(lock) proc main = var threads: array[numThreads, ComputeThread] for i in 0 .. numThreads-1: createThread(threads[i], worker, i) for i in 0 .. numThreads-1: joinThread(threads[i]) initLock(lock) main() echo(@leadingZeros) ``` [Answer] ## Java (`n=22`?) I think most of the answers which do better than `n=16` use a similar approach to this, although they differ in the symmetries they exploit and the way they divide the task between threads. The vectors defined in the question can be replaced with bit strings, and the inner product with XORing the overlapping window and checking that there are exactly `n/2` bits set (and hence `n/2` bits cleared). There are `n! / ((n/2)!)` (central binomial coefficient) strings of `n` bits with `n/2` bits set (which I call *balanced* strings), so for any given `F` there are that many windows of `S` which give a zero inner product. Moreover, the action of sliding `S` along one and checking whether we can still find an incoming bit which gives a zero inner product corresponds to looking for an edge in a graph whose nodes are the windows and whose edges link a node `u` to a node `v` whose first `n-1` bits are the last `n-1` bits of `u`. For example, with `n=6` and `F=001001` we get this graph: ![Graph for F=001001](https://i.stack.imgur.com/1Rf2W.png) and for `F=001011` we get this graph: ![Graph for F=001011](https://i.stack.imgur.com/5GdDz.png) Then we need to count for each `i` from `0` to `n` how many paths of length `i` there are, summing over the graphs for every `F`. I think most of us are using depth-first search. Note that the graphs are sparse: it's easy to prove that each node has in-degree of at most 1 and out-degree of at most one. That also means that the only structures possible are simple chains and simple loops. This simplifies the DFS a bit. I exploit a couple of symmetries: the balanced strings are closed under bit inverse (the `~` operation in many languages from the ALGOL family), and under bit rotation, so we can group together values of `F` which are related by these operations and only do the DFS once. ``` public class CodeGolf26459v8D implements Runnable { private static final int NUM_THREADS = 8; public static void main(String[] args) { v8D(22); } private static void v8D(int n) { int[] bk = new int[1 << n]; int off = 0; for (int i = 0; i < bk.length; i++) { bk[i] = Integer.bitCount(i) == n/2 ? off++ : -1; } int[] fwd = new int[off]; for (int i = 0; i < bk.length; i++) { if (bk[i] >= 0) fwd[bk[i]] = i; } CodeGolf26459v8D[] runners = new CodeGolf26459v8D[NUM_THREADS]; Thread[] threads = new Thread[runners.length]; for (int i = 0; i < runners.length; i++) { runners[i] = new CodeGolf26459v8D(n, i, runners.length, bk, fwd); threads[i] = new Thread(runners[i]); threads[i].start(); } try { for (int i = 0; i < threads.length; i++) threads[i].join(); } catch (InterruptedException ie) { throw new RuntimeException("This shouldn't be reachable", ie); } long surviving = ((long)fwd.length) << (n - 1); for (int i = 0; i <= n; i++) { for (CodeGolf26459v8D runner : runners) surviving -= runner.survival[i]; System.out.print(i == 0 ? "[" : ", "); java.math.BigInteger result = new java.math.BigInteger(Long.toString(surviving)); System.out.print(result.shiftLeft(n + 1 - i)); } System.out.println("]"); } public final int n; protected final int id; protected final int numRunners; private final int[] bk; private final int[] fwd; public long[] survival; public CodeGolf26459v8D(int n, int id, int numRunners, int[] bk, int[] fwd) { this.n = n; this.id = id; this.numRunners = numRunners; this.bk = bk; this.fwd = fwd; } private int dfs2(int[] graphShape, int flip, int i) { if (graphShape[i] != 0) return graphShape[i]; int succ = flip ^ (fwd[i] << 1); if (succ >= bk.length) succ ^= bk.length + 1; int j = bk[succ]; if (j == -1) return graphShape[i] = 1; graphShape[i] = n + 1; // To detect cycles return graphShape[i] = dfs2(graphShape, flip, j) + 1; } @Override public void run() { int n = this.n; int[] bk = this.bk; int[] fwd = this.fwd; // NB The initial count is approx 2^(2n - 1.33 - 0.5 lg n) // For n=18 we overflow 32-bit // 64-bit is good up to n=32. long[] survival = new long[n + 1]; boolean[] visited = new boolean[1 << (n - 1)]; int th = 0; for (int f = 0; f < visited.length; f++) { if (visited[f]) continue; int m = 1, g = f; while (true) { visited[g] = true; int ng = g << 1; if ((ng >> (n - 1)) != 0) ng ^= (1 << n) - 1; if (ng == f) break; m++; g = ng; } if (th++ % numRunners != id) continue; int[] graphShape = new int[fwd.length]; int flip = (f << 1) ^ f; for (int i = 0; i < graphShape.length; i++) { int life = dfs2(graphShape, flip, i); if (life <= n) survival[life] += m; } } this.survival = survival; } } ``` On my 2.5GHz Core 2 I get ``` # n=18 $ javac CodeGolf26459v8D.java && time java CodeGolf26459v8D [3341140958904320, 619683355033600, 115151552380928, 21392898654208, 3982886961152, 744128512000, 141108051968, 27588886528, 5800263680, 1408761856, 438001664, 174358528, 78848000, 38050816, 18762752, 9346816, 4666496, 2333248, 1166624] real 0m3.131s user 0m10.133s sys 0m0.380s # n=20 $ javac CodeGolf26459v8D.java && time java CodeGolf26459v8D [203141370301382656, 35792910586740736, 6316057966936064, 1114358247587840, 196906665902080, 34848574013440, 6211866460160, 1125329141760, 213330821120, 44175523840, 11014471680, 3520839680, 1431592960, 655872000, 317675520, 156820480, 78077440, 39005440, 19501440, 9750080, 4875040] real 1m8.706s user 4m20.980s sys 0m0.564s # n=22 $ javac CodeGolf26459v8D.java && time java CodeGolf26459v8D [12410090985684467712, 2087229562810269696, 351473149499408384, 59178309967151104, 9975110458933248, 1682628717576192, 284866824372224, 48558946385920, 8416739196928, 1518499004416, 301448822784, 71620493312, 22100246528, 8676573184, 3897278464, 1860960256, 911646720, 451520512, 224785920, 112198656, 56062720, 28031360, 14015680] real 20m10.654s user 76m53.880s sys 0m6.852s ``` Since Lembik's computer has 8 cores and executed my earlier single-threaded program twice as fast as mine, I'm optimistic that it will execute `n=22` in less than 8 minutes. [Answer] # C It is basically just a slightly optimised implementation of the algorithm in the question. It can manage `n=12` within the time limit. ``` #include <stdio.h> #include <inttypes.h> #define n 12 #define m (n + 1) int main() { int i; uint64_t S, F, o[m] = {0}; for (S = 0; S < (1LLU << (n + m - 1)); S += 2) for (F = 0; F < (1 << (n - 1)); F++) for (i = 0; i < m; i++) if (__builtin_popcount(((S >> i) & ((1 << n) - 1)) ^ F) == n >> 1) o[i] += 4; else break; for (i = 0; i < m; i++) printf("%" PRIu64 " ", o[i]); return 0; } ``` Test run for `n=12`, including compilation: ``` $ clang -O3 -march=native -fstrict-aliasing -ftree-vectorize -Wall fast.c $ time ./a.out 15502147584 3497066496 792854528 179535872 41181184 9826304 2603008 883712 381952 177920 85504 42560 21280 real 0m53.266s user 0m53.042s sys 0m0.068s $ ``` Comment: I just turned my brain on and used some simple combinatorics to calculate that the first value will always be `n! / ((n / 2)!)^2 * 2^(n + m - 1)`. It seems to me that there must be a completely algebraic solution to this problem. [Answer] ## Java, `n=16` For any given value of `F` there are `\binom{n}{n/2}` vectors which have a zero inner product with it. So we can build a graph whose vertices are those matching vectors and whose edges correspond to the shifting of `S`, and then we just need to count paths of length up to `n` in the graph. I haven't tried microoptimising this by replacing conditionals with bitwise operations, but each double-increment of `n` increases running time about 16-fold, so that's not going to make enough of a difference unless I'm pretty close to the threshold. On my machine, I'm not. ``` public class CodeGolf26459 { public static void main(String[] args) { v3(16); } // Order of 2^(2n-1) * n ops private static void v3(int n) { long[] counts = new long[n+1]; int mask = (1 << n) - 1; for (int f = 0; f < (1 << (n-1)); f++) { // Find adjacencies long[] subcounts = new long[1 << n]; for (int g = 0; g < (1 << n); g++) { subcounts[g] = Integer.bitCount(f ^ g) == n/2 ? 2 : -1; } for (int round = 0; round <= n; round++) { long count = 0; // Extend one bit. long[] next = new long[1 << n]; for (int i = 0; i < (1 << n); i++) { long s = subcounts[i]; if (s == -1) next[i] = -1; else { count += s; int j = (i << 1) & mask; if (subcounts[j] >= 0) next[j] += s; if (subcounts[j + 1] >= 0) next[j + 1] += s; } } counts[round] += count << (n - round); subcounts = next; } } System.out.print("["); for (long count : counts) System.out.print(count+", "); System.out.println("]"); } } ``` On my 2.5GHz Core 2 I get ``` $ javac CodeGolf26459.java && time java -server CodeGolf26459 [55276229099520, 10855179878400, 2137070108672, 420578918400, 83074121728, 16540581888, 3394347008, 739659776, 183838720, 57447424, 23398912, 10749184, 5223040, 2584896, 1291424, 645200, 322600, ] real 6m2.663s user 6m4.631s sys 0m1.580s ``` [Answer] ## RPython, N=22 ~3:23 Multi-threaded, using a stackless recursive descent. The program accepts two command line arguments: N, and the number of worker threads. ``` from time import sleep from rpython.rlib.rthread import start_new_thread, allocate_lock from rpython.rlib.rarithmetic import r_int64, build_int, widen from rpython.rlib.rbigint import rbigint r_int8 = build_int('r_char', True, 8) class ThreadEnv: __slots__ = ['n', 'counts', 'num_threads', 'v_range', 'v_num', 'running', 'lock'] def __init__(self): self.n = 0 self.counts = [rbigint.fromint(0)] self.num_threads = 0 self.v_range = [0] self.v_num = 0 self.running = 0 self.lock = None env = ThreadEnv() bt_bits = 12 bt_mask = (1<<bt_bits)-1 # computed compile time bit_table = [r_int8(0)] for i in xrange(1,1<<bt_bits): bit_table += [((i&1)<<1) + bit_table[i>>1]] def main(argv): argc = len(argv) if argc < 2 or argc > 3: print 'Usage: %s N [NUM_THREADS=2]'%argv[0] return 1 if argc == 3: env.num_threads = int(argv[2]) else: env.num_threads = 2 env.n = int(argv[1]) env.counts = [rbigint.fromint(0)]*env.n env.lock = allocate_lock() v_range = [] v_max = 1<<(env.n-1) v_num = 0 v = (1<<(env.n>>1))-1 while v < v_max: v_num += 1 v_range += [v] if v&1: # special case odd v s = (v+1)&-v v ^= s|(s>>1) else: s = v&-v r = v+s # s is at least 2, skip two iterations i = 3 s >>= 2 while s: i += 1 s >>= 1 v = r|((v^r)>>i) env.v_range = v_range env.v_num = v_num for i in xrange(env.num_threads-1): start_new_thread(run,()) # use the main process as a worker run() # wait for any laggers while env.running: sleep(0.05) result = [] for i in range(env.n): result += [env.counts[i].lshift(env.n-i+3).str()] result += [env.counts[env.n-1].lshift(3).str()] print result return 0 def run(): with env.lock: v_start = env.running env.running += 1 n = env.n counts = [r_int64(0)]*n mask = (1<<n)-1 v_range = env.v_range v_num = env.v_num z_count = 1<<(n-2) for i in xrange(v_start, v_num, env.num_threads): v = v_range[i] counts[0] += z_count counts[1] += v_num r = v^(v<<1) for w in v_range: # unroll counts[2] for speed # ideally, we could loop over x directly, # rather than over all v, only to throw the majority away # there's a 2x-3x speed improvement to be had here... x = w^r if widen(bit_table[x>>bt_bits]) + widen(bit_table[x&bt_mask]) == n: counts[2] += 1 x, y = v, x o, k = 2, 3 while k < n: # x = F ^ S # y = F ^ (S<<1) o = k z = (((x^y)<<1)^y)&mask # z is now F ^ (S<<2), possibly xor 1 # what S and F actually are is of no consequence # the compiler hint `widen` let's the translator know # to store the result as a native int, rather than a signed char bt_high = widen(bit_table[z>>bt_bits]) if bt_high + widen(bit_table[z&bt_mask]) == n: counts[k] += 1 x, y = y, z k += 1 elif bt_high + widen(bit_table[(z^1)&bt_mask]) == n: counts[k] += 1 x, y = y, z^1 k += 1 else: k = n with env.lock: for i in xrange(n): env.counts[i] = env.counts[i].add(rbigint.fromrarith_int(counts[i])) env.running -= 1 def target(*args): return main, None ``` --- **To Compile** Make a local clone of the [PyPy repository](https://bitbucket.org/pypy/pypy/src) using mercurial, git, or whatever you prefer. Type the following incantation (assuming the above script is named `convolution-high.py`): ``` $ pypy %PYPY_REPO%/rpython/bin/rpython --thread convolution-high.py ``` where `%PYPY_REPO%` represents an environment variable pointing to the repository you just cloned. Compilation takes about one minute. --- **Sample Timings** N=16, 4 threads: ``` $ timeit convolution-high-c 16 4 [55276229099520, 10855179878400, 2137070108672, 420578918400, 83074121728, 16540581888, 3394347008, 739659776, 183838720, 57447424, 23398912, 10749184, 5223040, 2584896, 1291424, 645200, 322600] Elapsed Time: 0:00:00.109 Process Time: 0:00:00.390 ``` N=18, 4 threads: ``` $ timeit convolution-high-c 18 4 [3341140958904320, 619683355033600, 115151552380928, 21392898654208, 3982886961152, 744128512000, 141108051968, 27588886528, 5800263680, 1408761856, 438001664, 174358528, 78848000, 38050816, 18762752, 9346816, 4666496, 2333248, 1166624] Elapsed Time: 0:00:01.250 Process Time: 0:00:04.937 ``` N=20, 4 threads: ``` $ timeit convolution-high-c 20 4 [203141370301382656, 35792910586740736, 6316057966936064, 1114358247587840, 196906665902080, 34848574013440, 6211866460160, 1125329141760, 213330821120, 44175523840, 11014471680, 3520839680, 1431592960, 655872000, 317675520, 156820480, 78077440, 39005440, 19501440, 9750080, 4875040] Elapsed Time: 0:00:15.531 Process Time: 0:01:01.328 ``` N=22, 4 threads: ``` $ timeit convolution-high-c 22 4 [12410090985684467712, 2087229562810269696, 351473149499408384, 59178309967151104, 9975110458933248, 1682628717576192, 284866824372224, 48558946385920, 8416739196928, 1518499004416, 301448822784, 71620493312, 22100246528, 8676573184, 3897278464, 1860960256, 911646720, 451520512, 224785920, 112198656, 56062720, 28031360, 14015680] Elapsed Time: 0:03:23.156 Process Time: 0:13:25.437 ``` [Answer] # Python 3.3, N = 20, 3.5min Disclaimer: my intention is **NOT** to post this as my own answer, since the algorithm I'm using is only a shameless port from [primo's RPython solution](https://codegolf.stackexchange.com/a/26667/20998). My purpose here is only to show what you can do in Python if you combine the magic of **Numpy** and **Numba** modules. Numba explained in short: > > Numba is an just-in-time specializing compiler which compiles annotated Python and NumPy code to LLVM (through decorators). <http://numba.pydata.org/> > > > **Update 1**: I noticed after tossing the numbers around that we can simply skip some of the numbers completely. So now **maxf** becomes **(1 << n) // 2** and **maxs** becomes **maxf**2\*\*. This will speed up the process quite a bit. n = 16 now takes only ~48s (down from 4,5min). I also have another idea which I'm going to try and see if I can make it go a little faster. **Update 2:** Changed algorithm (primo's solution). While my port does not yet support multithreading it is pretty trivial to add. It is even possible to release CPython GIL using Numba and ctypes. This solution, however, runs very fast on single core too! ``` import numpy as np import numba as nb bt_bits = 11 bt_mask = (1 << bt_bits) - 1 bit_table = np.zeros(1 << bt_bits, np.int32) for i in range(0, 1 << bt_bits): bit_table[i] = ((i & 1) << 1) + bit_table[i >> 1] @nb.njit("void(int32, int32, int32, int32, int64[:], int64[:])") def run(n, m, start, re, counts, result): mask = (1 << n) - 1 v_max = (1 << n) // 2 rr = v_max // 2 v = (1 << (n >> 1)) - 1 while v < v_max: s = start while s < rr: f = v ^ s counts[0] += 8 t = s << 1 o, j = 0, 1 while o < j and j < m: o = j w = (t ^ f) & mask bt_high = bit_table[w >> bt_bits] if bt_high + bit_table[w & bt_mask] == n: counts[j] += 8 t <<= 1 j += 1 elif bt_high + bit_table[(w ^ 1) & bt_mask] == n: counts[j] += 8 t = (t | 1) << 1 j += 1 s += re s = v & -v r = v + s o = v ^ r o = (o >> 2) // s v = r | o for e in range(m): result[e] += counts[e] << (n - e) ``` And finally: ``` if __name__ == "__main__": n = 20 m = n + 1 result = np.zeros(m, np.int64) counts = np.zeros(m, np.int64) s1 = time.time() * 1000 run(n, m, 0, 1, counts, result) s2 = time.time() * 1000 print(result) print("{0}ms".format(s2 - s1)) ``` This runs on my machine in 212688ms or ~3.5min. [Answer] # C++ N=16 I'm testing on a EEEPC with an atom.. my time don't make a lot of sense. :D The atom solve n=14 in 34 seconds. And n=16 in 20 minutes. I want to test n = 16 on OP pc. I'm optimistic. The ideas is that every time we find a solution for a given F we have found 2^i solution because we can change the lower part of S leading to the same result. ``` #include <stdio.h> #include <cinttypes> #include <cstring> int main() { const int n = 16; const int m = n + 1; const uint64_t maxS = 1ULL << (2*n); const uint64_t maxF = 1ULL << n; const uint64_t mask = (1ULL << n)-1; uint64_t out[m]={0}; uint64_t temp[m] = {0}; for( uint64_t F = 0; F < maxF; ++F ) { for( uint64_t S = 0; S < maxS; ++S ) { int numSolution = 1; for( int i = n; i >= 0; --i ) { const uint64_t window = S >> i; if( __builtin_popcount( mask & (window ^ F) ) == (n / 2) ) { temp[i] += 1; } else { numSolution = 1 << i; S += numSolution - 1; break; } } for( int i = n; i >= 0; --i ) { out[i] += temp[i]*numSolution; temp[i] = 0; } } } for( int i = n; i >= 0; --i ) { uint64_t x = out[i]; printf( "%lu ", x ); } return 0; } ``` to compile: gcc 26459.cpp -std=c++11 -O3 -march=native -fstrict-aliasing -ftree-vectorize -Wall -pedantic -o 26459 [Answer] ### JAVASCRIPT n:12 In my computer it took 231.242 seconds. In the Demo I'm using webworkers to prevent freezing the browser. This sure can be further improved with parallel workers. I know JS don't stand a chance in this challenge but I did it for fun! **[Click to run the online Demo](http://jsbin.com/segaq/3/edit?html,output)** ``` var n = 8; var m = n + 1; var o = []; var popCount = function(bits) { var SK5 = 0x55555555, SK3 = 0x33333333, SKF0 = 0x0f0f0f0f, SKFF = 0xff00ff; bits -= (bits >> 1) & SK5; bits = (bits & SK3) + ((bits >> 2) & SK3); bits = (bits & SKF0) + ((bits >> 4) & SKF0); bits += bits >> 8; return (bits + (bits >> 15)) & 63; }; for(var S = 0; S < (1 << n + m - 1); S += 2){ for(var F = 0; F < (1 << n - 1); F += 1){ for (var i = 0; i < m; i++){ var c = popCount(((S >> i) & ((1 << n) - 1)) ^ F); if(c == n >> 1){ if(!o[i]) o[i] = 0; o[i] += 4; } else break; } } } return o; ``` [Answer] # Rust Port of [@ilmale's C++ answer](https://codegolf.stackexchange.com/a/26471/110802) in Rust. [Try it online!](https://tio.run/##jVNNT8JAEL3zK54cTAsW@TDGWEpiTLwYeuFiQpDUusWNZZd0t0Ak/evWXQrItmCcpJvuzJuZNx@bpELmecQwDyizbGxqUBJyJiT8e6S3N/Bw5x5ph0or6BdRestHEx0bgShUBuzhZTraB@ig34fVRQO@XQY9GSDfNI@e91arMNtw0Ckw2yMmEvNUgqvPw7jtYjhxDYsk80XJtD0iniACZWi3Wlseu9qPfYVybLsH9eqDxkQp@0V1Rw7HTiydTwWPU0k502W5BkqnpTqtpfJ6vt1KyPLQ93K4FWXvfKWCCAwGoG4FRCNYuku4hLUDvyKy7VbIUyannBGhgnvbUV2jW4yq1z2RTotu1ZgexjlBs0JfSwYSC3ImRrl6PbUTxLUIHd/AO6fSaXlLSPB5gknt/O3fjVarUy660oiGwbNKpOJg7E2VnCi1trBm5nb@yV6vx1qlKbH/DblIKJMXVn2ToX6F9e7dZbWsluffYRQHM5E7j3whnZgsSez11C2W3IsCqf5kkMyIdMJF6rFA0iX5AQ) ### `src/main.rs` ``` fn main() { const N: u64 = 8; const M: usize = (N + 1) as usize; const MAX_S: u64 = 1 << (2 * N); const MAX_F: u64 = 1 << N; const MASK: u64 = (1 << N) - 1; let mut out = [0; M]; let mut temp = [0; M]; for f in 0..MAX_F { let mut s = 0; while s < MAX_S { let mut num_solution = 1; for i in (0..=N).rev() { let window = s >> i; if (MASK & (window ^ f)).count_ones() == (N / 2) as u32 { temp[i as usize] += 1; } else { num_solution = 1 << i; s += num_solution - 1; break; } } for i in (0..=N).rev() { out[i as usize] += temp[i as usize] * num_solution; temp[i as usize] = 0; } s += 1; } } for i in (0..=N).rev() { let x = out[i as usize]; print!("{} ", x); } } ``` ### Build and running ``` # win10 environment $ set Copt-level=3 $ set Clto=fat $ set Ctarget-cpu=native $ cargo build --release $ cargo run --release ``` [Answer] # Fortran: n=12 I just made a quick'n'dirty version in Fortran, no optimizations except OpenMP. It should squeeze in at just below 10 minutes for n=12 on the OPs machine, it takes 10:39 on my machine which is sligthly slower. 64-bit integers have a negative performance impact indeed; guess I would have to rethink the whole algorithm for this to be much faster. Don't know if I'm going to bother, I think I'll rather spend some time thinking up a good challenge that's more to my own tastes. If anyone else wants to take this and run with it, go ahead :) ``` program golf use iso_fortran_env implicit none integer, parameter :: n=12 integer :: F(n), S(2*n) integer(int64) :: leadingzerocounts(n+1) integer :: k integer(int64) :: i,j,bindec,enc leadingzerocounts=0 !$OMP parallel do private(i,enc,j,bindec,S,F,k) reduction(+:leadingzerocounts) schedule(dynamic) do i=0,2**(2*n)-1 enc=i ! Short loop to convert i into the array S with -1s and 1s do j=2*n,1,-1 bindec=2**(j-1) if (enc-bindec .ge. 0) then S(j)=1 enc=enc-bindec else S(j)=-1 endif end do do j=0,2**(n)-1 ! Convert j into the array F with -1s and 1s enc=j do k=n,1,-1 bindec=2**(k-1) if (enc-bindec .ge. 0) then F(k)=1 enc=enc-bindec else F(k)=-1 endif end do ! Compute dot product do k=1,n+1 if (dot_product(F,S(k:k+n-1)) /= 0) exit leadingzerocounts(k)=leadingzerocounts(k)+1 end do end do end do !$OMP end parallel do print *, leadingzerocounts end ``` [Answer] # Lua: n = 16 Disclaimer: my intention is NOT to post this as my own answer, since the algorithm I'm using is shamelessly stolen from [Anna Jokela's clever answer](https://codegolf.stackexchange.com/a/26513/3103). which was shamelessly stolen from [ilmale's clever answer](https://codegolf.stackexchange.com/a/26471/3103). Besides, it's not even valid - it has inaccuracies caused by floating point numbers (it would be better if Lua would support 64-bit integers). However, I'm still uploading it, just to show how fast this solution is. It's a dynamic programming language, and yet I can calculate n = 16 in reasonable time (1 minute on 800MHz CPU). Run with LuaJIT, standard interpreter is too slow. ``` local bit = require "bit" local band = bit.band local bor = bit.bor local bxor = bit.bxor local lshift = bit.lshift local rshift = bit.rshift -- http://stackoverflow.com/a/11283689/736054 local function pop_count(w) local b1 = 1431655765 local b2 = 858993459 local b3 = 252645135 local b7 = 63 w = band(rshift(w, 1), b1) + band(w, b1) w = band(rshift(w, 2), b2) + band(w, b2) w = band(w + rshift(w, 4), b3) return band(rshift(w, 24) + rshift(w, 16) + rshift(w, 8) + w, b7) end local function gen_array(n, value) value = value or 0 array = {} for i = 1, n do array[i] = value end return array end local n = 16 local u = math.floor(n / 2) local m = n + 1 local maxf = math.floor(lshift(1, n) / 2) local maxs = maxf ^ 2 local mask = lshift(1, n) - 1 local out = gen_array(m, 0) local temp = gen_array(m, 0) for f = 0, maxf do local s = 0 while s <= maxs do local num_solution = 1 for i = n, 0, -1 do if pop_count(band(mask, bxor(rshift(s, i), f))) == u then temp[i + 1] = temp[i + 1] + 8 else num_solution = lshift(1, i) s = s + num_solution - 1 break end end for i = 1, m do out[i] = out[i] + temp[i] * num_solution temp[i] = 0 end s = s + 1 end end for i = m, 1, -1 do print(out[i]) end ``` ]
[Question] [ It's Christmas everybody, and here's a code-golf challenge to celebrate. You need to make a program to print out a present. Specifically, the words "Merry Christmas". BUT, there is a catch: this program must only work if it is the 25th of December. If the code is run on any other day, then the program should crash. This is Code-Golf, so the answer with the least amount of bytes wins. Merry Christmas! [Answer] ## Pyke, 21 bytes ``` .dↄґ6C65h*325q/Al ``` [Try it here!](http://pyke.catbus.co.uk/?code=.d%02%E2%86%84%D2%916C65h%2a325q%2FAl) ``` C65h* - multiply the day by the (current month + 1) 325q - ^ == 325 6 / - 6 / ^ .dↄґ - load "merry christmas" Al - ^.capwords() ``` Or 18 bytes noncompetitive. ``` .dↄґ6Cs6Y1q/Al ``` Exactly the same except for this section: ``` Cs6Y1q C - get_time() s6 - add 1 week Y - get day of the year 1q - ^ == 1 ``` [Try it here!](http://pyke.catbus.co.uk/?code=.d%02%E2%86%84%D2%916Cs6Y1q%2FAl) [Answer] # JavaScript, ~~55~~ ~~53~~ 46 bytes Note: this has only been tested in Google Chrome, program may behave differently from browser to browser (or device to device) *2 bytes saved thanks to @ConorO'Brien* *7 bytes saved thanks to @ETHProductions* ``` alert(/c 25/.test(Date())?"Merry Christmas":a) ``` Exits with `Uncaught ReferenceError: a is not defined` if the date is not `Dec 25`. I'm not really sure if this counts as crashing ``` alert(/c 25/.test(Date())?"Merry Christmas":a) ``` [Answer] # Python 3, ~~66~~ 63 bytes Thanks to ideas from JavaScript / ES answers here I managed to squeeze some bytes. Index a dictionary - non-existent keys will raise a `KeyError`. The following code works in local time zone ``` import time;print({1:'Merry Christmas'}['c 25'in time.ctime()]) ``` The output format for `ctime` isn't locale-dependent - the format is always ~ `'Sun Dec 25 19:23:05 2016'`. Since only in December does the 3-letter abbreviation end with `c`, it is safe to use `'c 25'in time.ctime()` here. --- **Previous version:** This works in UTC time zone. For local time zone one needs to `s/gm/local` for 3 more bytes. For Python 2, one can remove parentheses from `print` for 65 bytes. ``` import time;print({(12,25):'Merry Christmas'}[time.gmtime()[1:3]]) ``` The construct throws `KeyError` on other dates: ``` >>> import time;print({(1,1):'Happy New Year'}[time.gmtime()[1:3]]) Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: (12, 25) ``` [Answer] # PHP, ~~39~~ 38 bytes, not competing (doesn´t crash) ``` <?=date(md)-1225?"":"Merry Christmas"; ``` or ``` <?date(md)-1225?die:0?>Merry Christmas ``` or ``` <?=["Merry Christmas"][date(md)-1225]; ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~68~~ ~~67~~ 65 bytes -1 with thanks to @muddyfish Thanks to @AnttiHaapala for the idea that saved another couple. ``` import time;print['Merry Christmas'][(12,25)!=time.gmtime()[1:3]] ``` [Try it online!](https://tio.run/nexus/python2#@5@ZW5BfVKJQkpmbal1QlJlXEq3um1pUVKngnFGUWVySm1isHhutYWikY2SqqWgLUqaXnguiNDSjDa2MY2P//wcA "Python 2 – TIO Nexus") Throws an IndexError if not 25th Dec. Non-competing version for 59 bytes as it only works for non Leap years (uses day of year which is 360 this year but 361 in leap years) ``` import time;print['Merry Christmas'][360!=time.gmtime()[7]] ``` [Answer] ## R, 52 61 58 bytes ``` `if`(format(Sys.Date(),"%m%d")=="1225","Merry Christmas",) ``` If the current date is not the 25th of December then an error is returned because no third argument is supplied to `if`. Edit: Fixed a silly error [Answer] My first time around here... Started with the best language ever for this job: # Java, ~~200~~ ~~188~~ bytes (thanks to @Daniel Gray), 186 bytes removing "ln" from print. ``` import java.util.*;public class a{public static void main(String[]r){Calendar c=Calendar.getInstance();if(!(c.get(2)==11&&c.get(5)==25)){int i=1/0;}System.out.print("Merry Christmas");}} ``` [Try it here!](https://www.compilejava.net/) [Answer] # [MATL](https://github.com/lmendo/MATL), ~~34~~ 33 bytes ``` 'Merry Christmas'IHh&Z'5U12h=?}Yl ``` This works in [current version (19.7.0)](https://github.com/lmendo/MATL/releases/tag/19.7.0) of the language. To cause the error, the following code exploits the fact that the logarithm of a string gives an error (this may change in future versions). [Try it online!](https://tio.run/nexus/matl#@6/um1pUVKngnFGUWVySm1is7umRoRalbhpqaJRha18bmfP/PwA "MATL – TIO Nexus") ### Explanation ``` 'Merry Christmas' % Push this string IHh % Push 3, then 2, concatenate: gives array [3 2] &Z' % Get 3rd and 2nd outputs of clock vector: current day and month 5U12h % Push 5, square, push 12, concatenate: gives [25 12] = % Compare if corresponding entries are equal in the two arrays ? % If all entries are equal: do nothing } % Else Yl % Logarithm. Gives an error when applied on a string % End (implicit). Display (implicit) ``` [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 48 bytes ``` ~left$$|(_D,5)=@12-25||?@Merry Christmas|\?a(12) ``` Explanation: ``` ~ IF left$$|(_D,5) the date string starts with =@12-25| the string "12-25" | THEN [[email protected]](/cdn-cgi/l/email-protection)| PRINT "Merry Christmas" \ ELSE ?a(12) Print the twelfth index of an undefined array. Since there are only 11 elements in undefined arrays, this results in an index-out-of-bounds error. The the IF statement is auto-closed by QBIC. ``` This assumes American `MM-DD` date notation. This would be shorter if I'd finally make a Substring function in QBIC. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~32~~ 21 bytes Saved 11 bytes thanks to Adnan's string compression :) . ``` 1žfže‚12D·>‚Q÷”ÞÙŒÎ”× ``` ## Explanation ``` žfže‚ Push [current month, current day] 12D·>‚ Push [12, 25] Q Push tmp = 1 if the two arrays are equal, tmp = 0 otherwise 1 ÷ Evaluate x = 1/tmp. If tmp = 0 a division by 0 exception is thrown ”ÞÙŒÎ”× Implicitly display "Merry Christmas" x times ``` [Try it online!](https://tio.run/nexus/05ab1e#@294dF/a0X2pjxpmGRq5HNpuB2QEHt7@qGHu4XmHZx6ddLgPxJz@/z8A "05AB1E – TIO Nexus") I did what came to mind first, so there may be better approaches for this one. But PPCG deserves a Merry Christmas in 05AB1E as well ;) . [Answer] # C# / CS Script ~~106~~ ~~100~~ 99 bytes 99 byte solution ``` using System;int i;Console.WriteLine(DateTime.Now.ToString("dM")=="2512"?"Merry Christmas":i/0+""); ``` [Try it here!](https://dotnetfiddle.net/VNCSxf) 100 byte solution (prefer this one... a bit different) ``` using System;int i;Console.WriteLine(DateTime.Now.AddDays(7).DayOfYear==1?"Merry Christmas":i/0+""); ``` Explained: ``` using System; int i; // if today plus 7 days is the first day of the year, then it's xmas! Console.WriteLine(DateTime.Now.AddDays(7).DayOfYear==1 ? "Merry Christmas" // otherwise divide i by 0 : i/0+""); ``` `DateTime.Now.AddDays(7).DayOfYear==1` is one byte shorter than `DateTime.Now.ToString("ddMM")=="2512"` but 1 byte longer than `DateTime.Now.ToString("dM")=="2512"` [Answer] # C#/CS Script, 96 Bytes, Mostly Plagiarized from Erresen ``` using System;Console.WriteLine(DateTime.Now.AddDays(7).DayOfYear==1?"Merry Christmas":1/0+""); ``` Deletes the `int i` declaration in favor of hard coding the division. I would leave this as a comment but don't have the reputation. [Answer] # bash + Unix utilities, ~~51~~ ~~49~~ 47 bytes ``` ((`date +%m%d`-1225))&&${};echo Merry Christmas ``` \*Thanks to @KenY-N for pointing out that the quotes in the echo can be removed, and to @IporSircer for reducing the condition size by 2 bytes. [Answer] # Groovy, 57 bytes ``` print new Date().format("Md")=="1225"?"Merry Christmas":b ``` Crashes on dates other than 25.12. with `groovy.lang.MissingPropertyException` because `b` is not defined. [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked/), 42 bytes [Try it here!](https://conorobrien-foxx.github.io/stacked/stacked.html) ``` ('Merry Christmas')'MMDD'date'1225'=¬#out ``` This creates a single-element array containing namely `'Merry Christmas!'`. After, it puts the date into a string with the month followed by the day. It checks for equality with `'1225'` (Christmas), inverts it with `¬`, then gets that member from the preceding array. If it isn't Christmas, this will error with an index error. Otherwise, it prints `Merry Christmas`. (Change the date in the string to see how it works on other days.) [Answer] ## Batch, 66 bytes ``` @echo off if %date:~0,5%==25/12 echo Merry Christmas&exit/b if ``` The trailing newline is significant, as it causes parsing of the `if` statement to fail. You may need to tweak the date check to match your local date format. [Answer] # Python 2, ~~69 77~~ 75 or ~~72~~ 70 Bytes ``` import time if time.strftime("%d%m")=="2512":print"Merry Christmas" else:1/0 ``` If it doesn't matter if it exits with an error when it is Christmas, then: ``` import time if time.strftime("%d%m")=="2512":print"Merry Christmas" 1/0 ``` EDIT: Thanks @Flp.Tkc for pointing out that I needed to raise an error -2 Bytes from @Max for pointing out about removing colons from the strftime function [Answer] # CJam, 28 ``` et[C25]#1="Merry Christmas"/ ``` [Try it online](http://cjam.aditsu.net/#code=et%5BC25%5D%231%3D%22Merry%20Christmas%22%2F) **Explanation:** ``` et push an array of current [year month day hour ...] [C25] push the array [12 25] (C=12) # find the position of the 2nd array within the first one 1= compare it with 1, resulting in 1 for 1 and 0 otherwise "Merry Christmas"/ split "Merry Christmas" into pieces of that length (it crashes if the length is 0) at the end, all the pieces are concatenated and printed automatically ``` [Answer] ## C#.NET, ~~180~~ ~~172~~ 171 bytes *Saved 8 bytes thanks to Kritixi Lithos* *Saved 1 byte thanks to Kritixi Lithos, again ;)* ``` namespace System{class P{static void Main(string[] args){var d=DateTime.Today;if(d.Day==25)if(d.Month>11){Console.Write("Merry Christmas!");return;}throw new Exception();}}} ``` Alternative, ungolfed variant: ``` namespace System //In System, so we don't have to use system. { class Program { static void Main(string[] args) //Main function. { var d = DateTime.Today; //Get Today. if (d.Day == 25) if (d.Month == 12) //Day has to be 25th, Month has to be 12nd. { Console.Write("Merry Christmas!"); return; //Prints. } throw new NotChristmasException(); //Errors/Crashes the program. } } class NotChristmasException : Exception { } //Holiday exception, hooray! } ``` [Answer] # Mathematica, 46 bytes ``` If[Today[[1,2;;]]=={12,25},"Merry Christmas!"] ``` [Answer] # Common Lisp, 140 ``` (let((m(multiple-value-list(decode-universal-time(get-universal-time)))))(if(and(eq(nth 3 m)25)(eq(nth 4 m)12))(write"Merry Christmas")(c))) ``` Crashes with undefined function if the date isn't right. [Answer] ## awk, 29 bytes (+ length("Merry xmas")) ``` v=1225==strftime("%m%d")||1/0 ``` Running it: ``` $ echo Merry xmas | awk 'v=1225==strftime("%m%d")||1/0' awk: cmd. line:1: (FILENAME=- FNR=1) fatal: division by zero attempted ``` Season greeting is piped to `awk`. `strftime` returns month+day (for example `1226`) and if it matches `1225` `$0` record gets outputed. Result of comparison `1225==1226` is placed to `v` var which is used to divide 1 if the date comparison fails. [Answer] ## Haskell, 116 Crashes with "Non-exhaustive patterns in function f" if it's not Christmas. ``` import Data.Time f(_,12,25)="Merry Christmas" main=getZonedTime>>=print.f.toGregorian.localDay.zonedTimeToLocalTime ``` Unfortunately, there's no function that allows you to just immediately get the time in a useful format, so most of this is converting the date formats. [Answer] # C#, ~~122~~ 104 bytes 18 bytes saved, thanks to @raznagul ``` using System;i=>{if(DateTime.Now.AddDays(7).DayOfYear==1)Console.Write("Merry Christmas");else{i/=0;};}; ``` It adds 7 days to the current day, and checks if it is the first day of the year, if yes, it displays "Merry Christmas", otherwise it divides by zero. [Answer] ## Ruby, 69 bytes ``` if Time.now.strftime("%j")=="360";puts "Merry Christmas";else 0/0;end ``` Works in 2016. Doesn't differentiate between normal and leap years, may need to be adjusted for non-leap years. [Answer] # ForceLang, 180 bytes ``` set s datetime.toDateString datetime.now() set t "Dec 25" def c s.charAt i def d t.charAt i set i -1 label 1 set i 1+i if i=6 io.write "Merry Christmas!" exit() if c=d goto 1 z.z ``` (Remember that `datetime.toDateString` is locale-dependent, so this may not work depending on your locale) [Answer] # C#, 90 bytes ``` using System;Console.Write(new[]{"Merry Christmas"}[DateTime.Now.AddDays(7).DayOfYear-1]); ``` Throws IndexOutOfRangeException if it's not christmas. [Try it here!](https://dotnetfiddle.net/6wbSVV) [Answer] # bash command line, ~~45~~ ~~48~~ 49 48 bytes ``` date +%m%d|grep -q 1225&&echo Merry Christmas||!- date +%m%d|grep -q 1225||!-;echo Merry Christmas ``` Similar to [Mitchell Spector's](https://codegolf.stackexchange.com/a/104609/63348), but use `grep` in silent mode to check for a match, then `&&` will ensure that it only prints on success, and the `||` causes it to look up history with `!-`, which gives me this: ``` -bash: !-: event not found ``` And it stops execution as `!- ; echo foo` demonstrates. The `bash` documentation says that `!-n` refers to the current command minus `n`, so perhaps it is being interpreted as `!-0`, which gives an identical (and non-localised) error message. ]
[Question] [ Help, I've been diagnosed with prosopagnosia! This means I'm no longer able to recognise faces.... :( Can you help me? # The challenge You will be given an image as a matrix of regular ASCII characters separated by new line characters, and your task is to determine if it contains a face. Faces will look something like the following: ``` o.o .7. ___ ``` Of course, people all look different - the only features that virtually everyone has are two eyes, a nose, and a mouth. For this challenge, eyes will be a lower-case `o`, a nose will be a `7`, and the mouth will be a line of underscores `_`. For this challenge, faces must have all of these features. To be specific, a face must have two eyes in the same row of the matrix, with a nose centred horizontally between them somewhere between the rows with the eyes and the mouth, and a mouth at the bottom of the face that is a row of underscores that extends all the way from the column of one eye to the other. Since a face must have a horizontally-centred nose, all faces must be an odd number of characters wide. Please note: The nose does not have to be centred vertically so long as it is between the rows of the eyes and mouth (exclusive). No other features of the face matter so long as the face has only two eyes, one nose, and one mouth - the "fill" of the face can be anything but the characters `o`, `7`, or `_` The output format is flexible - all you must be able to do is distinguish whether the image from the input has a face. You may use any output values to represent whether an image has a face (e.g. 1 if it does, 0 if it does not) # Examples/Test Cases ``` ...o.....o. ......7.... ..._______. ``` ^ contains a face ``` ...o.....o.o.o ......7.....7. ..._______.___ ``` ^ contains a face (actually contains two but your program does not need to care about any additional faces) ``` o.o...o..o o.7.7._.7. .._____7__ ``` ^ does not contain a face ``` o.o...o..o o...7...7. .._____7__ ``` ^ contains a face (notice the two differences between this case and the one above) ``` o...o .7... _____ ``` ^ does not contain a face, as the nose is not centred horizontally ``` ..o...o ....... ....... ....... ....7.. .______ ``` ^ contains a face formed by the last five columns ``` ,/o[]8o o198yH3 f_3j`~9 ()**&#^ *#&^79% 2______ ``` ^ contains a face (the last five columns form a face just like in the previous example, except with different filler characters that make it less human-readable) ``` o..o.o..o.o...o..o.o.o..o...o.o.o.o.o ......7....o7......7......7......7... ..7...............___......7....___.. ____.____.___._.._____.._____._______ ``` ^ contains a face (only the 3x3 face in the fifth-last through third-last columns is a face - all the other potential faces break one or more rules) ``` ..... .o.o. ..7.. ..... .___. ``` ^ contains a face ``` o7o ... ___ ``` ^ does not contain a face # A few extra clarifications -Faces will never be rotated -The `.`'s in the test cases could be any regular ASCII characters other than the three special characters, they are periods just for better readability -You can assume all matrices will be smaller than 100 x 100 # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code wins! [Answer] # JavaScript (ES6), ~~147 ... 140~~ 139 bytes Returns either *false* or a truthy value. ``` s=>(p='',g=k=>s.replace(/[^7o_]/g,0).match(`o${p}${p+=0}o${S=`.{${w=s.search` `-k}}(0${p+p}.{${w}})*`}${p+7+p+S}__{${k}}`)||w>0&&g(k+2))(2) ``` [Try it online!](https://tio.run/##bVFRT@MwDH7PrwiCW5J1ZN14CDspO50EiNMh8bDHsaVVSUtZr@k1BYRG@evDTemoAFuxHftL8tm5Dx9DG5VpUR3n5lbvYrmzck4LScgokRs5t7zURRZGmo6Xa2HUapyMfMb/hVV0RwNztC1qWJ70a4gXMuDbo@2TtNzqsIzuAhQcb@qa@g2mqF2xrtkwcIeEV3iLWinIAihgLy9Pc38wSOjGmzJGp2xX6v8PaakpiS1hwCS8vUgzvXjOIwokKrOoyjRPKOO2yNKKkpv8JgdgbMrzEPhRO8Ipw3KOI5Nbk2memYTSUlsssXdwEFPLGPYwAfVwm5eYTCY@KIhPlukK/8KEXv9lBP@E4OL3n6vzM0YYYzvOueHcWeQ8F41pYtUKR6gHAu3jwPahsBAyDgzLQChAVYtyEPEF0d70BdEUXQW5bEPiPdnKt140Xr0fGI3NcnUKT0xmp8@XJyhWJ/fB6wxRNhwODtdoeDhYi9kPNO0OmLZB/kGv23fhp@6N6I@i79B@t5dmPh8wt0Pd0JyBObXcO6fUvnV3pWk/SXRNu1bhe4xwrJrb3gA "JavaScript (Node.js) – Try It Online") ### How? We start with \$k=2\$ and \$p\$ set to an empty string. At each iteration, we first replace all characters in the input string \$s\$ other than `"o"`, `"7"` or `"_"` with zeros. This includes linefeeds. So the first test case: ``` ...o.....o. ......7.... ..._______. ``` is turned into: ``` flat representation: "...o.....o.¶......7....¶..._______." after replace() : "000o00000o00000000700000000_______0" ``` We then attempt to match the 3 parts of a face of width \$k+1\$. **Eyes** An `"o"` followed by \$k-1\$ zeros, followed by another `"o"`: ``` `o${p}${p+=0}o` ``` Followed by the padding string \$S\$ defined as: ``` `.{${w=s.search('\n')-k}}(0${p+p}.{${w}})*` \______________________/ \____________/ | right / left padding k+1 zeros +--> repeated any + same padding number of times ``` **Nose** \$k/2\$ zeros, followed by a `"7"`, followed by \$k/2\$ zeros, followed by the same padding string \$S\$ as above: ``` `${p+7+p+S}` ``` **Mouth** \$k+1\$ underscores: ``` `__{${k}}` ``` In case of failure, we try again with \$k+2\$. Or we stop as soon as the variable \$w\$ used to build \$S\$ is less than \$1\$, meaning that the padding string would become inconsistent at the next iteration. For the first test case, we successively get the following patterns: ``` o0o.{9}(000.{9})*070.{9}(000.{9})*__{2} o000o.{7}(00000.{7})*00700.{7}(00000.{7})*__{4} o00000o.{5}(0000000.{5})*0007000.{5}(0000000.{5})*__{6} ``` The 3rd one is a match. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~61~~ ~~60~~ 57 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 3тŸãε`I€Œsδùø€Œsδù€`}€`ʒćÁ„ooÅ?sRćÙ'_Qs€Ås7¢y¨J…_7oS¢2ÝQP ``` Input as a list of lines. Outputs a list of valid faces as truthy, or an empty list `[]` as falsey. If this is not allowed, the `ʒ` can be `ε` and a trailing `}à` has to be added, to output `1` for truthy and `0` for falsey. [Try it online](https://tio.run/##yy9OTMpM/f/f@GLT0R2HF5/bmuD5qGnN0UnF57Yc3nl4B4INZCXUgohTk460H2581DAvP/9wq31xEJA3Uz0@sBgod7i12PzQospDK7weNSyLN88PPrTI6PDcwID//6OVdPTzo2Mt8pV0lPINLS0qPYyBrLR446yEOksgS0NTS0tNOQ7I0lJWizO3VAWyjOLBQCkWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU3lo5aHdOlxK/qUlUJH/xhebju44vPjc1oRD6x41rTk6qfjclsM7D@9AsIGshFoQcWrSkfbDjY8a5uXnH261Lw4C8maqxwcWA@UOtxabH1pUeWiF16OGZfHm@cGHFhkdnhsY8L9W59A2@//R0Ur5evlKOkp65npAMj4@XilWRyFaSU9PL19PD0yCJMHAHERAePEQoIehGGoYQj3EXCQtcCvywZqAGKQjH6jOXC8ephqs1ByHSojJOFTqwXyjB/UPwkdwSQjAwzKHsOKRtOvo50fHWoAdYGhpUelhDGSlxRtnJdRZAlkamlpaaspxQJaWslqcuaUqkGWErD0fEjh6CK/A@DAmRsjlmyMHIzIFVgflwwEobBEKwTxoAOjBCGD4QvwEo@JhTowFAA). (Sometimes times out for the last biggest test case.) **Explanation:** Step 1: Transform the input into \$n\$ by \$m\$ blocks: ``` 3тŸ # Push a list in the range [3,100] ã # Create all possible pairs by taking the cartesian product ε # Map each pair [m,n] to: ` # Pop and push the m,n separated to the stack I # Push the input-list € # For each row: Œ # Get all substrings δ # For each list of substrings: s ù # Keep those of a length equal to `n` (using a swap beforehand) ø # Zip/transpose; swapping rows/columns # (we now have a list of columns, each with a width of size `n`) € # For each column of width `n`: Œ # Get all sublists δ # For each list of sublists: s ù # Keep those of a length equal to `m` (using a swap beforehand) €` # And flatten the list of list of lists of strings one level down }€` # After the map: flatten the list of list of strings one level down ``` [Try just this first step online.](https://tio.run/##yy9OTMpM/f/f@GLT0R2HF5/bmuD5qGnN0UnF57Yc3nl4B4INZCXUgoj//6OVdPTzo2Mt8pV0lPINLS0qPYyBrLR446yEOksgS0NTS0tNOQ7I0lJWizO3VAWyjOLBQCkWAA) Step 2: Keep the \$n\$ by \$m\$ blocks which are valid faces: ``` ʒ # Filter the list of blocks by: ć # Extract the first row; pop and push the remainder-list and first row # separated to the stack Á # Rotate the characters in the string once towards the right „ooÅ? # Check if the string now starts with a leading "oo" s # Swap to get the remaining list of rows R # Reverse the list ć # Extract head again, to get the last row separated to the stack Ù # Uniquify this string '_Q '# And check if it's now equal to "_" s # Swap to get the remaining list of rows € # For each row: Ås # Only leave the middle character (or middle 2 for even-sized rows) 7¢ # Count the amount of 7s in this list y # Push the entire block again ¨ # Remove the last row (the mouth) J # Join everything else together …_7oS # Push string "_7o" as a list of characters: ["_","7","o"] ¢ # Count each in the joined string 2Ý # Push the list [0,1,2] Q # Check if the two lists are equal P # And finally, check if all checks on the stack are truthy # (after which the filtered result is output implicitly) ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~264~~ \$\cdots\$ ~~223~~ 222 bytes Saved a whopping 16 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!!! Saved a byte thanks to [Tanmay](https://codegolf.stackexchange.com/users/96037/tanmay)!!! ``` import re b='[^o7_]' def f(l): while l: s,p=l.pop(0),1 while m:=re.compile(f'o{b}+o').search(s,p-1): a,p=m.span();d=p-a;e=d//2 if re.match(f'({b*d})*{b*e}7{b*e}({b*d})*'+'_'*d,''.join(s[a:p]for s in l)):return 1 ``` [Try it online!](https://tio.run/##jVPbjpswEH3nK6xddW2zrLMklZxkxXuf@gOUUBKMwgoYyxC1q1X666kv4RIlqWrEeM7YZzye8ciPbg/NYinV6VTWElSHlPC2EY43wNMEe7koUEEquvbQr31ZCVRpDbWBjComQZJXGoTa4NbqdaQE20EtNSIFhs/t8RkwZa3I1G5PNO0lNK4QyrSHmrUyawh9yyP5kr2JKJ/N5maxLHQUrM46zSkw@dz6@ZH6ehJHbmVvws84xX4eYMzeoWxIG2drmRSgUIvKBlWUrpXoDqpB4akTbdeiCBEPkVif8sAYA8asfAjOBj24EYMhdcMakgCFNLhB19@VBy2vnOj/2g9YN/o/@wDN5Cyd8C2ZD9zv0Ih/0V0Ad@kXRw80y3Gq3X/zLHfji7uy/wF8AOnU@SSSYAZxsuyvEK6WH98WDhTp4v3nn5UDhPr@0@PGAf/xacNXXxyY3/MMrkBszFOPe/VW9YBPSzmd@q1n0zBMfce9Fo3pZL3QdXU56Kf0XtzTFMLkifKLLI9pvfFCgY8XG2K5LCz1lGmJA/5xmPOvOxwgp4YLTD3TR6ZrAiR@S7HrTEvZLrIdjEwzFcQYqMVSlU2ne1zFeiU6cxJ6@gs "Python 3.8 (pre-release) – Try It Online") Inputs a list of strings. Outputs \$1\$ for a face, `None` otherwise. **How** Looks for pairs of eyes in each row, starting from the top, by repeatedly removing the top row from the input list. If a pair is found, the columns forming the pair are taken from the remaining rows and concatenated together. This string is then tested against a regex constructed from the distance separating the eyes to see if we've found a face. If not, we continue scanning the current line, beginning at the stage-left eye, looking for more pairs before moving onto the next row. [Answer] # Regex (PCRE2), ~~203~~ ~~193~~ ~~177~~ 181 bytes ``` /((?|^()|^(?:.(?=.* (\2.)))+){2}(?(8)(?=\8$)(?|()|(?:(?6)(?=.+((?6)\3)\7$))++){2}((?6)|(?!\5)7())\3(?=\7$)|o([^o7_])+o)(?|()|\7(?:.(?=.* .*(.\7)))+){2} (?=\2(.*)))+\5.*(?=\8)_+\7$/m ``` [Try it on regex101](https://regex101.com/r/yZqn7p/21) ### Explanation `((?|^()|^(?:.(?=.*\n(\2.)))+){2}(?(8)(?=\8$)(?|()|(?:(?6)(?=.+((?6)\3)\7$))++){2}((?6)|(?!\5)7())\3(?=\7$)|o([^o7_])+o)(?|()|\7(?:.(?=.*\n.*(.\7)))+){2}\n(?=\2(.*)))+` Main loop. Matches everything except for the mouth: `(?|^()|^(?:.(?=.*\n(\2.)))+){2}` - on each line, match the padding to the left of the face, while counting a matching number of characters of padding into `\2` from the start of the next line. This needs to use a Branch Reset Group `(?|`...`)` in order to initialize `\2` to empty with `^()` before building it up one character at a time with `(\2.)`. The `{2}` guarantees that both stages will execute exactly once, and do so in the correct order due to each one having a `^` anchor (which matches the start of any line due to the `/m` flag). Replacing the `{2}` with `+` wouldn't work because a loop will immediately terminate after any optional iteration that matches zero characters. Note that in the case of zero padding, the first stage will execute twice in a row. `(?(8)`...`|`...eyes...`)` - Only allow matching the eyes if we haven't already captured `\8`, i.e. iterated through the main loop at least once. `(?!\7)o([^o7_])+o` - match the eyes, and define the subroutine `(?6)` to do `[^o7_]`. `(?=\8$)(?|()|(?:(?6)(?=.+((?6)\3)\7$))++){2}((?6)|(?!\5)7())\3(?=\7$)` - Match the facial part of a row either containing no facial features, or containing the nose. `(?=\8$)` - assert that we're starting at the proper column, which was marked when the previous row was processed `(?|()|(?:(?6)(?=.+((?6)\3)\7$))++){2}` - build up the facial part of the row one character at a time on the left and right ends. The right part is built up in `\3`. Both ends a built towards the center. The `++` ensures this is done the maximum number of times; with an even length both ends would meet, and with an odd length one character is left between them. This uses a Branch Reset Group and `{2}` the same way as before, except that we guarantee both stages execute in the correct order differently. The `++` guarantees the second stage won't execute twice. The fact that an empty match would result in `(?=\7$)` failing to match guarantees that the first stage executes first. The fact that executing the two stages in the wrong order would result in too-long row (with the previous value of `\3` tacked in) guarantees the stages execute in the correct order. `((?6)|(?!\5)7())` - match either the absence of a nose or a nose. `(?6)` matches the absence of a nose, and `(?!\5)7()` matches a nose; `()` here sets `\5` to mark the fact that we've matched a nose, and `(?!\5)` prevents matching a nose if we've already done so. `\3` - match the right half of the facial part of the row, which we built up. `(?=\7$)` - assert that we're now at the first column directly to the right of the face. `(?|()|\7(?:.(?=.*\n.*(.\7)))+){2}` - match the padding to the right of the facial part of this line, while counting a matching number of characters of padding into `\7` from the corresponding part of the next line. Uses the same Branch Reset Group `{2}` trick as before, except that we guarantee both stages execute in the correct order in yet another different way. Sticking a `\7` in front of the second stage forces it to match too many characters if it tries to execute the second stage first, because the previous value of `\7` will be concatenated to the desired number of characters, which would only match in invalid input that has a line longer than the previous line. And the subsequent `\n` (seen below) prevents the first stage from executing twice on any valid input, because that would only match on a line shorter than the previous line. Note that in the case of zero padding, the first stage will execute twice in a row. `\n(?=\2(.*))` - match the end of the current line, and capture a marker for the desired starting column of the facial part of the next row in `\8`. Upon finishing the main loop, we reach `\5.*(?=\8)_+\7$`: `\5` - assert that we matched a nose. `.*(?=\8)` - skip to the correct starting column, as marked when the previous line was processed. `_+` - match the mouth. `\7$` - assert that the mouth ended at the proper column. # Regex (PCRE2), ~~363~~ ~~322~~ ~~283~~ ~~199~~ ~~182~~ ~~184~~ 186 bytes This version goes above and beyond the problem statement, allowing the input to have variable-length lines. ``` /((?|^()|^(?:.(?=.* (\2.)))+){2}(?=(?(8)(?=\8\9)(?|()|(?:(?6)(?=.+((?6)\3)\9))++){2}((?6)|(?!\5)7())\3(?=\9)|o([^o7_ ])+o)(.*))(?|()|\8(?:.(?=.* \2(\8.)(\C*)))+){2}\7 )+\5.*(?=\8)_+\9$/m ``` [Try it on regex101](https://regex101.com/r/o0A94M/42) ### Explanation `((?|^()|^(?:.(?=.*\n(\2.)))+){2}(?=(?(8)(?=\8\9)(?|()|(?:(?6)(?=.+((?6)\3)\9))++){2}((?6)|(?!\5)7())\3(?=\9)|o([^o7_\n])+o)(.*))(?|()|\8(?:.(?=.*\n\2(\8.)(\C*)))+){2}\7\n)+` Main loop. Matches everything except for the mouth: `(?|^()|^(?:.(?=.*\n(\2.)))+){2}` - on each line, match the padding to the left of the face, while counting a matching number of characters of padding into `\2` from the start of the next line. This needs to use a Branch Reset Group `(?|`...`)` in order to initialize `\2` to empty with `^()` before building it up one character at a time with `(\2.)`. The `{2}` guarantees that both stages will execute exactly once, and do so in the correct order due to each one having a `^` anchor (which matches the start of any line due to the `/m` flag). Replacing the `{2}` with `+` wouldn't work because a loop will immediately terminate after any optional iteration that matches zero characters. Note that in the case of zero padding, the first stage will execute twice in a row. `(?(8)`...`|`...eyes...`)` - Only allow matching the eyes if we haven't already captured `\8`, i.e. iterated through the main loop at least once. `o([^o7_\n])+o` - match the eyes, and define the subroutine `(?6)` to do `[^o7_\n]`. We need to explicitly exclude `\n` because otherwise the first row of the facing (containing the eyes) could be matched with newline(s) included between the eyes, which if orchestrated just right, could result in fooling the rest of the algorithm into matching a face. An alternative way of preventing this would be to capture `\7` using `(\C*)` instead of `(.*)` (which a previous version did), i.e. capturing everything to the end of the string (including newlines) instead of just to the end of the current line, but this results in worse golf, because we would also need to do `(?=\7).*\n` instead of `\7\n`, costing 6 bytes total. `(?=\8\9)(?|()|(?:(?6)(?=.+((?6)\3)\9))++){2}((?6)|(?!\5)7())\3(?=\9)` - Match the facial part of a row either containing no facial features, or containing the nose. (Do this in a lookahead so that we can iterate a second time over the same characters, in order to count them.) `(?=\8\9)` - assert that we're starting at the proper column, which was marked when the previous row was processed `(?|()|(?:(?6)(?=.+((?6)\3)\9))++){2}` - build up the facial part of the row one character at a time on the left and right ends. The right part is built up in `\3`. Both ends a built towards the center. The `++` ensures this is done the maximum number of times; with an even length both ends would meet, and with an odd length one character is left between them. This uses a Branch Reset Group and `{2}` the same way as before, except that we guarantee both stages execute in the correct order differently. The `++` guarantees the second stage won't execute twice. The fact that an empty match would result in `(?=\9)` failing to match guarantees that the first stage executes first. The fact that executing the two stages in the wrong order would result in too-long row (with the previous value of `\3` tacked in) guarantees the stages execute in the correct order. `((?6)|(?!\5)7())` - match either the absence of a nose or a nose. `(?6)` matches the absence of a nose, and `(?!\5)7())` matches a nose; `()` here sets `\5` to mark the fact that we've matched a nose, and `(?!\5)` prevents matching a nose if we've already done so. `\3` - match the right half of the facial part of the row, which we built up. `(?=\9)` - assert that we're now at the first column directly to the right of the face. `(.*)` - capture a marker `\7` for the column directly to the right of the facial part of the current line `(?|()|\8(?:.(?=.*\n\2(\8.)(\C*)))+){2}` - match the facial part of the current line again, this time to count the characters in it, so as to build up a capture in `\8` of a matching number of characters from the facial part of the next line, as a marker for column alignment, and capture in `\9` a marker for the column directly to the right of the facial part of that line. Uses the same Branch Reset Group `{2}` trick as before, and a very similar way of guaranteeing that both stages execute in the correct order. Sticking a `\8` in front of the second stage forces it to match too many characters if it tries to execute the second stage first, because the previous value of `\8`, not having been emptied by running the first stage, will be concatenated to the desired number of characters; this prevents `\7\n` from matching later. And a match can't result from executing the first stage twice – doing so would match an empty row, but the lookahead that matched the facial row the first time already guaranteed that it's of nonzero length. `\7\n` - match the non-facial ending of the current line, ensuring that we ended on the correct column. Upon finishing the main loop, we reach `\5.*(?=\8)_+\9$`: `\5` - assert that we matched a nose. `.*(?=\8)` - skip to the correct starting column, as marked when the previous line was processed. `_+` - match the mouth. `\9$` - assert that the mouth ended at the proper column. *+2 bytes (184 → 186) to fix a bug found by [jaytea](https://codegolf.stackexchange.com/users/75057/jaytea)* [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~85~~ 77 [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 monadic function taking a matrix of characters as argument. ``` 1∊∊{⍵∘{(⍉3,⍨a⍪⍵⍪⊖a←2↑⍨2 1÷⍨⍺-1)⍷4-'_o7'⍳A}¨0,¨↓∘.=⍨⍳¯2+2⌷⍵}¨1 2∘+¨2 1∘ר⍳⍴A←⎕ ``` [Try it online!](https://tio.run/##hVHNSsNAEL73KQLFbpImq9kI2xw89OY7iI0BUZDC5lqKHmMsrljEn0cIXjzUUvCYvsm8SJzdJLbRSDfZmW92v292ZzaKx@75JBqLywLS27jwIJ3hPwW5hPRtaoK88x2QWQTyXa2hnb1EkDwySOa4zgxvvUIP8sv1LJCrQ5eEghOQi@F1nh04eQbJE6aiR5q1yD9Yn8E9apa47xkM9/q5yoNg/ZorDsjPIR4BD8/qUkXcQaTiZE4opYJSbYlBNKJcmTIKy0FJ5x8Rfk0d2qYUZ1MttBinUgrkcxrWKi3hOxTlSTsUJVkz0WvW7yIqksmxP4QSqxWRqjKVLGxJ4@yLk9OBvpgXDCbHPqKL0L86uwkQmZZt97ojRHa3N@LBHiLWlkaUzaSbUuu4hn86Lfh227ed5lXxz1BvsSHqqGoMrQ2@Q1lj7ao3JMU3 "APL (Dyalog Unicode) – Try It Online") *-8 bytes thanks to @Adám* ### Interesting Bits This ends up encoding `eyes=2, nose=1, underscore=3`. ``` 1 2∘+¨2 1∘ר⍳⍴A←⎕ ⍝ Get at least all sizes (m,n) that fit in A such that ⍝ m is odd and n≥3 (surely this can be done shorter) ⍝ The search arrays are constructed transposed, so m ends ⍝ up being the width 0,¨↓∘.=⍨⍳¯2+2⌷⍵ ⍝ For a given height m, get all nose positions ⍝ e.g. m=3 gives (0 1 0 0)(0 0 1 0)(0 0 0 1) (2 1÷⍨⍺-1)↑2 ⍝ My favorite expression. Generates one-half of the face ⍝ ⍺ is (m,n), so (2 1÷⍨⍺-1) gives dimension pair ((⍺-1)÷2) (⍺-1) ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~129~~ 120 bytes ``` T`o7\_p`o7=- ((?<=(.)*)(?(1)\3-7-\3|o((-)*)-\3o).*¶(?>(?<-2>.)*)((?<=(.)*)-\3-\3-.*¶(?>(?<-6>.)*))*){2}(?>(?<-4>==)*)=== ``` [Try it online!](https://tio.run/##K0otycxL/P8/JCHfPCa@AEja6nJpaNjb2GroaWppathrGGrGGOua68YY1@RraOgCxYDMfE09rUPbNOztgAp1jezAKuF6gPIghKTCDKwCiKqNaqFCJna2tkABW1vb//919POjYy3yufINLS0qPYy50uKNsxLqLLk0NLW01JTjuLSU1eLMLVW5jOLBAAA "Retina 0.8.2 – Try It Online") Outputs 0 if there is no face, otherwise a positive integer number of nonoverlapping faces. Edit: Bug fix for minimal-width faces and saved 9 bytes thanks to @Deadcode. Explanation: ``` T`o7\_p`o7=- ``` Transliterate everything other than `o`, `7` and `_` to `-`. `_` gets transliterated to `=` as that avoids having to quote it again. (I used `-` as I find spaces confusing.) The next stage then defaults to a match count stage. ``` ( ``` Group 1 is just here so that it can be repeated. ``` (?<=(.)*) ``` Count the current indentation into capture group 2. ``` (?(1)\3-7-\3|o((-)*)-\3o) ``` If capture group 1 has already been matched, then match `-7-` surrounded by capture group 3 (the nose), otherwise match `o`, a string of `-`s into capture group 3 and its count into capture group 4, another `-`, a copy of capture group 3, and a final `o` (the eyes). ``` .*¶(?>(?<-2>.)*) ``` Match until the same amount of indentation on the next line. ``` ((?<=(.)*)-\3-\3-.*¶(?>(?<-6>.)*))* ``` Optionally match any number of lines containing three `-`s and two copies of capture group 3 (empty line), keeping track of and advancing to the same amount of indentation on the next line using capture group 6. ``` ){2} ``` Match this whole group twice. ``` (?>(?<-4>==)*)=== ``` Match two `=`s for each `-` captured in capture group 4, plus a final three `=`s (mouth). Here as in the previous two cases of balancing groups, the atomic group requires that any available `=`s are matched against the balancing group, so that the whole regex fails if there aren't three `=`s left over. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~90~~ 85 [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 character matrix argument. Requires `⎕IO←0` (0-based indexing). ``` 1∊∘∊{(∊¨1↑¨¨⍨1+⍳1,⍨⊣\⍴⍵)∘.⍀{'_'⍪⍨(⊢,0 1↓⌽)' 7',⍨2↑'o',1⍵⍴''}¨⍳⊢/⍴⍵}⍷¨∘⊂' '@(~∊∘'o7_') ``` [Try it online!](https://tio.run/##hVFBSwJBFL73KwTJ2bVtdPUwegu66CnIbpWbEAYhTFcRJQpElkaKCDrXZYmgg0WnLvtT3h/ZvpnZTS3DWfbN93a/75v33nQuetun/U5PniU0fWju0fi2nPg0CWnyiDhwEOLIp/FdHMURqcjfIjXzPSAKn49IvZP6cEHmpC4HLGCkXvDPofDJK@egu6ebL5flBNOSCnyYZJ4PEaSMDbXnDOSSdRqS@sQnnB1esRzbcUa2FCZFwNyki/JITSm8JvUKRfxWhSMKb@3vIh40mq2kmwPSPBzFOZecmwg3g7jQwWaBXZxt/CPCs6xDXJbiXVZLI8arlRJ8wYNMZSRijcKetEZhyYaJ3bB@N5GSHKEHzZm7ErG0M20WrLDxSvLwuGYK8@u1fqMK1A2q5yejOpDjFouFfBuomC@0RX0TqLLKRtph8nmrWZ7BP5OWYnHsi5vhpfnP0ncxJ5osHQzPAu7B9pht6R2ybw "APL (Dyalog Unicode) – Try It Online") This works by brute force; generating all possible faces and looking for them in turn. `' '@()` amend with spaces **at** the locations indicated by the following mask:  `∊∘'o7_'` membership of the set of special symbols  `~` negate that This replaces all non-special characters with spaces. `{`…`}⍷¨∘⊂` mask where each of the following have a top-left corner in the entirety of that:  `⍴⍵` the shape of the argument (rows, columns)  `⊢/` the rightmost element of that (columns)  `⍳` the indices 0…n-1 of that.  `{`…`}¨` apply the following function on each index:   `1⍵⍴''` create 1-row argument-column matrix of spaces   `'o',` prepend a column of eyes   `2↑` append a blank row (lit. take the first two rows)   `' 7',⍨` append a column consisting of a space above a nose   `(`…`)` apply the following tacit function to that:    `⌽` mirror the argument (puts the nose column on the left)    `0 1↓` drop no rows but one column (removes the nose column)    `⊢,` prepend the argument (this creates the full eye and nose rows)   `'_'⍪⍨` append a row of underscores (to form the mouth) This gives us a collection of all possible three-row faces.  `(`…`)∘.⍀` create all combinations of the following masks expanding (inserting blank rows on zeros) those faces:   `⍴⍵` the shape of the argument   `⊣\` two copies of the row-count (lit. cumulative left-argument reduction)   `1,⍨` append a one   `⍳` the Cartesian coordinates of an array of that size   `1+` increment   `1↑¨¨⍨` for each of each of those, create a mask of length with a single leading one (lit. take that many elements from one)   `∊¨` **ϵ**nlist (flatten) each  This gives us all the possible expansion masks  `∊` **ϵ**nlist (flatten) `1∊∘` is one a member thereof? [Answer] # [Python 3](https://docs.python.org/3/), 213 bytes Returns `False` when it finds a face and `True` when it doesn't. ``` lambda s:all(re.subn(f"\\n.{{{p}}}[^o_7]{{{g}}}7[^o_7]{{{g}}}",'',x)[1]-1for p in range(len(s))for g in range(len(s))for x in re.findall(f"^.{{{p}}}o[^o_7]{{{2*g-1}}}o([\S\s]+)^.{{{p}}}__{{{2*g}}}",s,8)) import re ``` The idea is that for each possible face size and indention, we look for eyes and a mouth in correct location (ignoring noses), then make sure there is exactly one nose that is centered. `p` is the left padding of the face, `g` is the gap from face edge to nose, and `8` is the value of `re.MULTILINE`. [Try it online!](https://tio.run/##bVJfb4IwEH@/T0Ew05ZhF/ShauL73vcI2GEExoItoSzRGPfVWXsIsrlrete7@7X3r9W5@VBy2WbbqC2T4/6QOHqTlCWpU6a/9pJkbhRJdrlcquv1Gu6U4LFRcqPwX5rrz2b@iYZBPA8yVTuVU0inTmSekjKVRFNqrfm/1hNaU5YV8mBjZ@6uj6iGIAsvnwfWQsLoLdLxMx1AQnR@TEP7K0qhOFaqbsyjbZPqRm9d12WMKcaQA0rGLbNn0REDGIHMGuMMH0PNBlAINluZIzdLdCiE8AdE99IDwjrRA2i1SdyMHf0ruZXidsF/UWG8MiGC9er8uoRMLD/fv9dAqOdNJzvwJtMdXz/Bor@gugLZPb1e749/qld83IqxgEEbyPbnDkMN@qYhM33qcu@FEEPp@KTqhsT7orFUMx7FMSvouw/YTY4GM2IA@53sxO2PwskzXZVFQ9xIRtKlG3AMVXUhG2LdvpOhpLT9AQ "Python 3 – Try It Online") [Answer] # PCRE2, 168 bytes ``` (?=(?13)(.*))o(?6)*(?=(?13)(.*))o((?=(.*?)(.\5|(?13)\2$)|)([^7o_]|(?!\7|(?5))\4()7)(((?=(?13)(.+\1|(?!.*\2)))\C)+(_+()((.(?=(.*+\C+?)(.\16?$)))*+\15?+)(?10))?)?)++\7\12 ``` <https://regex101.com/r/dHsdBq/2> @Deadcode made me do it :P It's theoretically valid but fails that one test because of catastrophic backtracking. Bonus: <https://regex101.com/r/dHsdBq/3> 166 bytes, PCRE1 (dropped both possessive `+`s in `(?13)`) The general method: `(?13)` will jump from the current point to the same position on the very last line of the subject. So, at any point in the face, you can compare what is captured in `(?=(?13)(.*))` to that captured at any other point in the face, particularly following the eyes (`\1` and `\2`, in order to determine whether or not you're in the face. `(?=(?13)(.+\1|(?!.*\2))` is therefore true when you're not in a face. The regex goes through face characters one at a time, but consumes at once characters from the end of the face on one line to the start of the face on the next. While doing so, it also optionally tests for a mouth. `(?=(.*?)(.\5|(?13)\2$)|)` is used to locate the nose in the middle of the face. It collects in `\5` characters from the end of the face on the current line, so that `(.*?)` finally matches the empty string once the middle of the face is reached. [Answer] # [J](http://jsoftware.com/), 101 93 99 97 bytes ``` 1 e.[:,>@{@;&(1+i.)/@$(((-:1 2 3*[:#:i:@_1+2^<:,<.@-:,])*2|]){:@$)@((4|'ao7_'&i.)-.0{0:"+);._3"$] ``` [Try it online!](https://tio.run/##jVJLb8IwDL7nV1jA2qQ0po9JgcCmTGhoB05sO6GSTRNocMl5Au2vd2naQocGXSLbSZTPj8/e5R30N3AnwYcQIpBWOMJ0MZ/lMaxxKcN7tVdjj8b9LbKB6lFKuYwhgTRYyq7cSqXjfrKayHCCisswY0FyyNheqh5TlN4e/HcjtO9ZNMdoH8lOn41Rp51eljNC1h@fBnzO4WXx@gic@9UTbIBm9l/CiqwigogG0WniLIpCFWddLiSsHWt3E25104OVi06M82HFEFPBHdghxRVgGbwOi39aUdgyiYt@woFZZkMbPR4Nv55SstHp7u17RCgLAq@7IkHXW4nRDUla/JiSBzwVVN/r4xlJRjQZaxpyvB1XQePpm7uRmlunUFec1Ua35FuxZMrOi5o5x5fr@WmGZg/z52tD9KuHwm79zx5WHXQ1t7ArHHekpSLTHOWzSbZF5T8 "J – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 290 bytes ``` int D(String[]t){for(int a=0,z=t.length,y=t[0].length();a<z;a++)for(int b=0;b<y;b++)for(int c=b+2;c<y;c+=2)for(int d=a+1;d<z;d++)for(int e=d+1;e<z;e++)if(t[a].charAt(b)=='o'&&t[a].charAt(c)=='o'&&t[d].charAt((b+c)/2)=='7'&&t[e].substring(b,c+1).replace("_","").isEmpty())return 1;return 0;} ``` [Try it online!](https://tio.run/##lVVNb6MwED3Dr7CoNrUD64RUFU0ph5W6Ui976iVSmmYNOAlZghE4adMo@9eztoFAUtpVjWQzbz7wvJkRS7Ih31lKk2X456Cnaz@OAhDEJM/BLxIlYKfrWonmnHBxbFgUgpXQwUeeRcl8PAEkm@dImWrK6RV4IKEvKgJEroCPppzmPBfqHdAAMBjGmD0lBjBBr2cLO7EEjLGDcQEfsalchqU3jLB0l/tT1hZDLkdulbqpmxYLfxBRPP8JKvbP4p5d1uqx8eSmJVVmD2@2D1dngWbTq@Xvv8MzFKJut3PxfIZ2LzrPzvDbGTqYthFWsXqSk8z2XSLvC9BwrzGZqsJOzZqfZQWfxVa9MFxK5fMp1cxp8t482q59suT9aicltfQVrjY8LStYHdP3NJ70bL/@dst9jr61s9Pm2uZoKGHv6sp7xjJQzpsaIXBbTBKSVo/bnNMVZmuOU2HB4wS@4nsoDXCexhGHhoiPEJLBtL2uH4QRuD/OL0c7ER9KkHh9683jOKbJnC@srcfH/UkpiUkmd28uMU1Umfte3/Xvtq7fwALPNwduINDA9AZHOPSIabuhCBA2jKkXCpQKlAo0mkE@JhMcLEj2g0Mfed4lu@x0mmBQg@ERhL4ZoN5AqhylohOcr/1cJQh9KzBthDOaxiSg0BAlMQyEo/znKuVbiFBG@TpLgO2WL313f9D1Xo@ADckikvBbwZvPWExJAmiTN1HHl4gvwKio0Vc4lJVr41HV/QMyiwZpp7TQae3MlkpNMDxSHFuSXNu2O51SDppyOLFqSq@vv85o9T2tZJRnayr/A6U4I3GuZNmOmrzuqOpuYilC0K40JXU3uHs5DPvDPw "Java (OpenJDK 8) – Try It Online") Takes a String[] broken at the lines as input and outputs 1 and 0 for true and false ]
[Question] [ **Introduction** Clarence is a data entry clerk who works at an internet service provider. His job is to manually enter the IP addresses of all of the ISP's customers into the database. He does this using a keypad which has the following layout: ``1````2````3`` ``4````5````6`` ``7````8````9`` ``.````0`` The distance between the centre of horizontally or vertically adjacent keys is exactly one centimetre. For instance, the distance between the centres of `3` and `9` would be two centimetres. The distance between the centres of `3` and `5` would be √2cm. The Pythagoras theorem is sufficient to calculate the distance between any two keys. Clarence, as you might expect from one who works in an ISP, uses a very slow and inefficient system of typing. He uses a single finger and searches for the key, and then moves his finger to the key, then presses it, and repeats for all of the digits in the number. You might know of this style as the "eagle search system" since the finger searches above the keyboard for the correct key before plunging down for the keypress, like an eagle plunging down for a kill. For example, here is how Clarence would type out the number `7851`: 1. He starts his finger at `7` and pushes the key. 2. He moves his finger to the right 1cm to `8` and pushes the key. 3. He moves his finger upwards 1cm to `5` and pushes the key. 4. He moves his finger diagonally upwards and left √2cm to `1` and pushes the key. Therefore the total distance that Clarence moved his finger to type in `7851` is `1 + 1 + √2` which is about 3.41cm. Your task is to write a program that calculates the distance Clarence must move his finger to type in arbitrary IP addresses. **Input Description** Input is a string that will be in the form `().().().()` where each `()` is an integer in the range `0` - `999`. This represents the IP address that Clarence must type in. An example input might be: `219.45.143.143` I would also like to point out that inputs such as `0.42.42.42` or `999.999.999.999` are still valid inputs, despite the fact that they are invalid IP addresses. So you don't need to include any IP address verification code in your program. **Output Description** Output the distance that Clarence must move his finger in order to type in the specified IP address. Round answers to two decimal places where needed, and use the `cm` unit in your output. The output for the example input is `27.38cm` (1 + √8 + √5 + 2 + 1 + √5 + 3 + 1 + √5 + √13 + 3 + 1 + √5). [Answer] # CJam, ~~46~~ ~~44~~ ~~43~~ ~~38~~ ~~37~~ 34 bytes ``` rA,sd`f#3fmd2/2ew::.-::mh:+2mO"cm" ``` *Thanks to @user23013 for suggesting `mh`, which made it possible to save 5 bytes.* Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=rA%2Csd%60f%233fmd2%2F2ew%3A%3A.-%3A%3Amh%3A%2B2mO%22cm%22&input=219.45.143.143). ### How it works ``` r e# Read a token from STDIN. A, e# Push [0 1 2 3 4 5 6 7 8 9]. s e# Stringify: [0 1 2 3 4 5 6 7 8 9] -> "0123456789" d e# Cast to Double: "0123456789" -> 123456789.0 ` e# Inspect: 123456789.0 -> "123456789.0" f# e# Push the index of each character from the input in "123456789.0". 3fmd e# Push the quotient and residue of each index divided by 3. 2/ e# Split the resulting array into pairs. 2ew e# Convert the array of pairs in the array of all overlapping pairs of pair. ::.- e# Reduce each pair using vectorized difference: [[a b][c d]] -> [a-b c-d] ::mh e# Reduce each reduced pair to its 2-norm distance: [a b] -> sqrt(aa + bb) :+ e# Sum all distances. 2mO e# Round to two decimal places. "cm" e# Push "cm". ``` [Answer] # Pyth, ~~38~~ ~~35~~ 34 bytes ``` +.Rs.aM-M.:m.jF.Dx`ciUTT1b3z2 2"cm ``` [Demonstration.](https://pyth.herokuapp.com/?code=%2B.Rs.aM-M.%3Am.jF.Dx%60ciUTT1b3z2+2%22cm&input=219.45.143.143&debug=0) Indexing into the string of a float idea thanks to @Dennis. Explanation, on the phony input `15.0`: * First, we take the input. It is implicitly stored in `z`. '15.0' * We map this list as follows: `m.jF.Dx`ciUTT1k3z`. + `UT`: We generate the list `[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]`. + `iUTT`: Next, we treat this list as a base 10 number giving us `123456789`. + `ciUTT1`: Next, we convert this number to a float by floating point dividing it by 1, giving `123456789.0`. + ```: Convert to a string. `'123456789.0'` + `x k`: Take the index of the input character in that string. `[0, 4, 9, 10]`. + `.D 3`: `.D` is the divmod function, outputing its first input divided and modulo'd by the second input. The second input is 3, here. This gives the physical location of the character on the numpad. `[(0, 0), (1, 1), (3, 0), (3, 1)]`. + `.jF`: `.j` is the complex number constructor. `F` applies it to the tuple. `[0j, (1+1j), (3+0j), (3+1j)]`. * `.: 2`: Now, we take the 2 entry substrings of this list so we can find the pairwise distances. `[[0j, (1+1j)], [(1+1j), (3+0j)], [(3+0j), (3+1j)]]`. * `-M`: Takes the difference of the two complex numbers. `[(-1-1j), (-2+1j), -1j]`. * `.aM`: Takes the absolute value of the result. This is the distance between the keypad locations. `[1.4142135623730951, 2.23606797749979, 1.0]` * `s`: Sum the distances. `4.650281539872885`. * `.R 2`: Round to 2 decimal places. `4.65`. * `+ "cm`: Add `'cm'` to the end and print. `4.65cm`. [Answer] ## PHP - 108 Bytes ``` <?for(;$v=strpos(-.987654321,fgetc(STDIN));$l=$v)$l&&$t+=hypot($l/3%4-$v/3%4,$l%3-$v%3);printf('%.2fcm',$t); ``` Input is taken from stdin. The `-.987654321` sent to the `strpos` function evaluates to `'-0.987654321'` in a string context. --- **Sample usage:** ``` $ echo 219.45.143.143 | php isp.php 27.38cm ``` [Answer] ## C, ~~192~~ ~~177~~ 159 bytes Updated version, now complete program using command line argument. At the same time, improved to still be shorter than previous version: ``` #define G c=*a[1]++,c=c>48?c-49:c/2-14,u=c%3,v=c/3 float r;c,u,v,p,q;main(int n,char**a){for(G;*a[1];)p=u,q=v,G,p-=u,q-=v,r+=sqrt(p*p+q*q);printf("%.2fcm",r);} ``` Ungolfed: ``` #include <stdio.h> #include <math.h> float r; int c, u, v, p, q; int main(int n, char** a) { c = *a[1]++; c = c > 48 ? c - 49 : c / 2 - 14; u = c % 3; v = c / 3; for ( ; *a[1]; ) { p = u; q = v; c = *a[1]++; c = c > 48 ? c - 49 : c / 2 - 14; u = c % 3; v = c / 3; p -= u; q -= v; r += sqrt(p * p + q * q); } printf("%.2fcm",r); return 0; } ``` The golfed version uses a preprocessor `#define` to shorten some of the repeated code in the full version. [Answer] # JavaScript (*ES6*), 132 I/O via popup. Run the snippet to test (Firefox only) ``` [for(a of prompt(d=''))[p,q,d]=[x=(a=a<'0'?9:-a?a-1:10)%3,y=a/3|0,d!==''?d+Math.sqrt((p-=x)*p+(q-=y)*q):0]],alert(d.toFixed(2)+'cm') ``` [Answer] # Python 3, 108 bytes ``` L=[x//3*1j+x%3for x in map("123456789.0".find,input())] print("%.2fcm"%sum(abs(a-b)for a,b in zip(L,L[1:]))) ``` Admittedly not very well golfed, but at least it ties with PHP. [Answer] # Ruby 135 ~~139~~ ``` s=0 gets.chars.each_cons(2).map{|a|i,j=a.map{|e|'123456789.0'.index e} i&&j&&s+=((i%3-j%3)**2+(i/3-j/3)**2)**0.5} print s.round(2),'cm' ``` Test it online: <http://ideone.com/2CIQa5> [Answer] # Python ~~199 171~~ 166 There's a shorter Python code (108) for this by SP3000: <https://codegolf.stackexchange.com/a/50854/41163> ``` import sys p=r=0 for i in sys.argv[1]: c=3,0 if i!=".":c=divmod(int(i)-1,3) if i<1:c=3,1 if p:r+=((p[1]-c[1])**2+(p[0]-c[0])**2)**0.5 p=c print"%.2fcm"%r ``` # Sample usage: ``` $ python isp.py 219.45.143.143 27.38cm ``` ### Run online: <http://codepad.org/h9CWCBNO> # Commented code ``` import sys # p - last position as (y,x) tuple - initialized with 0, because "if 0" -> equals to "False" p = 0 # r - result of adding all distances - ini with 0, because not moved any distances on start r = 0 # Loop over chars for char in sys.argv[1]: # c - current position of typist as (y,x) tuple # Always set c to position of "." key c = 3,0 # lazy for c=(3,0) # Check if char is not the "." key if char !=".": # Get position of char on keypad c=divmod(int(char)-1,3) if char<1: c=3,1 # If this is the first char, # then STORE_OPERATION has not been executed, # so p is still p=0 from original initialization # calling "if 0" evaluates to False, # so we jump this code block, for the first char if p: # calculate delta of x, y from current and last position, # then add both deltas squared (**2), # then get square root of it (**0.5 = **1/2) # add to r (+=) r+=( (p[1]-c[1])**2 + (p[0]-c[0])**2 )**0.5 # STORE_OPERATION - Store current position as last position p = c # .2f returns r with 2 trailing digits print"%.2fcm"%r ``` ]
[Question] [ Your goal is to check whether a completed [Minesweeper](http://en.wikipedia.org/wiki/Minesweeper_%28video_game%29) board is valid. This means that each number is a correct count of mines in cells adjacent to it, including diagonals. The board does not wrap around. [As usual](http://meta.codegolf.stackexchange.com/q/2447/20260), you should give a function or program, and shortest code in bytes wins. See also past challenges to [generate](https://codegolf.stackexchange.com/q/6474/20260), [solve](https://codegolf.stackexchange.com/q/24118/20260), and [fully implement](https://codegolf.stackexchange.com/q/10635/20260) Minesweeper. **Input:** A single string like this: `02X2 13X2 X211`. * The rows of the minesweeper board are given separated by spaces. So, the above represents the 3x4 board: `02X2` `13X2` `X211` * Each cell is a character: `X` for a mine, or a number `0` through `8`. * All rows have the same length. * There are at least 3 rows and 3 columns. * The input doesn't start or end with a space, but you may include a newline at the end if you wish. **Output:** A consistent [Truthy](http://meta.codegolf.stackexchange.com/q/2190/20260) on correct boards, and a consistent [Falsey](http://meta.codegolf.stackexchange.com/q/2190/20260) value on incorrect boards. *Consistent* means that all Truthy outputs are the same and all Falsey outputs are the same. **Test cases** Each line is a separate test case. `True`: ``` 02X2 13X2 X211 XXXX XXXX XXXX XXXX XX4X2 5X6X4 XX6XX 4XX54 2X4XX ``` `False`: ``` 02X2 13X2 X212 XXXX XXXX X7XX XXXX XX5X2 5X6X4 XX6XX 4XX54 2X5XX ``` [Answer] # Python 2, ~~132 129~~ 128 ``` def f(s):w=s.find(' ');E=dict(enumerate(s));return all(E[i]in' X'+`sum(E.get(i+d/3*~w+d%3+w,5)>'O'for d in range(9))`for i in E) ``` I used `enumerate` in a golf...and even used `range` elsewhere in the same program. Clearly something is wrong here. Edit: Iterate over `dict(enumerate(s))` rather than `enumerate(s)`, so `enumerate` does not need to be called twice. [Answer] # Pyth, 43 ``` Jhxzd!f-@zT+" X"`sm/:+*JNztd+d2\Xm+T*kJU3Uz ``` Try it [here](http://isaacg.scripts.mit.edu/pyth/index.py). **Explanation:** * `Jhxzd`: This is the location of the first space in the input + 1. (`z` in the input, `d` is space.) It is the separation in the input between vertically adjacent cells on the board. * `!f`: This is the logical not (`!`) of a filter (`f`), which will be `True` if and only if the expression is falsy for every element of the sequence. * `-@zT`: Take the character at location `T` (the lambda variable) from the input, and remove any appearances of: (This will be truthy if the character is not removed, and falsy if it is. * `+" X"`: Remove space, X, and * ```: Repr of * `sm`: sum of map to * `/ \X`: count of "X" in * `:+*JNz`: The slice of the input prefixed by `J` dummy characters * `td+d2`: From d-1 to d+2. * `m+T*kJU3`: For d in [T, T+J, T+2\*J]. * `Uz` For T in `range(len(input))`. [Answer] ## APL (NARS2000) (74) ``` {~0∊(G>9)∨G=(⍴G)↑{+/∊9<⍵∘⌷¨G∘.⊖(G←2-⍳3)∘.⌽⊂Z}¨⍳⍴Z←G↑⍨2+⍴G←¯1+⎕D⍳⊃⍵⊂⍨⍵≠' '} ``` Also works in Dyalog APL if `⎕ML` is set to `3`. Explanation: * `⊃⍵⊂⍨⍵≠' '`: split `⍵` on the spaces and use the lists to form a matrix. * `G←¯1+⎕D⍳`: find the index in `⎕D` for each value, subtract 1, and store this in `G`. (`⎕D` contains the digits, any non-digit will turn into `10`). * `Z←G↑⍨2+⍴G`: add two lines and columns of zeroes at the edge of the matrix, to deal with the wraparound * `{`...`}¨⍳⍴Z`: for each position in `Z`, find the amount of bombs in the Moore neighbourhood of that position: + `G∘.⊖(G←2-⍳3)∘.⌽⊂Z`: rotate `Z` left, right, up, down, left-up, right-up, left-down, and right-down. + `⍵∘⌷¨`: for each of these, find the element at `⍵` in each of these rotated matrices + `+/∊9<`: count how many elements are higher than 9 (this is the amount of bombs). * `(⍴G)↑`: remove the added lines of zeroes again, * `G=`: check whether each element in `G` is equal to the amount of bombs surrounding that position (this should be true for all non-bomb squares), * `(G>9)∨`: and check whether the elements in `G` are higher than `9` (these are the bombs). * `~0∊`: return `1` if the resulting matrix contains no zeroes (=all squares are either bombs or the correct number), and `0` if it does. [Answer] # C#, 321 320 305 ``` bool s(string B){var L=B.Split(' ').Select(s=>' '+s+' ').ToList();var b=new string(' ',L[0].Length);L.Insert(0,b);L.Add(b);Func<int,int,IEnumerable<int>>E=Enumerable.Range;return E(1,b.Length-2).All(x=>E(1,L.Count-2).All(y=>L[y][x]=='X'||L[y][x]-'0'==E(x-1,3).Sum(X=>E(y-1,3).Sum(Y=>L[Y][X]=='X'?1:0))));} ``` First attempt golfing anything, and I know that C# isn't the ideal language. I hope writing an instance method is allowed, otherwise add another 7 characters for `static`. Spaced out: ``` bool s(string B) { var L = B.Split(' ').Select(s => ' ' + s + ' ').ToList(); var b = new string(' ', L[0].Length); L.Insert(0, b); L.Add(b); Func<int, int, IEnumerable<int>> E = Enumerable.Range; return E(1, b.Length - 2).All(x => E(1, L.Count - 2).All(y => L[y][x] == 'X' || L[y][x] - '0' == E(x - 1, 3).Sum(X => E(y - 1, 3).Sum(Y => L[Y][X] == 'X' ? 1 : 0)))); } ``` Using Linq saves some space compared to for loops, but it's harder to debug. I learned a few things like converting `char => int` by subtracting `'0'`. It seemed simpler to pad out the board with spaces so iterating over it would be easier. [Answer] ## Python 2, 121 ``` def f(B):n=B.find(' ')+1;R=range(len(B));print all(B[I]in' X'+`sum(2>I%n-i%n>-2<I/n-i/n<2<B[i]>'W'for i in R)`for I in R) ``` This is heavily inspired by [feersum's answer](https://codegolf.stackexchange.com/a/42344/20260). The order of the day is overkill: rather than checking for mines in the 9 neighbors of the cell, check every single cell to see whether it's a neighboring mine. We check if two cells are neighbors with `2>r>-2<c<2`, where `r` and `c` are the row and column differences of cells, equivalent to `{r,c}<{-1,0,1}`. These coordinates are computed from the cell indices `I` and `i` as `c=I%n-i%n` and `r=I/n-i/n`. It's more efficient to index directly into the string and extract rows and columns than to convert it to a 2D object like a list of lists. The mine check is `B[i]>'W'`, equivalent here to `B[i]=='X'`. Using `enumerate` would have saved two characters over the ugly `range(len(B))` except that it returns an iterator object which does not support two nested loops through it. [Answer] # Python 2, 140 ``` s=input();w=s.index(' ')+1 print all(c in'X 'or(int(c)==sum(s[max(0,a-1):max(0,a+2)].count('X')for a in[i-w,i,i+w]))for i,c in enumerate(s)) ``` [Answer] # JavaScript (ES6), ~~135~~ ~~133~~ ~~125~~ 122 ``` f=s=>s.split(" ")[e="every"]((l,i,a)=>[...l][e]((c,j)=>!(-[-1,0,k=1][e]((y,m,q)=>q[e](x=>k+=(a[i+y]||0)[j+x]=="X"))-c+k))) ``` Provide input to the function as a string: ``` f("XX4X2 5X6X4 XX6XX 4XX54 2X4XX"); ``` For an explanation, see the old version, below. The new version replaces the `for` loops with `every` calls, and uses the variable `e="every"` to do `someArray[e](...)` instead of `someArray.every(...)`. Also, the counter `k` is now indexed at `1` so that the `k+=...` expression is always truthy, in order to keep the `every` loop running. We eliminate that extra `1` by subtracting the `true` result (which numerically coerces to `1`) returned by the `every` operation `[-1,0,k=1][e](...)`. --- Old version: ``` f=s=>s.split(" ").every((l,i,a)=>[...l].every((c,j)=>{q=[-1,k=0,1];for(y of q)for(x of q)k+=(a[i+y]||0)[j+x]=="X";return c=="X"||k==c})) ``` Code with spaces and comments: ``` f=s=>s.split(" ") // split on spaces .every((l,i,a)=> // for every line // l: line string, i: line number, a: whole array [...l].every((c,j)=>{ // for every character // c: character, j: index in string q=[-1,k=0,1]; // define counter k=0 and q=[-1,0,1] for(y of q) // use q to loop adjacent spaces for(x of q) k+= // add the following boolean to k: (a[i+y] // from line number i+y... ||0) // (or a dummy zero, to prevent lookups on undefined) [j+x] // ...get index j+x from the above value... =="X"; // ...and compare it to "X" return !(k-c) // after the loop, this character passed if // the char equals the number of counted X's (so k-c is 0) // or it is an X itself (so `k-c` is NaN) }) ) ``` The JavaScript `every` array method takes a callback and applies the callback to every element of the array. If any callback returns a falsey value, the `every` call returns `false`. Booleans in JS are coerced to 1 or 0 when part of an addition. For each surrounding space, we "add" the boolean result of comparing its value to `X` and then add that value to the counter `k` in the expression `k += (... == "X")`. Therefore, `k` contains a count of the number of surrounding `X`s, because `true` counts as `1` and `false` counts as `0`. [Answer] # CJam, ~~70 65~~ 63 bytes ``` 1l_S#):L)S*+:Q{Ii33/2%[0~1LL)L(L~)L~_))]W):Wf+Qf='X/,(scI==&}fI ``` This can be golfed a lot. Gives `1` for a valid board and `0` for an invalid board. **Test cases** ``` {-1:W; 1l_S#):L)S*+:Q{Ii33/2%[0~1LL)L(L~)L~_))]W):Wf+Qf='X/,(scI==&}fI }6*]N* ``` Input ``` 02X2 13X2 X211 XXXX XXXX XXXX XXXX XX4X2 5X6X4 XX6XX 4XX54 2X4XX 02X2 13X2 X212 XXXX XXXX X7XX XXXX XX5X2 5X6X4 XX6XX 4XX54 2X5XX ``` Output ``` 1 1 1 0 0 0 ``` [Try it online here](http://cjam.aditsu.net/) [Answer] # JavaScript (ES6) 98 Using *some* to apply a function to each character of the string. The function returns * false if blank * NaN if 'X' (repeatedly subtracting values from a non numeric char like 'X' gives NaN) * A numeric value of 0 if there are the right number of adiacent 'X', else non 0. The inner check is made using *map* just because it's shorter than *forEach* *some* returns true at the first truthy value (in this case, nonzero) meaning a failed check. The result is negated to give a more recognizable true/false. ``` F=v=>![...v].some( (x,p)=>x!=' '&&[1,-1,l=v.search(' '),-l,++l,-l,++l,-l].map(q=>x-=v[p+q]=='X')|x ) ``` **Test** In FireFox / FireBug console ``` ;["02X2 13X2 X212","XXXX XXXX X7XX XXXX","XX5X2 5X6X4 XX6XX 4XX54 2X5XX" ,"02X2 13X2 X211","XXXX XXXX XXXX XXXX","XX4X2 5X6X4 XX6XX 4XX54 2X4XX","111 1X1 111"] .forEach(t => console.log(t, F(t))) ``` *Output* ``` 02X2 13X2 X212 false XXXX XXXX X7XX XXXX false XX5X2 5X6X4 XX6XX 4XX54 2X5XX false 02X2 13X2 X211 true XXXX XXXX XXXX XXXX true XX4X2 5X6X4 XX6XX 4XX54 2X4XX true 111 1X1 111 true ``` [Answer] # R, 156 chars ``` a=b=do.call(rbind,strsplit(scan(,""),""));for(i in 1:nrow(a))for(j in 1:ncol(a))b[i,j]=sum(a[abs(i-row(a))<2&abs(j-col(a))<2]=="X");v=a!="X";all(b[v]==a[v]) ``` With indents, spaces and line breaks, for legibility: ``` a = b = do.call(rbind,strsplit(scan(,""),"")) #Reads stdin and turn into a matrix for(i in 1:nrow(a)) #Ugly, ugly loop for(j in 1:ncol(a)) b[i,j] = sum(a[abs(i-row(a))<2 & abs(j-col(a))<2]=="X") v = a!="X" all(b[v]==a[v]) ``` Examples: ``` > a=b=do.call(rbind,strsplit(scan(,""),""));for(i in 1:nrow(a))for(j in 1:ncol(a))b[i,j]=sum(a[abs(i-row(a))<2&abs(j-col(a))<2]=="X");v=a!="X";all(b[v]==a[v]) 1: XX4X2 5X6X4 XX6XX 4XX54 2X4XX 6: Read 5 items [1] TRUE > a=b=do.call(rbind,strsplit(scan(,""),""));for(i in 1:nrow(a))for(j in 1:ncol(a))b[i,j]=sum(a[abs(i-row(a))<2&abs(j-col(a))<2]=="X");v=a!="X";all(b[v]==a[v]) 1: XXXX XXXX XXXX XXXX 5: Read 4 items [1] TRUE > a=b=do.call(rbind,strsplit(scan(,""),""));for(i in 1:nrow(a))for(j in 1:ncol(a))b[i,j]=sum(a[abs(i-row(a))<2&abs(j-col(a))<2]=="X");v=a!="X";all(b[v]==a[v]) 1: XX5X2 5X6X4 XX6XX 4XX54 2X5XX 6: Read 5 items [1] FALSE ``` [Answer] # [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 27 bytes ``` ėf:⸠'X=Ḟ£?ṂÞȯ1⁾ƛ'XC}¥'XẠᵛᶲ₌ ``` [Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCLEl2Y64rigJ1g94biewqM/4bmCw57IrzHigb7GmydYQ33CpSdY4bqg4bWb4bay4oKMIiwiIiwiWFg0WDIgNVg2WDQgWFg2WFggNFhYNTQgMlg0WFgiLCIzLjQuMSJd) ``` ėf:⸠'X=Ḟ£?ṂÞȯ1⁾ƛ'XC}¥'XẠᵛᶲ₌­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏⁠‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁣⁡‏⁠‎⁡⁠⁢⁣⁢‏⁠‎⁡⁠⁢⁣⁣‏‏​⁡⁠⁡‌⁢⁣​‎‏​⁢⁠⁡‌­ ėf: # ‎⁡remove whitespace and flatten, push two copies to the stack ⸠'X=Ḟ # ‎⁢get the indices of the mines and push to register ?ṂÞȯ1⁾ # ‎⁣Split the input on spaces, get the neighbors of each cell and flatten one layer ƛ'XC} # ‎⁤Count the number of mines surrounding each cell ¥'XẠ # ‎⁢⁡push the register, and re-apply the mines at the original indices ᵛᶲ₌ # ‎⁢⁢convert the numbers to strings and check if the two lists are equal # ‎⁢⁣the other list is the one we pushed two copies of at the start 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). ]
[Question] [ [John Horton Conway](https://en.wikipedia.org/wiki/John_Horton_Conway) was a brilliant mathematician. Among his contributions were three Turing-complete esolangs: [Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life) ([esolangs wiki](https://esolangs.org/wiki/Game_of_Life)), [FRACTRAN](https://en.wikipedia.org/wiki/FRACTRAN) ([esolangs wiki](https://esolangs.org/wiki/Fractran)), and [Collatz function](https://en.wikipedia.org/wiki/Collatz_conjecture#Undecidable_generalizations) ([esolangs wiki](https://esolangs.org/wiki/Collatz_function)). Because [we did an extremely amazing job around GoL](https://codegolf.stackexchange.com/questions/11880/build-a-working-game-of-tetris-in-conways-game-of-life), it is time for the challenge with the other two. ## 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. A Collatz sequence is defined as the following: given a positive integer \$n\$, $$ \begin{align} a\_0 &= n \\ a\_{i+1} &= \begin{cases} a\_i/2, & \text{if $a\_i$ is even} \\ 3a\_i+1, & \text{if $a\_i$ is odd} \end{cases} \end{align} $$ It is conjectured that, for every positive integer \$n\$, the sequence eventually reaches 1. ## Task Write a FRACTRAN program that takes \$p^n\$ as input (for a prime \$p\$ of your choice) and halts if and only if the Collatz sequence starting at \$n\$ reaches 1. You may see [Avi F. S.'s COLLATZGAME](https://codegolf.stackexchange.com/a/201483/78410) as an example. Also, [TIO](https://tio.run/##SytKTC4pSsz7DwT/8gtKMvPziv/rZgAA) has [an implementation of FRACTRAN](https://github.com/DennisMitchell/ffi), so you can test your program with it. (Enter the starting number in the Arguments section; it accepts base-exponent form e.g. `2^27` as well as plain integer form.) The shortest program in terms of **the number of fractions** wins. [Answer] # ~~9~~ ~~8~~ 7 fractions $$\frac{5}{4}, \frac{63}{22}, \frac{14}{55}, \frac{66}{35}, \frac{1}{7}, \frac{2}{3}, \frac{44}{5}$$ Takes input as \$3^n\$. [Try it online!](https://tio.run/##DcjLCcAgEAXAVrYBWdyf3QQkJOBFxVh/XjLHuVc996odcDYKZRHKxu4UweqUuZCwkv0HQA8p75i7jf4gTUW69AM "FRACTRAN – Try It Online") ### How it works The first transition is $$3^n \xrightarrow{\frac{2}{3}} 2 \cdot 3^{n - 1},$$ which we will consider the “real” representation of the number \$n\$, because some intermediate control flows will bypass the above transition. If \$n = 1\$, the program now halts immediately. If \$n = 2k\$ is even, we have $$\begin{multline\*} 2 \cdot 3^{2k - 1} \xrightarrow{\frac{2}{3}} 2^2 \cdot 3^{2k - 2} \xrightarrow{\frac{5}{4}} 3^{2k - 2} \cdot 5 \xrightarrow{\left(\frac{2}{3} \cdot \frac{2}{3} \cdot \frac{5}{4}\right)^{k - 1}} 5^k \xrightarrow{\frac{44}{5}} 2^2 \cdot 5^{k - 1} \cdot 11 \\ \xrightarrow{\frac{5}{4}} 5^k \cdot 11 \xrightarrow{\frac{14}{55}} 2 \cdot 5^{k - 1} \cdot 7 \xrightarrow{\left(\frac{66}{35} \cdot \frac{5}{4} \cdot \frac{14}{55}\right)^{k - 1}} 2 \cdot 3^{k - 1} \cdot 7 \xrightarrow{\frac{1}{7}} 2 \cdot 3^{k - 1}, \end{multline\*}$$ which represents \$\frac{n}{2}\$. If \$n = 2k + 1\$ is odd, we instead have $$\begin{multline\*} 2 \cdot 3^{2k} \xrightarrow{\left(\frac{2}{3} \cdot \frac{5}{4} \cdot \frac{2}{3}\right)^k} 2 \cdot 5^k \xrightarrow{\frac{44}{5}} 2^3 \cdot 5^{k - 1} \cdot 11 \xrightarrow{\frac{5}{4}} 2 \cdot 5^k \cdot 11 \\ \xrightarrow{\frac{63}{22}} 3^2 \cdot 5^k \cdot 7 \xrightarrow{\left(\frac{66}{35} \cdot \frac{63}{22}\right)^k} 3^{3k + 2} \cdot 7 \xrightarrow{\frac{1}{7}} 3^{3k + 2} \xrightarrow{\frac{2}{3}} 2 \cdot 3^{3k + 1}, \end{multline\*}$$ which represents \$3k + 2 = \frac{3n + 1}{2}\$, which is two steps ahead of \$n\$. [Answer] # 9 fractions ``` 13/11 22/39 1/13 7/5 320/21 1024/7 3/4 5/6 22/3 ``` [Try it online!](https://tio.run/##HcpRCoAgEAXAq@wF5LlvNekyQURBPyrm@dug@Z5r7Mcce3VXg6qQsFUUalKQxRhBFY1MKGJIkrH8yd25sbytz7vVx0Onh5Mf "FRACTRAN – Try It Online") Input is a power of 2. It's probably easier to think about FRACTRAN code in terms of the powers of the primes in each fraction. I list these below for the code, with positive exponents coming from numerators and negative values from denominators, omitting 0's to reduce clutter. Thinking of programs as lists of vectors and the current value as a vector, FRACTRAN repeatedly modifies the value by adding the first-listed row such this results in no negatives entries. ``` 2 3 5 7 11 13 ---------------- -1 +1 +1 -1 +1 -1 -1 -1 +1 +6 -1 +1 -1 +10 -1 -2 +1 -1 -1 +1 +1 -1 +1 ``` I suspect this solution is similar to [Anders Kaseorg's](https://codegolf.stackexchange.com/a/203682/20260) earlier 9-byte solution, who has already explained how his now-more-golfed answer works in detail. So, I'll instead explain a useful conceptual idea in my code. **Switcher gadget** I'll talk about a control flow gadget that I'll call a *switcher* that my code heavily relies on. You can see two copies of it, one in columns 3 and 4, and another in columns 5 and 6. It looks like this: ``` -1 +1 B +1 -1 b -1 A a +1 ``` Here, `A`, `a`, `B`, and `a` are some FRACTRAN operations, taking up multiple columns. A switcher alternates between two things: * Repeat `A` as long as it's legal, then do `a` once. * Repeat `B` as long as it's legal, then do `b` once. The first row `-1 +1` doesn't do any code operation is just used for control flow. Here's how a switcher it might look like operating. The first column shows the operation performed, and the other two columns showing the value of those variables used for control flow, which are always 0 or 1. ``` A 0 0 A 0 0 A 0 0 a 1 0 0 1 B 1 0 0 1 B 1 0 0 1 B 1 0 0 1 b 0 0 A 0 0 A 0 0 ... ``` **What is it good for?** So, why do we want a switcher? Well, without a gadget like this, it's hard to keep FRACTRAN focused on a task. Say we want to alternate between doing `A` repeatedly and doing `B` repeatedly. FRACTRAN prioritizes the one that's listed first, so if we list `A` then `B`, then when doing `B`, FRACTRAN will keep jumping back to `A` when it can. Of course, the other order means we just have the same problem with it jumping back to `B`. For example, consider this simple program made of two operations: ``` A = [-2, +1] B = [+1, -1] ``` Starting with `[2*n, 0]`, these operations almost work to product `[n, 0]` but not quite. First, `A` is applies as long as possible, adding `[-2, +1]` until we arrive at`[0, n]`. For example, with `n=3`, this goes: ``` [6, 0] add A: [4, 1] add A: [2, 2] add A: [0, 3] ``` Now we have `[0, n]` and want to get `[n, 0]`. To move `n` back to the first entry, we want to to keep adding `B = [+1, -1]`. Since we can't do `A` at first, the code indeed switches to `B`, but then things go wrong: ``` [0, 3] add B: [1, 2] add B: [2, 1] add A: [0, 2] ``` Because doing `B` twice made `A` applicable again, it never finishes applying `B` and so doesn't get to `[n, 0]`. A switcher lets us fix exactly this by keeping the program on task with `B`, making it alternates between `A`-mode and `B`-mode until each respective task is complete and can be done no further. It also let us run additional one-time operations `a` and `b` when switching modes. **The Collatz code** This operation of halving is exactly what the Collatz code does on even values. If we ignore the third and fourth columns (which are for odd values) and their rows, we get: ``` code switcher -1 +1 (B) +1 -1 +1 -1 (b) -1 (A) -2 +1 (a) +1 -1 +1 ``` This is exactly a switcher (in columns 3 and 4) applies to the operations in the first two columns. These are the halving operations `A = [-2, +1], B = [+1, -1]` described before. A detail is that we also have `b = A` to make the transition from `B` work out by doing `A` an additional time in advance. Similarly, columns 3 and 4 are a switcher for the operation used for odd values. To take `[n,0] -> [3*n+1,0]` for odd `n`, we use: ``` A = [-2, +1] a = [-1, -1] B = [+6, -1] b = [+10, 0] ``` Note that making `B` be `[+6, -1]` rather than `[+1, -1]` as for the even case means that we end up with a result about 6 times as big, so `3*n` rather than `n/2`. The `a` and `b` work out to give the `+1` in `3*n+1` while serving other useful purposes. Specifically, they make the code go into the odd switcher rather than the even switcher when the first entry is odd, as well as make the program terminate when the Collatz sequence reaches 1. The odd code might be a bit simpler producing `(3*n+1)/2`, that is pre-doing an addition halving step, which is always what follows because `3*n+1` is even for odd `n`. But, I think that this would just make the numerical entries in the rows smaller rather than cutting a row (fraction), which is what counts for scoring. ]
[Question] [ You have a stack of [pancakes](http://en.wikipedia.org/wiki/Pancake) on a plate with a glob of syrup on top so thick it can't run down the sides. You won't be happy to eat until both faces of each pancake have at least touched the syrup, but right now only one face of the top pancake has. You know that the syrup will never soak through even one pancake, but it can be transferred indefinitely via face-to-face contact between two pancakes. Once a face of a pancake has touched syrup it is considered coated in syrup forever, and will make any non-syrup coated face that touches it syrup coated as well. It is possible to transfer syrup to and from the top side of the plate as well. You proceed to coat every pancake face with syrup by inserting a spatula below one or more pancakes and flipping them all over, exactly as is done in [pancake sorting](https://codegolf.stackexchange.com/q/12028/4372). (Unfortunately this spatula is syrup-resistant, and does not help to distribute the syrup by touching pancake faces.) Sadly you lose track of which pancake faces have touched syrup but you do remember the flips you have made. *Given your past flips can you determine if your pancakes are all coated with syrup yet?* # Challenge Write a program that takes in a positive integer N for the number of pancakes, and a list of positive integers (all <= N) for the flips you have made so far. Each number in the list represents the number of pancakes that were flipped. Output a truthy value if the pancakes are done being coated and a falsy value if not. ([truthy/falsy definition](http://meta.codegolf.stackexchange.com/a/2194/26997)) The input should come from stdin or the command line and the output should go to stdout (or closest alternatives). It's fine if your input needs a little extra formatting: e.g. `[1, 1, 2, 2]` instead of `1 1 2 2` for the list. # Examples Assume N = 2, so we have a stack of two pancakes on a plate, starting with the syrup on top. If the list is `1 1 2 2`, this means we... * flip the top pancake - coating the upper face of the bottom pancake * flip the top again - coating the original bottom face of the top pancake * flip both - coating the plate * flip both again - coating the original bottom face of the bottom pancake Since all four faces are coated the output would be something like `True` or `1`. If the list is `1 2 2 1`, this means we... * flip the top pancake - coating the upper face of the bottom pancake * flip both - coating nothing * flip both again - coating nothing * flip the top again - coating the original bottom face of the top pancake Since the face touching the plate is still syrup-free the output would be something like `False` or `0`. # Notes * The flip list may be arbitrarily large and can be empty, in which case the output is falsy. * The plate acts as a syrup-carrier but it doesn't matter if it gets coated or not. (In fact any flip solution *will* coat the plate because the pancake face it touches must be coated, but regardless.) * The plate cannot be flipped. * You can assume these pancakes are [unit disks](http://en.wikipedia.org/wiki/Unit_disk) with no sides to speak of, only two opposite faces. # Scoring This is code-golf. The shortest solution [in bytes](https://mothereff.in/byte-counter) wins. [Answer] # Haskell, ~~92~~ ~~90~~ ~~86~~ ~~84~~ ~~114~~ ~~110~~ ~~99~~ 98 the requirement of a full program is so annoying. I wonder why would anyone require this. ``` m(n:s)=all(<1)$foldl(\r@(p:s)n->reverse(take n s)++(p*r!!n):drop n s)[0..n]s main=readLn>>=print.m ``` this solution works by representing the pile of pancakes by a list of the sides, when adjacent pancakes share the same side. every side is a number, and a side is coated if it has a zero value. run as: ``` *Main> main [2,1,1,2,2] True ``` [Answer] ## Python, 92 bytes I think this works: ``` s=[1]+[0,0]*input() for f in input():x=f*2;s[0]=s[x]=s[0]|s[x];s[:x]=s[x-1::-1] print all(s) ``` It uses a list of pancake faces (plate included) to remember which are coated with syrup. Pancakes are flipped by reversing part of the list, but any syrup is first transferred between the top face and the newly revealed face. Usage: ``` $ python pancakes.py 2 1, 1, 2, 2 True ``` [Answer] # CJam, ~~32~~ ~~30~~ 29 bytes ``` q~2@#2b\{)/(W%)1$0=|@]s:~}/:& ``` [Try it online.](http://cjam.aditsu.net/) ### Test cases ``` $ cjam pancakes.cjam <<< '2 [1 1 2 2]'; echo 1 $ cjam pancakes.cjam <<< '2 [1 2 2 1]'; echo 0 ``` ### How it works ``` q~ " N, L := eval(input()) "; 2@#2b " P := base(2 ** N, 2) "; \{ }/ " for F in L: "; )/ " P := split(P, F + 1) "; (W%) " T, U, V := P[1:], reverse(P[0])[:-1], reverse(P[-1])[0] "; 1$0=| " V |= U[0] "; @]s:~ " P := map(eval, str([U, V, T])) "; :& " print and(P) "; ``` [Answer] ## Python 2: 75 A simplification of grc's and feersum's solution. ``` n,b=input() s=[1]+[0]*n for x in b:s[:x+1]=s[x::-1];s[x]|=s[0] print all(s) ``` Storing the syrup state of `2*n+1` pancake edges is redundant because touching edges are always the same. This instead remembers the state of each of `n+1` pancake junctions. That way, syrup transfer is automatically accounted for. The only update needed is to preserve the syrup at the `x` junction when a flip cuts it. This is done by or-ing the post-flip syrup at `0` into `x`. Taking input twice doesn't affect the character count. ``` s=[1]+[0]*input() for x in input():s[:x+1]=s[x::-1];s[x]|=s[0] print all(s) ``` [Answer] # Python 2, 93 bytes At first I was going to post my answer, but then grc had already posted a very similar one a minute before. So I tried to come up with some improvements. The only one I could find is to use a lexicographic list comparison instead of `all()`. Edit: Fixed a mistake introduced by unsuccessfully trying different input methods which doesn't change character count. ``` n,F=input() L=[1]+2*n*[0] for f in F:f*=2;L[0]=L[f]=L[0]|L[f];L[:f]=L[~-f::-1] print[1]*2*n<L ``` Sample input/output: ``` 2, [1, 1, 2] ```   ``` False ``` [Answer] ## APL, [77](https://mothereff.in/byte-counter#%E2%88%A7%2F%E2%8A%83%7Bx%5B1%5D%2B%E2%86%90%E2%8D%BA%E2%8C%B7x%E2%86%90%E2%8D%B5%E2%8B%84%28%E2%8C%BD%E2%8D%BA%E2%86%91x%29%2C%E2%8D%BA%E2%86%93x%7D%2F%28%E2%8C%BD1%2B%E2%8E%95%29%2C%E2%8A%821%2C%E2%8E%95%E2%8D%B40) ``` ∧/⊃{x[1]+←⍺⌷x←⍵⋄(⌽⍺↑x),⍺↓x}/(⌽1+⎕),⊂1,⎕⍴0 ``` [Answer] ## Python 2, 107 ``` d=[1]+[0,0]*input() for i in input():n=2*i;d[:n]=reversed(d[:n]);d[n]=d[n-1]=d[n]|d[n-1] print(all(d[:-1])) ``` [Answer] # Haskell, ~~129~~ 125 ``` t(m:l)=all(any(<1).(\i->foldr(\n->foldr($)[].map(n%))[i]l))[0..m] n%i|i>n=(i:)|i<n=(n-i:)|1>0=(n:).(0:) main=readLn>>=print.t ``` Probably not completely golfed yet, but it works without manipulating a list of coated sides. Instead, it works its way backwards to figure out whether a given side of a given pancake has ever come in contact with anything that was the top side at the beginning. `foldr` effectively traverses the list of flips backwards, therefore there is no `reverse`. So here is the algorithm: We map over all relevant sides (`[0..m]`) and make a list of sides that our side inherits syrup from at each step, starting from the back: initially the list is just `[i]`, but with a flip of `n` pancakes, each entry becomes `[n-i]` if `i<n`, `[n,0]` if `i==n`, and `[i]` if `i>n`. The side in question has been coated if and only if the resulting list after all flips contains a `0` (`any (<1)`). `all` does the rest, and `main` converts all this into a runnable program. The program takes its input from `stdin` in the form of `[n_pancakes, flip1, flip2, flip3, ...]`, terminated by a newline. ]
[Question] [ # Background The computer game NetHack dates from 1987, before the use of graphics in computer games was widely established. There are lots of monsters in the game, and potentially a lot need to fit on screen at once, so monsters are drawn in a very minimal way: a monster is simply drawn as an ASCII character on screen. In addition to there being lots of monsters, there are lots of *types* of monster. It can be important to know which is which; you'd have to react differently upon seeing a kitten and seeing a dragon. As such, most of ASCII is used to represent monsters; for example, a kitten is `f`, and a red dragon is `D`. This means that it can be very helpful to know what a given monster will look like, as it will help you to recognise it if you encounter it later on in the game. (Note that there are more types of monsters than there are ASCII characters, so some of them share; a red dragon and a blue dragon are both `D`.) # Task Your program must take the name of a NetHack monster as input, and produce the ASCII character that represents it within the game as output. The program is allowed to assume that the input is in fact the name of a NetHack monster; it may if it wishes crash, produce meaningless results, etc. if the input is invalid. The following Stack Snippet is a JSON object giving the full mapping of possible inputs to their corresponding outputs: ``` { "Aleax": "A", "Angel": "A", "Arch Priest": "@", "Archon": "A", "Ashikaga Takauji": "@", "Asmodeus": "&", "Baalzebub": "&", "Chromatic Dragon": "D", "Croesus": "@", "Cyclops": "H", "Dark One": "@", "Death": "&", "Demogorgon": "&", "Dispater": "&", "Elvenking": "@", "Famine": "&", "Geryon": "&", "Grand Master": "@", "Green-elf": "@", "Grey-elf": "@", "Hippocrates": "@", "Ixoth": "D", "Juiblex": "&", "Keystone Kop": "K", "King Arthur": "@", "Kop Kaptain": "K", "Kop Lieutenant": "K", "Kop Sergeant": "K", "Lord Carnarvon": "@", "Lord Sato": "@", "Lord Surtur": "H", "Master Assassin": "@", "Master Kaen": "@", "Master of Thieves": "@", "Medusa": "@", "Minion of Huhetotl": "&", "Mordor orc": "o", "Nalzok": "&", "Nazgul": "W", "Neferet the Green": "@", "Norn": "@", "Olog-hai": "T", "Oracle": "@", "Orcus": "&", "Orion": "@", "Pelias": "@", "Pestilence": "&", "Scorpius": "s", "Shaman Karnov": "@", "Thoth Amon": "@", "Twoflower": "@", "Uruk-hai": "o", "Vlad the Impaler": "V", "Wizard of Yendor": "@", "Woodland-elf": "@", "Yeenoghu": "&", "abbot": "@", "acid blob": "b", "acolyte": "@", "air elemental": "E", "aligned priest": "@", "ape": "Y", "apprentice": "@", "arch-lich": "L", "archeologist": "@", "attendant": "@", "baby black dragon": "D", "baby blue dragon": "D", "baby crocodile": ":", "baby gray dragon": "D", "baby green dragon": "D", "baby long worm": "w", "baby orange dragon": "D", "baby purple worm": "w", "baby red dragon": "D", "baby silver dragon": "D", "baby white dragon": "D", "baby yellow dragon": "D", "balrog": "&", "baluchitherium": "q", "barbarian": "@", "barbed devil": "&", "barrow wight": "W", "bat": "B", "black dragon": "D", "black light": "y", "black naga hatchling": "N", "black naga": "N", "black pudding": "P", "black unicorn": "u", "blue dragon": "D", "blue jelly": "j", "bone devil": "&", "brown mold": "F", "brown pudding": "P", "bugbear": "h", "captain": "@", "carnivorous ape": "Y", "cave spider": "s", "caveman": "@", "cavewoman": "@", "centipede": "s", "chameleon": ":", "chickatrice": "c", "chieftain": "@", "clay golem": "'", "cobra": "S", "cockatrice": "c", "couatl": "A", "coyote": "d", "crocodile": ":", "demilich": "L", "dingo": "d", "disenchanter": "R", "djinni": "&", "dog": "d", "doppelganger": "@", "dust vortex": "v", "dwarf king": "h", "dwarf lord": "h", "dwarf mummy": "M", "dwarf zombie": "Z", "dwarf": "h", "earth elemental": "E", "electric eel": ";", "elf mummy": "M", "elf zombie": "Z", "elf": "@", "elf-lord": "@", "energy vortex": "v", "erinys": "&", "ettin mummy": "M", "ettin zombie": "Z", "ettin": "H", "fire ant": "a", "fire elemental": "E", "fire giant": "H", "fire vortex": "v", "flaming sphere": "e", "flesh golem": "'", "floating eye": "e", "fog cloud": "v", "forest centaur": "C", "fox": "d", "freezing sphere": "e", "frost giant": "H", "gargoyle": "g", "garter snake": "S", "gas spore": "e", "gecko": ":", "gelatinous cube": "b", "ghost": " ", "ghoul": "Z", "giant ant": "a", "giant bat": "B", "giant beetle": "a", "giant eel": ";", "giant mimic": "m", "giant mummy": "M", "giant rat": "r", "giant spider": "s", "giant zombie": "Z", "giant": "H", "glass golem": "'", "glass piercer": "p", "gnome king": "G", "gnome lord": "G", "gnome mummy": "M", "gnome zombie": "Z", "gnome": "G", "gnomish wizard": "G", "goblin": "o", "gold golem": "'", "golden naga hatchling": "N", "golden naga": "N", "gray dragon": "D", "gray ooze": "P", "gray unicorn": "u", "green dragon": "D", "green mold": "F", "green slime": "P", "gremlin": "g", "grid bug": "x", "guard": "@", "guardian naga hatchling": "N", "guardian naga": "N", "guide": "@", "healer": "@", "hell hound pup": "d", "hell hound": "d", "hezrou": "&", "high priest": "@", "hill giant": "H", "hill orc": "o", "hobbit": "h", "hobgoblin": "o", "homunculus": "i", "horned devil": "&", "horse": "u", "housecat": "f", "human mummy": "M", "human zombie": "Z", "human": "@", "hunter": "@", "ice devil": "&", "ice troll": "T", "ice vortex": "v", "iguana": ":", "imp": "i", "incubus": "&", "iron golem": "'", "iron piercer": "p", "jabberwock": "J", "jackal": "d", "jaguar": "f", "jellyfish": ";", "ki-rin": "A", "killer bee": "a", "kitten": "f", "knight": "@", "kobold lord": "k", "kobold mummy": "M", "kobold shaman": "k", "kobold zombie": "Z", "kobold": "k", "kraken": ";", "large cat": "f", "large dog": "d", "large kobold": "k", "large mimic": "m", "leather golem": "'", "lemure": "i", "leocrotta": "q", "leprechaun": "l", "lich": "L", "lichen": "F", "lieutenant": "@", "little dog": "d", "lizard": ":", "long worm": "w", "lurker above": "t", "lynx": "f", "mail daemon": "&", "manes": "i", "marilith": "&", "master lich": "L", "master mind flayer": "h", "mastodon": "q", "mind flayer": "h", "minotaur": "H", "monk": "@", "monkey": "Y", "mountain centaur": "C", "mountain nymph": "n", "mumak": "q", "nalfeshnee": "&", "neanderthal": "@", "newt": ":", "ninja": "@", "nurse": "@", "ochre jelly": "j", "ogre king": "O", "ogre lord": "O", "ogre": "O", "orange dragon": "D", "orc mummy": "M", "orc shaman": "o", "orc zombie": "Z", "orc": "o", "orc-captain": "o", "owlbear": "Y", "page": "@", "panther": "f", "paper golem": "'", "piranha": ";", "pit fiend": "&", "pit viper": "S", "plains centaur": "C", "pony": "u", "priest": "@", "priestess": "@", "prisoner": "@", "purple worm": "w", "pyrolisk": "c", "python": "S", "quantum mechanic": "Q", "quasit": "i", "queen bee": "a", "quivering blob": "b", "rabid rat": "r", "ranger": "@", "raven": "B", "red dragon": "D", "red mold": "F", "red naga hatchling": "N", "red naga": "N", "rock mole": "r", "rock piercer": "p", "rock troll": "T", "rogue": "@", "rope golem": "'", "roshi": "@", "rothe": "q", "rust monster": "R", "salamander": ":", "samurai": "@", "sandestin": "&", "sasquatch": "Y", "scorpion": "s", "sergeant": "@", "sewer rat": "r", "shade": " ", "shark": ";", "shocking sphere": "e", "shopkeeper": "@", "shrieker": "F", "silver dragon": "D", "skeleton": "Z", "small mimic": "m", "snake": "S", "soldier ant": "a", "soldier": "@", "spotted jelly": "j", "stalker": "E", "steam vortex": "v", "stone giant": "H", "stone golem": "'", "storm giant": "H", "straw golem": "'", "student": "@", "succubus": "&", "tengu": "i", "thug": "@", "tiger": "f", "titan": "H", "titanothere": "q", "tourist": "@", "trapper": "t", "troll": "T", "umber hulk": "U", "valkyrie": "@", "vampire bat": "B", "vampire lord": "V", "vampire": "V", "violet fungus": "F", "vrock": "&", "warg": "d", "warhorse": "u", "warrior": "@", "watch captain": "@", "watchman": "@", "water demon": "&", "water elemental": "E", "water moccasin": "S", "water nymph": "n", "water troll": "T", "werejackal": "d", "wererat": "r", "werewolf": "d", "white dragon": "D", "white unicorn": "u", "winged gargoyle": "g", "winter wolf cub": "d", "winter wolf": "d", "wizard": "@", "wolf": "d", "wood golem": "'", "wood nymph": "n", "woodchuck": "r", "wraith": "W", "wumpus": "q", "xan": "x", "xorn": "X", "yellow dragon": "D", "yellow light": "y", "yellow mold": "F", "yeti": "Y", "zruty": "z" } ``` So basically, the task here is "given a key in the dictionary represented by the JSON object above, return the corresponding value". Note that this challenge is, in a way, a reverse [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'"); instead of going from a small/empty input to a large output, you're going from a large input to a small output. (There's thus lots of redundant information in the input, which you can ignore or make use of as you wish). It's also fairly similar to regex golf, except that a) any language is allowed (not just regex), and b) there are more than two possible outputs. (We've had a few tasks like this before, such as [these](https://codegolf.stackexchange.com/q/90106/62131) [two](https://codegolf.stackexchange.com/q/18048/62131), but this task is somewhat different because the specified input/output behaviour has stronger patterns). # Clarifications You can use any reasonable input and output format (e.g. you can produce the output as a character, or as its ASCII code, or as a string that's one character long). You can submit a function instead of a full program, if you prefer. This is already mentioned in the standard loopholes, but just to reiterate: you *cannot* store the correspondence between input and output anywhere other than your program's source code. This challenge is basically about representing the input/output behaviour in the smallest space possible, so you must not do things like downloading a list from the Internet, store the correspondence in an external file, start NetHack in debug mode and spawn the monster in question to see what it looks like, etc.. (Besides, I don't want to have to fight off monsters to test your submissions.) # Victory condition This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the winning entry will be the entry that is shortest, counted in bytes. Good luck! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 309 bytes in Jelly's encoding ``` “Æ÷“¥s“ɲ“¡µ’;“ịƊ⁴çNṂ‘_\ OḌ;¢*5$%¥/µ“+⁷ż!¤ña¡jIȧƁfvḶg/Ọ=^ƝĠ0Ẇƭ³½N~=.Ɗ°ɗẇ⁵\ɦ*ɠPf⁾?ṾHḣ 2=⁹ƒ!©ƊĠṣƥ®Ƙ0Yƙ>!ȧtƊN0w,$ɠẎ46fẋ⁷(ṣẆm⁾ŻƓṫµsçwṣḂḲd0Ruṛ’ḃ21+\iµØW“&;:' ”;“¡3ȧ%⁾xƑ?{Ñṃ;Ċ70|#%ṭdṃḃ÷ƑĠẏþḢ÷ݳȦṖcẇọqƁe ʠ°oḲVḲ²ụċmvP[ỴẊẋ€kṢ ȯḂ;jɓỴẏeṾ⁴ḳḢ7Ẓ9ġƤṙb€xÇ4ɗ⁻>Ẉm!Ƈ)%Ḃẇ$ġ£7ȧ`ỵẈƘɗ¡Ṃ&|ƙƥ³ẏrṛbḋƙċ⁻ṁƲRṀẹṾ<ñ⁻Ṅ7j^ɓĊ’b58¤ị;0ị@ ḲÇ€t0”@;Ṫ ``` [Try it online!](https://tio.run/nexus/jelly#HVJbbxJREH7vr4AIVVtj19qKutL2UV@w6YPGSKrFQiOGVEtviY1hqSlmqTaURCC2CdduvFQpFNmzqzycs53s@i9m/wgOPJw5c2bOzHzfd07fTR2JPdGljTeSZJ3WwK3wjpsqyeSimQXVVc6FFkKWdlPFZ@GRh6jvy7w6Nu3z88bE4OrRuKt0L/54eV2cLfFK/IGtgRLbRP33ygSa@8FFOLbKEhp7cMrb/G/oXfA6qLzpFNDIuEon7JyMOeX5mKv0ZpH17qNe80wGXYXBoZd/BdUqI6tBg/@EovQESjNeW1sHNSRtXfM5ZTQ@Td2KoZElCFfoHk1JUKMLE/LIvvNOUmhbg7CeRr21LC1sIPtC5FDfnbwxHn7JO6L4mBiMyncve9zUsTzkf9PW/NRkG3Kzb0UO2a5sqQFp55If2ekyHaladCFHwIwD0UO9KrpWk7ftE2SfXxApND@@ASXq@VfmzVWa@4gWb6HZsLKJzfmnaJ6joQ4wp3@8Qlb12L8Inxx38sPMQZRUINFRb1PrABqHd6wK1JGVIlSwLTJTTsFVzBk0PiS8kLnqH5AzMj6rwmsBW3uOZodSUHQKvEKvNroDJVKvTY3XiHwE9SyULNLLRKZAawFZCg1GI@@Js2HwfSC@6OQtlWSKTN/mdfoEskRmboRoiAxhWJdIqjkZ2bd@v7@ylPQkX6@uRf8D "Jelly – TIO Nexus") I decided it was about time I had a go at my own challenge. The use of Jelly (and its 8-bit codepage) gives me a 12.5% advantage over the ASCII-only languages, and Jelly is convenient for this challenge due to having built-in base conversion operators with short names, but most of the savings are due to a better compression algorithm (this program averages less than one byte per type of monster). ## Algorithm and explanation ### Word-based classification I decided that in order to get a good score, it was necessary to take more advantage of the structure of the input than other entries were. One thing that's very noticeable is that many monsters have names of the form "*adjective* *species*"; a `red dragon` and a `blue dragon` are both types of dragon, and thus appear as `D`. Some other monsters have names of the form "*species* *job*", such as the `orc shaman`; being a type of orc, this appears as `o`. Complicating matters are the undead; a `kobold zombie` is both a kobold *and* a zombie, and the latter state takes precedence in NetHack monster naming, thus we'd want to classify this as `Z`. As such, I classified the words that appear in monster names as follows: an *indicator* is a word that strongly suggests the appropriate monster class (e.g. `sphere` strongly suggests that the monster is in class `e`); an *ambiguous word* is a word that makes much less of a suggestion (`lord` doesn't tell you much), and all other words are *nonwords* that we don't care about. The basic idea is that we look at the words in the monster name from the end backwards to the start, and pick the first indicator that we see. As such, it was necessary to ensure that each monster name contained at least one indicator, which was followed entirely by ambiguous words. As an exception, words that appear in the names of monsters that look like an `@` (the largest group) are all classified as ambiguous. Anything can appear before an indicator; for example, color names (such as `red`) always appear earlier in a name than an indicator does, and thus are considered nonwords (as they're never examined while determining a monster's identity). In the end, this program comes down to a hash table, like the other programs do. However, the table doesn't contain entries for all monster names, or for all words that appear in monster names; rather, it contains only the indicators. The hashes of ambiguous words do not appear in the table, but must be assigned to empty slots (attempting to look up an ambiguous word will always come up empty). For nonwords, it doesn't matter whether the word appears in the table or not, or whether the hash collides or not, because we never use the value of looking up a nonword. (The table is fairly sparse, so most nonwords don't appear in the table, but a few, such as `flesh`, are found in the table as a consequence of hash collisions.) Here's some examples of how this part of the program works: * `woodchuck` is a single word long (thus an indicator), and the table lookup on `woodchuck` gives us the intended answer `r`. * `abbot` is also a single word long, but looks like an `@`. As such, `abbot` is considered an ambiguous word; the table lookup comes up empty, and we return an answer of `@` by default. * `vampire lord` consists of an indicator (`vampire` corresponding to `V`) and an ambiguous word (`lord`, which is not in the table). This means that we check both words (in reverse order), then give the correct answer of `V`. * `gelatinous cube` consists of a nonword (`gelatinous`, corresponding to `H` due to a hash collision) and an indicator (`cube`, corresponding to `b`). As we only take the last word that's found in the table, this returns `b`, as expected. * `gnome mummy` consists of two indicators, `gnome` corresponding to `G` and `mummy` corresponding to `M`. We take the last indicator, and get `M`, which is what we want. The code for handling the word-based classification is the last line of the Jelly program. Here's how it works: ``` ḲÇ€t0”@;Ṫ Ḳ Split on spaces Ç€ Call function 2 (table lookup) on each entry t0 Remove trailing zeroes (function 2 returns 0 to mean "not found") ”@; Prepend an @ character Ṫ Take the last result ``` There are two real cases; if the input consists entirely of ambiguous words, `t0` deletes the entire output of the table lookups and we get an `@` outcome by default; if there are indicators in the input, `t0` will delete anything to the right of the rightmost indicator, and `Ṫ` will give us the corresponding result for that indicator. ### Table compression Of course, breaking the input into words doesn't solve the problem by itself; we still have to encode the correspondence between indicators and the corresponding monster classes (and the lack of correspondence from ambiguous words). To do this, I constructed a sparse table with 181 entries used (corresponding to the 181 indicators; this is a big improvement over the 378 monsters!), and 966 total entries (corresponding to the 966 output values of the hash function). The table is encoded in he program via the use of two strings: the first string specifies the sizes of the "gaps" in the table (which contain no entries); and the second string specifies the monster class which corresponds to each entry. These are both represented in a concise way via base conversion. In the Jelly program, the code for the table lookup, together with the program itself, is represented in the second line, from the first `µ` onwards. Here's how this part of the program works: ``` “…’ḃ21+\iµØW“&;:' ”;“…’b58¤ị;0ị@ “…’ Base 250 representation of the gap sizes ḃ21 Convert to bijective base 21 +\ Cumulative sum (converts gaps to indexes) i Find the input in this list µ Set as the new default for missing arguments ØW Uppercase + lowercase alphabets (+ junk we ignore) “&;:' ”; Prepend "&;:' " “…’ Base 250 representation of the table entries b58 Convert to base 58 ¤ Parse the preceding two lines as a unit i Use the table to index into the alphabets ;0 Append a zero i@ Use {the value as of µ} to index into the table ``` Bijective base 21 is like base 21, except that 21 is a legal digit and 0 isn't. This is a more convenient encoding for us because we count two adjacent entries as having a gap of 1, so that we can find the valid indexes via cumulative sum. When it comes to the part of the table that holds the values, we have 58 unique values, so we first decode into 58 consecutive integers, and then decode again using a lookup table that maps these into the actual characters being used. (Most of these are letters, so we start this secondary lookup table with the non-letter entries, `&;:'` , and then just append a Jelly constant that starts with the uppercase and lowercase alphabets; it also has some other junk but we don't care about that.) Jelly's "index not found" sentinel value, if you use it to index into a list, returns the last element of the list; thus, I appended a zero (an integer zero, even though the table's mostly made of characters) to the lookup table to give a more appropriate sentinel to indicate a missing entry. ### Hash function The remaining part of the program is the hash function. This starts out simply enough, with `OḌ`; this converts the input string into its ASCII codes, and then calculates the last code, plus 10 times the penultimate code, plus 100 times the code before, and so on (this has a very short representation in Jelly because it's more commonly used as a string→integer conversion function). However, if we simply reduced this hash directly via a modulus operation, we'd end up needing a rather large table. So instead, I start off with a chain of operations to reduce the table. They each work like this: we take the fifth power of the current hash value; then we reduce the value modulo a constant (which constant depends on which operation we're using). This chain gives more savings (in terms of reducing the resulting table size) than it costs (in terms of needing to encode the chain of operations itself), in two ways: it can make the table *much* smaller (966 rather than 3529 entries), and the use of multiple stages gives more opportunity to introduce beneficial collisions (this didn't happen much, but there is one such collision: both `Death` and `Yeenoghu` hash to 806, thus allowing us to remove one entry from the table, as they both go to `&`). The moduli that are used here are [3529, 2163, 1999, 1739, 1523, 1378, 1246, 1223, 1145, 966]. Incidentally, the reason for raising to the fifth power is that if you just take the value directly, the gaps tend to stay the same size, whereas exponentiation moves the gaps around and can make it possible for the table to become distributed more evenly after the chain rather than getting stuck in a local minimum (more evenly distributed gaps allow for a terser encoding of the gap sizes). This has to be an odd power in order to prevent the fact that *x*²=(-*x*)² introducing collisions, and 5 worked better than 3. The first line of the program encodes the sequence of moduli using delta encoding: ``` “…’;“…‘_\ “…’ Compressed integer list encoding, arbitrary sized integers ; Append “…‘ Compressed integer list encoding, small integers (≤ 249) _\ Take cumulative differences ``` The remainder of the program, the start of the second line, implements the hash function: ``` OḌ;¢*5$%¥/ O Take ASCII codepoints Ḍ "Convert from decimal", generalized to values outside the range 0-9 ;¢ Append the table of moduli from the previous line / Then reduce by: *5$ raising to the power 5 (parsing this as a group) %¥ and modulusing by the right argument (parsing this as a group, too). ``` ## Verification This is the Perl script I used to verify that the program works correctly: ``` use warnings; use strict; use utf8; use IPC::Run qw/run/; my %monsters = ("Aleax", "A", "Angel", "A", "Arch Priest", "@", "Archon", "A", "Ashikaga Takauji", "@", "Asmodeus", "&", "Baalzebub", "&", "Chromatic Dragon", "D", "Croesus", "@", "Cyclops", "H", "Dark One", "@", "Death", "&", "Demogorgon", "&", "Dispater", "&", "Elvenking", "@", "Famine", "&", "Geryon", "&", "Grand Master", "@", "Green-elf", "@", "Grey-elf", "@", "Hippocrates", "@", "Ixoth", "D", "Juiblex", "&", "Keystone Kop", "K", "King Arthur", "@", "Kop Kaptain", "K", "Kop Lieutenant", "K", "Kop Sergeant", "K", "Lord Carnarvon", "@", "Lord Sato", "@", "Lord Surtur", "H", "Master Assassin", "@", "Master Kaen", "@", "Master of Thieves", "@", "Medusa", "@", "Minion of Huhetotl", "&", "Mordor orc", "o", "Nalzok", "&", "Nazgul", "W", "Neferet the Green", "@", "Norn", "@", "Olog-hai", "T", "Oracle", "@", "Orcus", "&", "Orion", "@", "Pelias", "@", "Pestilence", "&", "Scorpius", "s", "Shaman Karnov", "@", "Thoth Amon", "@", "Twoflower", "@", "Uruk-hai", "o", "Vlad the Impaler", "V", "Wizard of Yendor", "@", "Woodland-elf", "@", "Yeenoghu", "&", "abbot", "@", "acid blob", "b", "acolyte", "@", "air elemental", "E", "aligned priest", "@", "ape", "Y", "apprentice", "@", "arch-lich", "L", "archeologist", "@", "attendant", "@", "baby black dragon", "D", "baby blue dragon", "D", "baby crocodile", ":", "baby gray dragon", "D", "baby green dragon", "D", "baby long worm", "w", "baby orange dragon", "D", "baby purple worm", "w", "baby red dragon", "D", "baby silver dragon", "D", "baby white dragon", "D", "baby yellow dragon", "D", "balrog", "&", "baluchitherium", "q", "barbarian", "@", "barbed devil", "&", "barrow wight", "W", "bat", "B", "black dragon", "D", "black light", "y", "black naga hatchling", "N", "black naga", "N", "black pudding", "P", "black unicorn", "u", "blue dragon", "D", "blue jelly", "j", "bone devil", "&", "brown mold", "F", "brown pudding", "P", "bugbear", "h", "captain", "@", "carnivorous ape", "Y", "cave spider", "s", "caveman", "@", "cavewoman", "@", "centipede", "s", "chameleon", ":", "chickatrice", "c", "chieftain", "@", "clay golem", "'", "cobra", "S", "cockatrice", "c", "couatl", "A", "coyote", "d", "crocodile", ":", "demilich", "L", "dingo", "d", "disenchanter", "R", "djinni", "&", "dog", "d", "doppelganger", "@", "dust vortex", "v", "dwarf king", "h", "dwarf lord", "h", "dwarf mummy", "M", "dwarf zombie", "Z", "dwarf", "h", "earth elemental", "E", "electric eel", ";", "elf mummy", "M", "elf zombie", "Z", "elf", "@", "elf-lord", "@", "energy vortex", "v", "erinys", "&", "ettin mummy", "M", "ettin zombie", "Z", "ettin", "H", "fire ant", "a", "fire elemental", "E", "fire giant", "H", "fire vortex", "v", "flaming sphere", "e", "flesh golem", "'", "floating eye", "e", "fog cloud", "v", "forest centaur", "C", "fox", "d", "freezing sphere", "e", "frost giant", "H", "gargoyle", "g", "garter snake", "S", "gas spore", "e", "gecko", ":", "gelatinous cube", "b", "ghost", " ", "ghoul", "Z", "giant ant", "a", "giant bat", "B", "giant beetle", "a", "giant eel", ";", "giant mimic", "m", "giant mummy", "M", "giant rat", "r", "giant spider", "s", "giant zombie", "Z", "giant", "H", "glass golem", "'", "glass piercer", "p", "gnome king", "G", "gnome lord", "G", "gnome mummy", "M", "gnome zombie", "Z", "gnome", "G", "gnomish wizard", "G", "goblin", "o", "gold golem", "'", "golden naga hatchling", "N", "golden naga", "N", "gray dragon", "D", "gray ooze", "P", "gray unicorn", "u", "green dragon", "D", "green mold", "F", "green slime", "P", "gremlin", "g", "grid bug", "x", "guard", "@", "guardian naga hatchling", "N", "guardian naga", "N", "guide", "@", "healer", "@", "hell hound pup", "d", "hell hound", "d", "hezrou", "&", "high priest", "@", "hill giant", "H", "hill orc", "o", "hobbit", "h", "hobgoblin", "o", "homunculus", "i", "horned devil", "&", "horse", "u", "housecat", "f", "human mummy", "M", "human zombie", "Z", "human", "@", "hunter", "@", "ice devil", "&", "ice troll", "T", "ice vortex", "v", "iguana", ":", "imp", "i", "incubus", "&", "iron golem", "'", "iron piercer", "p", "jabberwock", "J", "jackal", "d", "jaguar", "f", "jellyfish", ";", "ki-rin", "A", "killer bee", "a", "kitten", "f", "knight", "@", "kobold lord", "k", "kobold mummy", "M", "kobold shaman", "k", "kobold zombie", "Z", "kobold", "k", "kraken", ";", "large cat", "f", "large dog", "d", "large kobold", "k", "large mimic", "m", "leather golem", "'", "lemure", "i", "leocrotta", "q", "leprechaun", "l", "lich", "L", "lichen", "F", "lieutenant", "@", "little dog", "d", "lizard", ":", "long worm", "w", "lurker above", "t", "lynx", "f", "mail daemon", "&", "manes", "i", "marilith", "&", "master lich", "L", "master mind flayer", "h", "mastodon", "q", "mind flayer", "h", "minotaur", "H", "monk", "@", "monkey", "Y", "mountain centaur", "C", "mountain nymph", "n", "mumak", "q", "nalfeshnee", "&", "neanderthal", "@", "newt", ":", "ninja", "@", "nurse", "@", "ochre jelly", "j", "ogre king", "O", "ogre lord", "O", "ogre", "O", "orange dragon", "D", "orc mummy", "M", "orc shaman", "o", "orc zombie", "Z", "orc", "o", "orc-captain", "o", "owlbear", "Y", "page", "@", "panther", "f", "paper golem", "'", "piranha", ";", "pit fiend", "&", "pit viper", "S", "plains centaur", "C", "pony", "u", "priest", "@", "priestess", "@", "prisoner", "@", "purple worm", "w", "pyrolisk", "c", "python", "S", "quantum mechanic", "Q", "quasit", "i", "queen bee", "a", "quivering blob", "b", "rabid rat", "r", "ranger", "@", "raven", "B", "red dragon", "D", "red mold", "F", "red naga hatchling", "N", "red naga", "N", "rock mole", "r", "rock piercer", "p", "rock troll", "T", "rogue", "@", "rope golem", "'", "roshi", "@", "rothe", "q", "rust monster", "R", "salamander", ":", "samurai", "@", "sandestin", "&", "sasquatch", "Y", "scorpion", "s", "sergeant", "@", "sewer rat", "r", "shade", " ", "shark", ";", "shocking sphere", "e", "shopkeeper", "@", "shrieker", "F", "silver dragon", "D", "skeleton", "Z", "small mimic", "m", "snake", "S", "soldier ant", "a", "soldier", "@", "spotted jelly", "j", "stalker", "E", "steam vortex", "v", "stone giant", "H", "stone golem", "'", "storm giant", "H", "straw golem", "'", "student", "@", "succubus", "&", "tengu", "i", "thug", "@", "tiger", "f", "titan", "H", "titanothere", "q", "tourist", "@", "trapper", "t", "troll", "T", "umber hulk", "U", "valkyrie", "@", "vampire bat", "B", "vampire lord", "V", "vampire", "V", "violet fungus", "F", "vrock", "&", "warg", "d", "warhorse", "u", "warrior", "@", "watch captain", "@", "watchman", "@", "water demon", "&", "water elemental", "E", "water moccasin", "S", "water nymph", "n", "water troll", "T", "werejackal", "d", "wererat", "r", "werewolf", "d", "white dragon", "D", "white unicorn", "u", "winged gargoyle", "g", "winter wolf cub", "d", "winter wolf", "d", "wizard", "@", "wolf", "d", "wood golem", "'", "wood nymph", "n", "woodchuck", "r", "wraith", "W", "wumpus", "q", "xan", "x", "xorn", "X", "yellow dragon", "D", "yellow light", "y", "yellow mold", "F", "yeti", "Y", "zruty", "z"); for my $monster (sort keys %monsters) { run ["./jelly", "fu", "monsters.j", $monster], \ "", \my $out; print "$monster -> \"$out\" (", ($out ne $monsters{$monster} ? "in" : ""), "correct)\n"; } ``` [Answer] ## JavaScript (ES6), ~~915~~ ... ~~902~~ 890 bytes ``` w=>[..."aZM?o@;LWu&P?D@zF@W: @aT&@nCEfvQ&R&Tb'b@&p@:Srn @ahlrdpdT'TRv:HUYG@&fSfYdG&SGHL@Mh@G@gs';@CS@km@OsirA@q@njOZS@O@';HYqHE&DJavq&&aYaBmZMf;bv@EqHg@Z@;dm@M@?@rs@d@@oDAosDT@d@ZeBVrq@jFooD@VV&&BvMEDKiuiPC@&@DYrD&eD@D@@:AwccKZiF:DKLXAwdL@w&@@u'Hc@@q&;D:::WjdN@N@xD&eFh@gh@&Md?&Ye@@&h@hNN'Z&qtKEd@@HtH&@'@&@xd&dZsv@oo@FDyd@@&&@&@HS'Hw?DF@@@MPfDfi'AH&@@pkZkuMyZhFNN'P?d@u@NN&B@uo'fdi@?ke&"].find((_,i)=>!(s-=`GD4~#_@'R<1*~7C7RbZ6F'"Sa&!*1),#''3'.+B6(K$.l%9&!#0@51""~/+!gaW!/.(5'-@0'';!%C.&""!-.$16.2>(#&g!!O,#8A50O!)*(9b|Z4@7V).;*A*HWO(g1$/*-4&SL1I#K$#"3"#=e/'V~4'B(*,.3),$@D3)*76-"\\&kL7(-4#=7!!#+(B/B!-%!"_+!")+)0$1:E84!L191&)(255)!3O<,90NN6&;Q2'"bO=*h7.%1![<o!%M'G5/R.0$-J*%\\~6T?>)16""L&!X94T4"3$!2'^070Y2a"##)#"&n&(+1*&!-M""73R5%'y0~$-6<".MV?+1*ED>!B6b!)%&)8.+$&X0~Q'E%8&#%S/H.1<#>~!sU`.charCodeAt(i)-32),w=w.replace(/\W/g,1),s=parseInt((w+=w+w)[0]+w[2]+w[3]+w[6]+[...w].pop(),36)%8713) ``` ### Formatted Below is a formatted version of the code with truncated payload data. ``` w => [..."aZM(…)"].find( (_, i) => !(s -= `GD4(…)`.charCodeAt(i) - 32), w = w.replace(/\W/g, 1), s = parseInt((w += w + w)[0] + w[2] + w[3] + w[6] + [...w].pop(), 36) % 8713 ) ``` ### How it works **Step #1** We first reduce the monster name by: 1. Replacing non-alphanumerical characters (spaces and dashes) with `1`'s. 2. Repeating this string 3 times to make sure that we have enough characters to work with for the next step. 3. Keeping only the 1st, 3rd, 4th, 7th and last characters. Examples: ``` 1.34..7..L Demogorgon -> Dmorn ^ ^^ ^ ^ 1.34..7.L orc mummy -> orc1mummy -> oc1my ^ ^^ ^ ^ 1.34..7....L xorn -> xornxornxorn -> xrnrn ^ ^^ ^ ^ ``` This leads to a few collisions. For instance, `"Master Assassin"` and `"Master Kaen"` are both reduced to `"Mst1n"`. Fortunately, all colliding monster names share the same symbol (`@` in this case). **Step #2** Then, we interpret this 5-character string as a base 36 quantity to convert it to decimal (this operation is case insensitive) and we apply a modulo `8713`, which was empirically chosen to produce a collision-free list of keys. Examples: ``` Dmorn --[from base 36]--> 22893539 --[MOD 8713]--> 4488 oc1my --[from base 36]--> 40872778 --[MOD 8713]--> 95 xrnrn --[from base 36]--> 56717843 --[MOD 8713]--> 4926 ``` **Step #3** All keys are sorted in ascending order: ``` [ 39, 75, 95, 192, 255, 287, 294, 344, 372, 389, 399, 516, 551, 574, 624, ..., 8635, 8688 ] ``` Converted to delta values: ``` [ 39, 36, 20, 97, 63, 32, 7, 50, 28, 17, 10, 117, 35, 23, 50, ..., 83, 53 ] ``` And encoded as ASCII characters in the range `[ 32, 126 ]`. Some intermediate dummy values are inserted when the difference between two consecutive keys exceeds the maximum encodable magnitude. Finally, the list of keys is mapped to a list of symbols arranged in the same order. ### Test ``` f= w=>[..."aZM?o@;LWu&P?D@zF@W: @aT&@nCEfvQ&R&Tb'b@&p@:Srn @ahlrdpdT'TRv:HUYG@&fSfYdG&SGHL@Mh@G@gs';@CS@km@OsirA@q@njOZS@O@';HYqHE&DJavq&&aYaBmZMf;bv@EqHg@Z@;dm@M@?@rs@d@@oDAosDT@d@ZeBVrq@jFooD@VV&&BvMEDKiuiPC@&@DYrD&eD@D@@:AwccKZiF:DKLXAwdL@w&@@u'Hc@@q&;D:::WjdN@N@xD&eFh@gh@&Md?&Ye@@&h@hNN'Z&qtKEd@@HtH&@'@&@xd&dZsv@oo@FDyd@@&&@&@HS'Hw?DF@@@MPfDfi'AH&@@pkZkuMyZhFNN'P?d@u@NN&B@uo'fdi@?ke&"].find((_,i)=>!(s-=`GD4~#_@'R<1*~7C7RbZ6F'"Sa&!*1),#''3'.+B6(K$.l%9&!#0@51""~/+!gaW!/.(5'-@0'';!%C.&""!-.$16.2>(#&g!!O,#8A50O!)*(9b|Z4@7V).;*A*HWO(g1$/*-4&SL1I#K$#"3"#=e/'V~4'B(*,.3),$@D3)*76-"\\&kL7(-4#=7!!#+(B/B!-%!"_+!")+)0$1:E84!L191&)(255)!3O<,90NN6&;Q2'"bO=*h7.%1![<o!%M'G5/R.0$-J*%\\~6T?>)16""L&!X94T4"3$!2'^070Y2a"##)#"&n&(+1*&!-M""73R5%'y0~$-6<".MV?+1*ED>!B6b!)%&)8.+$&X0~Q'E%8&#%S/H.1<#>~!sU`.charCodeAt(i)-32),w=w.replace(/\W/g,1),s=parseInt((w+=w+w)[0]+w[2]+w[3]+w[6]+[...w].pop(),36)%8713) list = { "Aleax": "A", "Angel": "A", "Arch Priest": "@", "Archon": "A", "Ashikaga Takauji": "@", "Asmodeus": "&", "Baalzebub": "&", "Chromatic Dragon": "D", "Croesus": "@", "Cyclops": "H", "Dark One": "@", "Death": "&", "Demogorgon": "&", "Dispater": "&", "Elvenking": "@", "Famine": "&", "Geryon": "&", "Grand Master": "@", "Green-elf": "@", "Grey-elf": "@", "Hippocrates": "@", "Ixoth": "D", "Juiblex": "&", "Keystone Kop": "K", "King Arthur": "@", "Kop Kaptain": "K", "Kop Lieutenant": "K", "Kop Sergeant": "K", "Lord Carnarvon": "@", "Lord Sato": "@", "Lord Surtur": "H", "Master Assassin": "@", "Master Kaen": "@", "Master of Thieves": "@", "Medusa": "@", "Minion of Huhetotl": "&", "Mordor orc": "o", "Nalzok": "&", "Nazgul": "W", "Neferet the Green": "@", "Norn": "@", "Olog-hai": "T", "Oracle": "@", "Orcus": "&", "Orion": "@", "Pelias": "@", "Pestilence": "&", "Scorpius": "s", "Shaman Karnov": "@", "Thoth Amon": "@", "Twoflower": "@", "Uruk-hai": "o", "Vlad the Impaler": "V", "Wizard of Yendor": "@", "Woodland-elf": "@", "Yeenoghu": "&", "abbot": "@", "acid blob": "b", "acolyte": "@", "air elemental": "E", "aligned priest": "@", "ape": "Y", "apprentice": "@", "arch-lich": "L", "archeologist": "@", "attendant": "@", "baby black dragon": "D", "baby blue dragon": "D", "baby crocodile": ":", "baby gray dragon": "D", "baby green dragon": "D", "baby long worm": "w", "baby orange dragon": "D", "baby purple worm": "w", "baby red dragon": "D", "baby silver dragon": "D", "baby white dragon": "D", "baby yellow dragon": "D", "balrog": "&", "baluchitherium": "q", "barbarian": "@", "barbed devil": "&", "barrow wight": "W", "bat": "B", "black dragon": "D", "black light": "y", "black naga hatchling": "N", "black naga": "N", "black pudding": "P", "black unicorn": "u", "blue dragon": "D", "blue jelly": "j", "bone devil": "&", "brown mold": "F", "brown pudding": "P", "bugbear": "h", "captain": "@", "carnivorous ape": "Y", "cave spider": "s", "caveman": "@", "cavewoman": "@", "centipede": "s", "chameleon": ":", "chickatrice": "c", "chieftain": "@", "clay golem": "'", "cobra": "S", "cockatrice": "c", "couatl": "A", "coyote": "d", "crocodile": ":", "demilich": "L", "dingo": "d", "disenchanter": "R", "djinni": "&", "dog": "d", "doppelganger": "@", "dust vortex": "v", "dwarf king": "h", "dwarf lord": "h", "dwarf mummy": "M", "dwarf zombie": "Z", "dwarf": "h", "earth elemental": "E", "electric eel": ";", "elf mummy": "M", "elf zombie": "Z", "elf": "@", "elf-lord": "@", "energy vortex": "v", "erinys": "&", "ettin mummy": "M", "ettin zombie": "Z", "ettin": "H", "fire ant": "a", "fire elemental": "E", "fire giant": "H", "fire vortex": "v", "flaming sphere": "e", "flesh golem": "'", "floating eye": "e", "fog cloud": "v", "forest centaur": "C", "fox": "d", "freezing sphere": "e", "frost giant": "H", "gargoyle": "g", "garter snake": "S", "gas spore": "e", "gecko": ":", "gelatinous cube": "b", "ghost": " ", "ghoul": "Z", "giant ant": "a", "giant bat": "B", "giant beetle": "a", "giant eel": ";", "giant mimic": "m", "giant mummy": "M", "giant rat": "r", "giant spider": "s", "giant zombie": "Z", "giant": "H", "glass golem": "'", "glass piercer": "p", "gnome king": "G", "gnome lord": "G", "gnome mummy": "M", "gnome zombie": "Z", "gnome": "G", "gnomish wizard": "G", "goblin": "o", "gold golem": "'", "golden naga hatchling": "N", "golden naga": "N", "gray dragon": "D", "gray ooze": "P", "gray unicorn": "u", "green dragon": "D", "green mold": "F", "green slime": "P", "gremlin": "g", "grid bug": "x", "guard": "@", "guardian naga hatchling": "N", "guardian naga": "N", "guide": "@", "healer": "@", "hell hound pup": "d", "hell hound": "d", "hezrou": "&", "high priest": "@", "hill giant": "H", "hill orc": "o", "hobbit": "h", "hobgoblin": "o", "homunculus": "i", "horned devil": "&", "horse": "u", "housecat": "f", "human mummy": "M", "human zombie": "Z", "human": "@", "hunter": "@", "ice devil": "&", "ice troll": "T", "ice vortex": "v", "iguana": ":", "imp": "i", "incubus": "&", "iron golem": "'", "iron piercer": "p", "jabberwock": "J", "jackal": "d", "jaguar": "f", "jellyfish": ";", "ki-rin": "A", "killer bee": "a", "kitten": "f", "knight": "@", "kobold lord": "k", "kobold mummy": "M", "kobold shaman": "k", "kobold zombie": "Z", "kobold": "k", "kraken": ";", "large cat": "f", "large dog": "d", "large kobold": "k", "large mimic": "m", "leather golem": "'", "lemure": "i", "leocrotta": "q", "leprechaun": "l", "lich": "L", "lichen": "F", "lieutenant": "@", "little dog": "d", "lizard": ":", "long worm": "w", "lurker above": "t", "lynx": "f", "mail daemon": "&", "manes": "i", "marilith": "&", "master lich": "L", "master mind flayer": "h", "mastodon": "q", "mind flayer": "h", "minotaur": "H", "monk": "@", "monkey": "Y", "mountain centaur": "C", "mountain nymph": "n", "mumak": "q", "nalfeshnee": "&", "neanderthal": "@", "newt": ":", "ninja": "@", "nurse": "@", "ochre jelly": "j", "ogre king": "O", "ogre lord": "O", "ogre": "O", "orange dragon": "D", "orc mummy": "M", "orc shaman": "o", "orc zombie": "Z", "orc": "o", "orc-captain": "o", "owlbear": "Y", "page": "@", "panther": "f", "paper golem": "'", "piranha": ";", "pit fiend": "&", "pit viper": "S", "plains centaur": "C", "pony": "u", "priest": "@", "priestess": "@", "prisoner": "@", "purple worm": "w", "pyrolisk": "c", "python": "S", "quantum mechanic": "Q", "quasit": "i", "queen bee": "a", "quivering blob": "b", "rabid rat": "r", "ranger": "@", "raven": "B", "red dragon": "D", "red mold": "F", "red naga hatchling": "N", "red naga": "N", "rock mole": "r", "rock piercer": "p", "rock troll": "T", "rogue": "@", "rope golem": "'", "roshi": "@", "rothe": "q", "rust monster": "R", "salamander": ":", "samurai": "@", "sandestin": "&", "sasquatch": "Y", "scorpion": "s", "sergeant": "@", "sewer rat": "r", "shade": " ", "shark": ";", "shocking sphere": "e", "shopkeeper": "@", "shrieker": "F", "silver dragon": "D", "skeleton": "Z", "small mimic": "m", "snake": "S", "soldier ant": "a", "soldier": "@", "spotted jelly": "j", "stalker": "E", "steam vortex": "v", "stone giant": "H", "stone golem": "'", "storm giant": "H", "straw golem": "'", "student": "@", "succubus": "&", "tengu": "i", "thug": "@", "tiger": "f", "titan": "H", "titanothere": "q", "tourist": "@", "trapper": "t", "troll": "T", "umber hulk": "U", "valkyrie": "@", "vampire bat": "B", "vampire lord": "V", "vampire": "V", "violet fungus": "F", "vrock": "&", "warg": "d", "warhorse": "u", "warrior": "@", "watch captain": "@", "watchman": "@", "water demon": "&", "water elemental": "E", "water moccasin": "S", "water nymph": "n", "water troll": "T", "werejackal": "d", "wererat": "r", "werewolf": "d", "white dragon": "D", "white unicorn": "u", "winged gargoyle": "g", "winter wolf cub": "d", "winter wolf": "d", "wizard": "@", "wolf": "d", "wood golem": "'", "wood nymph": "n", "woodchuck": "r", "wraith": "W", "wumpus": "q", "xan": "x", "xorn": "X", "yellow dragon": "D", "yellow light": "y", "yellow mold": "F", "yeti": "Y", "zruty": "z" }; success = error = 0; for(w in list) { list[w] == f(w) ? success++ : error++; } console.log("Success:", success); console.log("Error:", error); ``` [Answer] ## Java, 1130 bytes ``` import java.util.*;class G{public static void main(String[]u){BitSet s=BitSet.valueOf(Base64.getDecoder().decode("D94FuoCWYEIhCTEgLWwRNU/CMB1cE7XBhxBsBCusihaASRg14IJpQMOIDJdFx3BOdDcmThdhILVkCgGsEmhII8UE+SB4kDYEEJzw7Tw54oUEQZe0AUHCACH6nAdqgiZgJhASCIPAEAzJBmuMIrBCHE8IiFjgKQwrN4/90B4QFaLBQBEwTArRBMLCLHQOUQs7ZXZ8B8uGC1EbeAMJBdihUDgCIwGUEKgEAu4W2SJkIAhzB1IQSHgNiEAwABQECV5BvAB7eizABXxFLEg5iMA3whhAFXOKHXEURB7UA7PQjgUK7sji8CmIC0FJsTB4tAMFgiARB3hOJATDsBkgGKnGmWIiIWBRwkMgToQJ49G8gTR4IqcB4vJwDBHSVBLQhpwHsUFipqBcWWaEsCBoGBF0AlNAE305HAfdU1AEbELBO0EERAfkmMkgZcEXDIa4MAp4HcENmYAMBB7UBbTwBqQPSMS9kVkEBMhCudAqBAKaR1CzZggDRw8WMAh0FQPEyKAsRAxzBwn0grwDMQMyQMdADRtFUBAsBQetRRBwcUgrlsQ1IkosBc9B6iBcjAkSDDKgEAQ1wgLIMEEwMkYB42ERBCdiEJMAt1wYSIAQkdIEI0UPNhALsDnRQ1AT/HQi1AyCEwiICOICpiAPlB8MwxnBPIk6JYaIgDy8NJHDsiAqzK0JAXpQPXgPLwJuEEbMTAGBYlQbDESvAXJAAQ=="));int i,j,k,c,d,h=u[0].hashCode(),a=(h&4092)>>2|(h>>5)&1024|(h>>7)&2048|(h>>9)&4096;char r='@';for(i=k=0;i<4297;i+=14){for(c=0,j=7;j>=0;j--)c+=c+(s.get(i+j)?1:0);if((k+=c)==a){for(d=0,j=13;j>=8;j--)d+=d+(s.get(i+j)?1:0);r=d<5?" &':;".charAt(d):(char)((d<31?60:66)+d);}}System.out.println(r);}} ``` Ungolfed: ``` import java.util.*; class G { public static void main(String[] u) { BitSet s = BitSet.valueOf(Base64.getDecoder().decode( "D94FuoCWYEIhCTEgLWwRNU/CMB1cE7XBhxBsBCusihaASRg14IJpQMOIDJdFx3BOdDcmThdhILVkCgGsEmhII8UE+SB4kDYEEJzw7Tw54oUEQZe0AUHCACH6nAdqgiZgJhASCIPAEAzJBmuMIrBCHE8IiFjgKQwrN4/90B4QFaLBQBEwTArRBMLCLHQOUQs7ZXZ8B8uGC1EbeAMJBdihUDgCIwGUEKgEAu4W2SJkIAhzB1IQSHgNiEAwABQECV5BvAB7eizABXxFLEg5iMA3whhAFXOKHXEURB7UA7PQjgUK7sji8CmIC0FJsTB4tAMFgiARB3hOJATDsBkgGKnGmWIiIWBRwkMgToQJ49G8gTR4IqcB4vJwDBHSVBLQhpwHsUFipqBcWWaEsCBoGBF0AlNAE305HAfdU1AEbELBO0EERAfkmMkgZcEXDIa4MAp4HcENmYAMBB7UBbTwBqQPSMS9kVkEBMhCudAqBAKaR1CzZggDRw8WMAh0FQPEyKAsRAxzBwn0grwDMQMyQMdADRtFUBAsBQetRRBwcUgrlsQ1IkosBc9B6iBcjAkSDDKgEAQ1wgLIMEEwMkYB42ERBCdiEJMAt1wYSIAQkdIEI0UPNhALsDnRQ1AT/HQi1AyCEwiICOICpiAPlB8MwxnBPIk6JYaIgDy8NJHDsiAqzK0JAXpQPXgPLwJuEEbMTAGBYlQbDESvAXJAAQ==")); int i, j, k, c, d, h = u[0].hashCode(), a = (h & 4092) >> 2 | (h >> 5) & 1024 | (h >> 7) & 2048 | (h >> 9) & 4096; char r = '@'; for (i = 0, k = 0; i < 4297; i += 14) { for (c = 0, j = 7; j >= 0; j--) c += c + (s.get(i + j) ? 1 : 0); if ((k += c) == a) { for (d = 0, j = 13; j >= 8; j--) d += d + (s.get(i + j) ? 1 : 0); r = d < 5 ? " &':;".charAt(d) : (char) ((d < 31 ? 60 : 66) + d); } } System.out.println(r); } } ``` Monster names are: * hashed using Java `hashcode` method => *32 bits* * ANDed with mask 1001001000111111111100 => *13 bits* * sorted from smallest to biggest * we then use the delta values of the sorted list => *8 bits* The display character is encoded on 6 bits. So each tuple (monster name, character) uses 14 bits. All the tuples are saved in a BitSet and base 64 encoded. I lose a lot of bytes with base64 encoding and BitSet operations :-) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 228 bytes in Jelly's encoding ``` ȷ;€`ḥþḲḋ“Ṗ³2Ḅ:rṡXTɗP½ȧọʂḃ¤ḋʋßw`Ḍḋẇ^wḤxḌƝ⁴⁽Ẓ£g§n/ɓ1Ọؽ¶GØßḅƑÐḣȤYɲ⁽ẉG³ȯṅ#Ƭṫ¢>f®dŒḊ(ṡC®a6ȮỵḞJḶÑƁėġBȦṣịḊƙỴ\!W2Ɱ=M\j⁻æÆ⁻¢Ỵ(¬ɼEḲȯɲ{½ⱮŀỴ?4IbÐƬ&ḃ|ṅæbṄỌḋXġọṀ¤$⁴⁻Ƙ¥ƈŀṭĖẹD°ðṭþḄ#Ð⁷ɗƬ½©ƥFȤ[qU⁹ẏɼn;rṆ=$ḌṘ*ṙðȧʠżġḷƙṄ!’b59$¤%59t0Ṫo1ịØW“@&;:' ”;$¤ ``` [Try it online!](https://tio.run/##HZFdTxNBFIb/SoEKxBuVCAk0iPGLaGLihQaIhNCGYiSlxkqCRC52sXxIIRRM6DYRoXTbRl1LLUhnuq0XZ9rJbP/FmT@yHriaOXPek/M@7yxEY7EV31e1kF5zZpEVxD9kVWQpbXxDfgjnA8iSIwnkucmXXuYFNFUJ3d3OGrLPYJOskxLHyzS3Q3esb84sI7M/UimPtHmhzSbWDyD/BkrxW97XO@juCAuacDkuLHGMbF3uizSyvLKnvOq1@Ms4nKsz5Os90kH@C07vzUN5rn2AbLufPDyEcnhIldH9i@z7M2SXYl@arUwr90AVkefRTZFQZtG9mO6aGNB/yqPPpxe06Yqi2KADTqnTD47XeEyQ6syrfoImqdoGvY/dfRoRaen0EtoqORDFCPIkWSayyVaOqJEbYAevuVxpQUFu0SD/3TrEOn8EFVGh4iq@ZI9Ia7PmZaRDsD9k4YmyX79/pU2O9T2vEQ9RnBujwavQuHUTeVZUVKlz0m7QFlYj@zzZpY1sZHA4CPaNweGl28h/vqP0UsKaoH@53xsa6Qto4yhEfd/3uxfDH5aiicDi2/hcYD4WXokmuv8D "Jelly – Try It Online") ## History Although I've had [the (previously) winning answer](https://codegolf.stackexchange.com/a/105569) on this question for most of its lifetime, something has been bugging me on and off for much of that time. All the answers so far have worked along the lines of "use a hash function to convert the input to a number in a collision-free way, then look up the resulting number in a lookup table". The basic problem here is that if you just use a randomly selected hash function (or a random oracle), the [birthday paradox](https://en.wikipedia.org/wiki/Birthday_problem) means that the lookup table has to be *much* larger than the number of monsters that you can actually look up in it (meaning that it's a sparse table, and you need to store the gaps between the elements somewhere, a significant contribution to the program size). My previous solution took advantage of the structure of monster names, and the zeroes in a sparse table, to reduce the 378 monsters to 171 indicators; but using a general-purpose hash function directly, this would still require a 3529-element table (with all elements other than the 171 indicators as zero). Intentionally salting the hash algorithm to reduce collisions reduced the size of the table to 966, but there are limits to how much this technique can help (eventually the size required to store the salt outweighs the savings from a more compact table). So even with an advanced solution like this, the "hash without collisions, then look up in a table" solution seemed like it was storing a lot more data than it really needed to. So the question that was bothering me all this time was: is there some sort of optimal generic construction for this sort of problem? "Hash without collisions + table lookup" doesn't work, but maybe something will. I'm pleased to announce that I've now found a generic construction that's usable to produce asymptotically optimal solutions for all problems of this type (assuming that there are no exploitable patterns in the function), allowing me to golf off an additional 25% over my previous solution (which was already less than 35% of the size of the next-best solution). ## Algorithm This algorithm exploits the structure of the problem in a similar way to my previous answer, but in a simpler way. The monster name is split into words. If the last word is anything other than `lord`, `king`, `shaman`, or `wizard`, it uniquely identifies the monster's symbol; we look it up in a lookup table. For `lord`, `king`, `shaman`, or `wizard`, the previous word in the monster's name is used. There is one monster, `wizard`, which ends with one of the ambiguous words and has no previous word; this monster is represented by the symbol `@`, and the algorithm has a special case to return `@` if the previous word does not exist. The bulk of the program therefore consists of a lookup table that can look up 259 different words: the 255 words that are used to uniquely determine the monster symbols, plus the 4 special words `lord`, `king`, `shaman`, `wizard`. This is effectively a case of finding a function whose domain consists of arbitrary strings, and whose codomain is a number from 0 to 58 inclusive (0 for the four special words, or 1 to 58 representing one of the 58 monster symbols; I call these *symbol indexes*), and for which we only care about the function's behaviour at 259 different points. The lookup table is used as follows: we have 259 different hash functions (produced in a terse manner by using a single hash function with 259 different salts – Jelly has a salted hash builtin), each of which maps arbitrary strings to numbers in the range 0 to 58. This means that we can use our list of 259 hash functions will map any string to a 259-dimensional vector of elements in the finite field **GF**(59) (fortunately, 59 is a prime number, meaning that **GF**(59) exists and its field operations are easy to implement in Jelly, because they are just arithmetic modulo 59, so we can do regular arithmetic and add a `%59` at the end). The lookup table itself is also a 259-dimensional vector in **GF**(59), and the string-to-symbol-index function is defined as taking the dot product of the string's vector and the vector that is the lookup table. That's all that the program does at runtime. In order to create the lookup table vector in the first place, though (and thus to write the program), we need to find a lookup table vector for which all 259 possible dot products happen to produce the correct result. The way to do this is to imagine a lookup table vector of 259 different unknowns, and think about how we would find their values; we effectively have 259 different constraints (that the input "Aleax" produces the output 7, that the input "Amon" produces the output 1, etc.), and each of these ends up corresponding to a linear equation in these 259 variables in **GF**(59). We therefore have 259 variables and 259 equations, and can "simply" just solve these equations to figure out what the lookup table vector should be. (Of course, it is necessary that a solution actually exists, but the probability that a solution will exist when the number of variables equals the number of equations is very high; approximately (not exactly) 58 in 59 if the hash functions are modelled as independent random oracles. The 259 hash functions used here are not independent random oracles – Jelly's built-in hash function is intentionally designed to make it easy to choose salts to choose specific outputs, so the outputs with different hashes are somewhat correlated with each other – but the chance that a solution will exist still seems to be very high when using a finite field with as many as 59 different elements.) Actually formulating and solving the equations was another matter, though. As a proof of concept (and because it was interesting), I wrote a Jelly program to formulate and solve the equations for general problems of this nature, but it had O(*n*4) performance and thus was unusable for a 259-dimensional problem. In the end, I used a mixture of Perl and Jelly to calculate what the equations were, and [Sage](https://www.sagemath.org/) to actually do the work of solving them (inverting/doing elimination on a 259×259 matrix in **GF**(59) is fairly quick in Sage, taking only a few seconds). ## Explanation ``` ȷ;€`ḥþḲḋ“…’b59$¤%59t0Ṫo1ịØW“@&;:' ”;$¤ ; Form a pair using € each number from 1 to ȷ 1000 ȷ ` and 1000 þ For each pair, and each Ḳ space-separated word {in the input} ḥ hash that word, with that pair as salt ``` This produces 259 results per word in the input; the second element of the ḥ salt specifies the range of output, 1…1000. So we now have a list of 259-element vectors. ``` ȷ;€`ḥþḲḋ“…’b59$¤%59t0Ṫo1ịØW“@&;:' ”;$¤ ḋ Take the dot product of {each result} ¤ with a constant calculated by b59$ taking the base-59 representation of “…’ [a very large compressed integer] %59 Take the resulting value modulo 59 t0 Remove leading and trailing 0s Ṫ Last element {of the resulting list} o1 Replace empty/invalid output with 1 ị Index into ¤ a constant calculated by ;$ concatenating “@&;:' ” the string "@&;:' ", and ØW the uppercase+lowercase alphabets (plus some extra irrelevant junk) ``` My actual program has a couple of tweaks from the theoretical algorithm above, in order to save a couple of bytes. One is that it calculates 1000 different hash functions, rather than 259, and simply throws away all but the first 259 results (Jelly's `ḋ` operator will trim the longer vector to the length of the shorter); this is simply because 1000 has a shorter representation in Jelly than 259 does. Similarly, the codomain of the hash function is integers in the range 1…1000, rather than 1…259 or 0…258, to save a couple of bytes specifying the codomain (this introduces a little modulo bias into the results of the hashes when they get converted into **GF**(59), making the equations a little more likely to be unsolvable, but fortunately they still happen to be solvable). The choice of 1000 rather than 259 also randomly happens to make the compressed integer representing the lookup table vector one byte shorter than it otherwise would be (because it happens to have a smaller value). The program also performs operations in an inefficient order (from the point of view of the length of time the program takes to run); instead of looking up the last word in the table, then the second-last word if the last word is one of the four special words, it simply looks up every word immediately. This reduces the amount of control flow required, again saving a few bytes (basically, we can remove trailing 0s from the list of lookup table outputs from each word, and thus the last remaining lookup table output will be the output for the last non-special word; the `o1` handles the case of `wizard` where there are no non-special words, forcing the output to 1 which maps to `@`). The program is still fast enough that it can produce answers in a fraction of a second (although a sufficiently large fraction that there's a noticeable hesitation when running it). [Answer] # Mathematica, 1067 bytes (Mac OS Roman character encoding) ``` FromCharacterCode[Mod[Tr/@{c=ToCharacterCode@#,c^2},216,32],"MacintoshRoman"]/.Inner[Rule,";¤7«´3πœ(ú-UU=6z±'¥ÿ†tƒ|\¢KÛd§≤jSóKWÊ8‰Ñwiøì¡ÛhÓ\‡¨:–*~‚¬æº¢»‘¤Á^∫„·nLÒ¤b|$|ÇòCóÌÈS_Ñä.Ëí 5y«KΔË\Ãò™_E`J’ëΔñTV–N„'„Ÿà¥xpîH#-PP)ÈÊVQ©LrBt}∑WÉ∏dÿå„•Tz∑Âao¿rÃ^bbP¨}ëÖ◇1èÇ&d¢¤ái√,B}±BˆÍdA´íBtæÅ/m√yQ6,uãÊ≤/Î!ïøuΩÒÉ)ë“∕C$RY•ÍÍu£oÉÓå‚Ïl.·1‚40ÃÚ¨ÇÆÅccflÓ8Ï Gáç3EÑ¥fXñ¨Àìz~j÷–ñÓz0~ôWtñ}μÎ◇f||Dd\ ÙH﷿É∑Ì´|¿Ö_»RT8Ûª|Äqü‘&6Ãác›Yˆ¿ô5≈ënÚqΩåVä>∫æ∂p ¨jtöåoÌfløÏÏò§¤flÈ;À∑Ѥ·›9né∕<·ì∕ÿmŸ«Ì»j√üà‰÷“5ïä^Ûe◇kd‡“(Ïö71›iΟÁm„ÈïÒß„kÕπ°ÊÓÒçÓfˆ¨flÁ9k|¶ä∕l~Òød‹jZÏ2[kÎ√3ÛâìÓΔE]ıIÚ>{#ÁÖ‚Üâ;·?l^vàß‹‘jîÙÇÅÉú¥äärÆæ™∏Üi≈mØÂ’-%USÌâ’ı Ê›·Ëÿb‡ıÖ31nh™Δ$~%À0n-À´sflk∑p.o5vz}mè]ÎÅç©lt;Îu„ŸW„›ˆˆÍ﷿Ä*7m8‰πór,„Õш/”Ë∕ªß9±‡¶çÁ•âg˜fló)ÖÔ¡'wúæ0ñ„Kûr"~(a=StringPartition)~2,"AAA&&DH&&&&&D&KKKKH&o&WT&&soV&bEYLDD:DDwDwDDDD&q&WBDyNNPuDj&FPhYss:c'ScAd:LdR&dvhhMZhE;MZv&MZHaEHve'evCdeHgSe:b ZaBa;mMrsZH'pGGMZGGo'NNDPuDFPgxNNdd&Hohoi&ufMZ&Tv:i&'pJdf;AafkMkZk;fdkm'iqlLFd:wtf&i&LhqhHYCnq&:jOODMoZooYf';&SCuwcSQiabrBDFNNrpT'qR:&Ysr eFDZmSajEvH'H'&ifHqtTUBVVF&du&ESnTdrdDugddd'nrWqXDyFYz"~a~1,List]/.x_/;StringLength@x>1->"@"& ``` Unnamed function taking a string as input and returning a character. The function has the following form: ``` 1 FromCharacterCode[ 2 Mod[Tr/@{c=ToCharacterCode@#,c^2},216,32] 3 ,"MacintoshRoman"] /. 4 Inner[Rule, 5 GIANT_STRING_1 ~(a=StringPartition)~2, 6 GIANT_STRING_2 ~a~1, 7 List] 8 /. x_/;StringLength@x>1 -> "@" & ``` Here GIANT\_STRING\_1 is a string containing 608 one-byte characters in the Mac OS Roman character encoding (none of which are in the range 00-1F), while GIANT\_STRING\_2 is a string containing 304 ASCII characters. Line 2 starts the hash function: it converts the input string into a list of character codes (encoding irrelevant since they're all printable ASCII), then computes the sum of those character codes and the sum of their squares, both modulo 216 and forcing the answer to lie between 32 and 255. Then lines 1 and 3 convert those ordered pairs of integers into two-character strings, which is the hash value we ultimately use. Line 5 turns GIANT\_STRING\_1 into a list of 304 two-character strings; line 6 turns GIANT\_STRING\_2 into a list of 304 one-character strings. Then lines 4 and 5 convert those two lists into a set of 304 replacement rules: if you see such-and-such two-character string, turn it into such-and-such one-character string. Finally, line 8 turns any remaining two-character string into `"@"`. There are 71 monsters in the list whose symbol is `"@"`, and those are handled without hashing (I stole this idea from a comment by ais523 on another answer). It just so happens that the other 304 hash values are all unique! and so no other modifications to the algorithm are needed. (It's a lucky break that `"human"` needs to be mapped to `"@"`, since the sums of the character codes of the letters in `"human"` and the letters in `"shark"` are identical, as are the sums of the squares of those codes—as integers, not even modulo 216!) [Answer] ## Python, 2055 bytes ``` def f(s):import re;m=re.search(s[-3:-1]+s[:2]+str(len(s))+"(.)","omgn5Gteen13vligr7glero10'akga12Sanso11aragi9rgoDe10&tiet5HleVl16Vanst11Hmpmo14nubge15brsho5uingo21Nbuin7&gobl11Dgobl12Duaja6faule10lkest7Eolic9Ttawa15EanKo14KanKo12Kviba12&gore10Dimim3iutzr5zingn10Ganhi10Herfr15emmel9Mlele13'guNa6Wkaja6dotco6docvr5&petr7tmaor10oarli6:nhpi7;moma11&icli4Linbl20Nolwa11Titwr6Wtlgi12ateru12Rbign12Zozgr9Plepa11'oufo9vingu23Norhi8onena10&tati5Hiosc8sinre18Nligo6obeki10aeaow7Yeyfl12elewo10'adsh5 anfr11Hapap3Ygrog4Obequ9ahopy6Steki6fgogr11Dgogr12Dpepi9Sngdi5dindw10hlegl11'imgr11Pbava11Bcero12phaOl8Tdoli10dcuwi15dargn14GotIx5Dinbl13Parwa4dpuhe14dtisa9&ilba14:liho9onyer6&euAs8&aupl14Cttle9qmmdw11Molbr10Fmism11mncPe10&mpwa11noror3oispy8caumo16Clest11'haUr8okekr6;bigi12ZbuBa9&gowh12Dbiko13Zbiet12Zmmgn11Molwe8dmowa11&icde8Lbiho6hdola9dleJu7&otMi18&ulum10Uenpi9&luho10ighye12ymamu5qorwh13ughbl11yylga8gKoKe12Knndj6&mmet11Magbl10Narsh5;osgh5 orxo4Xoltr5Tdoma8qopCy7Hceir12pgoba18Dorlo9wgoba16Dbidw12ZinFa6&goor13DeaAl5Aiuba14qloac9bkemo6Yniqu16QteDi8&aufo14Ckesh8Fetye4Yolro9ryema18hersh15eaggo11Nrase9ranig6:ghba12Winbr13Polwi11dgeti5fzoNa6&orga9emmko12Manfi8aorgn10Gatco6Alecl10'goye13Deabu7hinog9Oheli6Feoch9:ynly4fngte5ieeel12;rawe7ricch11caior11ocala9fguvi13Fangi9aangi5Hhepa7fdesa10:cuOr5&rswa8ubrco5Sorva12Vxaxa3xovlu12tbaba3Bilcr9:geAn5Aolwo4dviic9&tafi14Ecegl13pbugr8xorpu11wgoCh16Dicar9Laggu13Ndegi12shoAr6Aolla12kedce9sitma8&erti11qicma11Lbior10Zviho12&test12vbusu8&fofo3ddeca11srara9rolko6kmpwo10ntaea15Ellbl10jgosi13Daksn5Svibo10&tosk8Zicco10cvera5Bgoba15DatDe5&goba17Dpuwu6qkawe10dmmhu11Mdodo3dunhe10dtcsa9Yckge5:tefi11vsiqu6iloqu14bewne4:yoGe6&caho8fucwo9rorMo10oisje9;taai13Eardw5holye11Fordw10hlloc11jough5Zerfl14emila11mtedu11vthro5qteic10vtuLo11Hmmor9Mirva7Vbagi9Bolro10Tmako13kleir10'biel10Zmmgi11Mnema5ilego10'olre8Forbl13usiwa14Sroba6&agre8Nrohe6&orgr12ulefl11'ocja10JghYe8&aumi8HiuSc8sbihu12Zriki6Ayemi11horko11kolgr10Furle6ianfi10Hmigi11monpo4ullsp13jaiKo11Ktedi12Rapca15Yorog9Oylwi15geegi9;orba14worba16w");return m.group(1)if m else'@' ``` Here's my test harness, in case it helps anyone else. ``` MAPPING = { # as given in the original question } def validate_solution(f): for k, v in MAPPING.iteritems(): vv = f(k) if vv != v: print 'FAIL: f(%s) = %s instead of %s' % (k, vv, v) print 'SUCCESS!' ``` I wrote a little program to enumerate all the various ways of extracting 4 characters plus the length of the string. My original plan had been to then `ord()` these characters, do some math on them, and boil it down to a perfect hash function that produced indices into a table of outputs. So I wrote another little program to enumerate all the various ways of summing/multiplying/modulo'ing these 4 characters together; but the resulting hash functions kept having *way* too many collisions. So eventually I gave up and just did what you see here, which is just a map from the small-string representation of each monster's name to the appropriate symbol. That is: What I wanted to get was ``` def f(monster_name): small_string = f1(monster_name) integer_index = f2(small_string) symbol = "relatively_short_table"[integer_index] return symbol ``` but I only managed to get as far as ``` def f(monster_name): small_string = f1(monster_name) symbol = {relatively_large_dict}[small_string] return symbol ``` where my dict lookup `{relatively_large_dict}[small_string]` is expressed as `re.match(small_string+"(.)", "relatively_large_string")` for golfiness. [Answer] # JavaScript (ES6), 1178 ``` n=>'@0uy1c8@@@@@@2cb7sj0sb5rhcm626435y6js6u651b1nj5jg85g2xj02l4wh31u2py2xl96h5fz6ys46tc7821p2e9c1o1td1cy834@2sq2c055iabn91f82vahc6ytagh5d363i@@@@@@@@@@@@@@@@@@@7hh2wf2nd1bu2d93cm0gu862@144819a6v2h44o41d4@@@@@@0c404806f3fa0z8@04c82o1vfac3@c10a3g08g@82e0lr7bf26p2dibcb11t9y19q6bbh4db7tr3592u2bof4913edawy84p1cr@bap1qzb1o033bt6@8d93v230t4240w9ahh8cy@09u0a60sd1qd@1n23ak1bt614bax0ro7sd57xagg22s1gj@@be0@74l01c28qcdi@1so83t0c068s@2jh7as7ddalq0vxag68pn6b9@0gabu71zp54m6997imb2047h@10s0zo0mv@aww6ixbqgag7@944@bza76b@1a053c2yn6101eh8en@4je6fq97t1py9f0@6co@b3k5my44p@4edb737t9@0tl@00rau75y369z5hk0ot@23d2wicb90uwb54a9l3gw9lv3z51nv@@@@@@@amy81e3kh9yc90e59d@6528z42ic@7uv6bm58t@3av0w004t05aavs3oq3040irawj0ov1n90213h89yn0vs@0mcc284fv6uyaxp@3242ok39h0jd06905v1ia@7zc9659bk@ax30ua0um0652sa65daqd@00z03d2ra1f95751xu@9x10676yz@72w33r24b63d@2d7@ats6f678u@bcg9uf6h6@1b60us2d17ygbxn72106t02g@adublf05q@8xu5wobqb1tc1c73cs7pj@87k3cj2xq6258l379y@0q42qy3vs3y70r9@06v2a9@ast4su12w0ko4y77dn@7oubr07ju1ct5qe81v@0d52kb66t4zj@93508c@af30kj@299'.replace(/@\w*/g,v=>~-v.search((100+h.toString(36)).slice(-3))%3?++i:r=String.fromCharCode(i),i=32,r='@',n.replace(/\w/g,c=>h=parseInt(c,36)^(h*3)&16383,h=0))&&r ``` **Less golfed** ``` n=>( '@0uy1c8@@@@@@2cb7sj0sb5rhcm626435y6js6u651b1nj5jg85g2xj02l4wh31u2py2xl96h5fz6ys46tc7821p2e9c1o1td1cy834@2sq2c055iabn91f82vahc6ytagh5d363i@@@@@@@@@@@@@@@@@@@7hh2wf2nd1bu2d93cm0gu862@144819a6v2h44o41d4@@@@@@0c404806f3fa0z8@04c82o1vfac3@c10a3g08g@82e0lr7bf26p2dibcb11t9y19q6bbh4db7tr3592u2bof4913edawy84p1cr@bap1qzb1o033bt6@8d93v230t4240w9ahh8cy@09u0a60sd1qd@1n23ak1bt614bax0ro7sd57xagg22s1gj@@be0@74l01c28qcdi@1so83t0c068s@2jh7as7ddalq0vxag68pn6b9@0gabu71zp54m6997imb2047h@10s0zo0mv@aww6ixbqgag7@944@bza76b@1a053c2yn6101eh8en@4je6fq97t1py9f0@6co@b3k5my44p@4edb737t9@0tl@00rau75y369z5hk0ot@23d2wicb90uwb54a9l3gw9lv3z51nv@@@@@@@amy81e3kh9yc90e59d@6528z42ic@7uv6bm58t@3av0w004t05aavs3oq3040irawj0ov1n90213h89yn0vs@0mcc284fv6uyaxp@3242ok39h0jd06905v1ia@7zc9659bk@ax30ua0um0652sa65daqd@00z03d2ra1f95751xu@9x10676yz@72w33r24b63d@2d7@ats6f678u@bcg9uf6h6@1b60us2d17ygbxn72106t02g@adublf05q@8xu5wobqb1tc1c73cs7pj@87k3cj2xq6258l379y@0q42qy3vs3y70r9@06v2a9@ast4su12w0ko4y77dn@7oubr07ju1ct5qe81v@0d52kb66t4zj@93508c@af30kj@299' .replace(/@\w*/g, v= > (v.search((100 + h.toString(36)).slice(-3))-1) % 3 ? ++i : r = String.fromCharCode(i), i=32, r='@', n.replace(/\w/g,c => h=parseInt(c,36) ^ (h*3) & 16383,h=0) ) && r ``` **Test** ``` F= n=>'@0uy1c8@@@@@@2cb7sj0sb5rhcm626435y6js6u651b1nj5jg85g2xj02l4wh31u2py2xl96h5fz6ys46tc7821p2e9c1o1td1cy834@2sq2c055iabn91f82vahc6ytagh5d363i@@@@@@@@@@@@@@@@@@@7hh2wf2nd1bu2d93cm0gu862@144819a6v2h44o41d4@@@@@@0c404806f3fa0z8@04c82o1vfac3@c10a3g08g@82e0lr7bf26p2dibcb11t9y19q6bbh4db7tr3592u2bof4913edawy84p1cr@bap1qzb1o033bt6@8d93v230t4240w9ahh8cy@09u0a60sd1qd@1n23ak1bt614bax0ro7sd57xagg22s1gj@@be0@74l01c28qcdi@1so83t0c068s@2jh7as7ddalq0vxag68pn6b9@0gabu71zp54m6997imb2047h@10s0zo0mv@aww6ixbqgag7@944@bza76b@1a053c2yn6101eh8en@4je6fq97t1py9f0@6co@b3k5my44p@4edb737t9@0tl@00rau75y369z5hk0ot@23d2wicb90uwb54a9l3gw9lv3z51nv@@@@@@@amy81e3kh9yc90e59d@6528z42ic@7uv6bm58t@3av0w004t05aavs3oq3040irawj0ov1n90213h89yn0vs@0mcc284fv6uyaxp@3242ok39h0jd06905v1ia@7zc9659bk@ax30ua0um0652sa65daqd@00z03d2ra1f95751xu@9x10676yz@72w33r24b63d@2d7@ats6f678u@bcg9uf6h6@1b60us2d17ygbxn72106t02g@adublf05q@8xu5wobqb1tc1c73cs7pj@87k3cj2xq6258l379y@0q42qy3vs3y70r9@06v2a9@ast4su12w0ko4y77dn@7oubr07ju1ct5qe81v@0d52kb66t4zj@93508c@af30kj@299'.replace(/@\w*/g,v=>~-v.search((100+h.toString(36)).slice(-3))%3?++i:r=String.fromCharCode(i),i=32,r='@',n.replace(/\w/g,c=>h=parseInt(c,36)^(h*3)&16383,h=0))&&r monsters = { "Aleax": "A", "Angel": "A", "Arch Priest": "@", "Archon": "A", "Ashikaga Takauji": "@", "Asmodeus": "&", "Baalzebub": "&", "Chromatic Dragon": "D", "Croesus": "@", "Cyclops": "H", "Dark One": "@", "Death": "&", "Demogorgon": "&", "Dispater": "&", "Elvenking": "@", "Famine": "&", "Geryon": "&", "Grand Master": "@", "Green-elf": "@", "Grey-elf": "@", "Hippocrates": "@", "Ixoth": "D", "Juiblex": "&", "Keystone Kop": "K", "King Arthur": "@", "Kop Kaptain": "K", "Kop Lieutenant": "K", "Kop Sergeant": "K", "Lord Carnarvon": "@", "Lord Sato": "@", "Lord Surtur": "H", "Master Assassin": "@", "Master Kaen": "@", "Master of Thieves": "@", "Medusa": "@", "Minion of Huhetotl": "&", "Mordor orc": "o", "Nalzok": "&", "Nazgul": "W", "Neferet the Green": "@", "Norn": "@", "Olog-hai": "T", "Oracle": "@", "Orcus": "&", "Orion": "@", "Pelias": "@", "Pestilence": "&", "Scorpius": "s", "Shaman Karnov": "@", "Thoth Amon": "@", "Twoflower": "@", "Uruk-hai": "o", "Vlad the Impaler": "V", "Wizard of Yendor": "@", "Woodland-elf": "@", "Yeenoghu": "&", "abbot": "@", "acid blob": "b", "acolyte": "@", "air elemental": "E", "aligned priest": "@", "ape": "Y", "apprentice": "@", "arch-lich": "L", "archeologist": "@", "attendant": "@", "baby black dragon": "D", "baby blue dragon": "D", "baby crocodile": ":", "baby gray dragon": "D", "baby green dragon": "D", "baby long worm": "w", "baby orange dragon": "D", "baby purple worm": "w", "baby red dragon": "D", "baby silver dragon": "D", "baby white dragon": "D", "baby yellow dragon": "D", "balrog": "&", "baluchitherium": "q", "barbarian": "@", "barbed devil": "&", "barrow wight": "W", "bat": "B", "black dragon": "D", "black light": "y", "black naga hatchling": "N", "black naga": "N", "black pudding": "P", "black unicorn": "u", "blue dragon": "D", "blue jelly": "j", "bone devil": "&", "brown mold": "F", "brown pudding": "P", "bugbear": "h", "captain": "@", "carnivorous ape": "Y", "cave spider": "s", "caveman": "@", "cavewoman": "@", "centipede": "s", "chameleon": ":", "chickatrice": "c", "chieftain": "@", "clay golem": "'", "cobra": "S", "cockatrice": "c", "couatl": "A", "coyote": "d", "crocodile": ":", "demilich": "L", "dingo": "d", "disenchanter": "R", "djinni": "&", "dog": "d", "doppelganger": "@", "dust vortex": "v", "dwarf king": "h", "dwarf lord": "h", "dwarf mummy": "M", "dwarf zombie": "Z", "dwarf": "h", "earth elemental": "E", "electric eel": ";", "elf mummy": "M", "elf zombie": "Z", "elf": "@", "elf-lord": "@", "energy vortex": "v", "erinys": "&", "ettin mummy": "M", "ettin zombie": "Z", "ettin": "H", "fire ant": "a", "fire elemental": "E", "fire giant": "H", "fire vortex": "v", "flaming sphere": "e", "flesh golem": "'", "floating eye": "e", "fog cloud": "v", "forest centaur": "C", "fox": "d", "freezing sphere": "e", "frost giant": "H", "gargoyle": "g", "garter snake": "S", "gas spore": "e", "gecko": ":", "gelatinous cube": "b", "ghost": " ", "ghoul": "Z", "giant ant": "a", "giant bat": "B", "giant beetle": "a", "giant eel": ";", "giant mimic": "m", "giant mummy": "M", "giant rat": "r", "giant spider": "s", "giant zombie": "Z", "giant": "H", "glass golem": "'", "glass piercer": "p", "gnome king": "G", "gnome lord": "G", "gnome mummy": "M", "gnome zombie": "Z", "gnome": "G", "gnomish wizard": "G", "goblin": "o", "gold golem": "'", "golden naga hatchling": "N", "golden naga": "N", "gray dragon": "D", "gray ooze": "P", "gray unicorn": "u", "green dragon": "D", "green mold": "F", "green slime": "P", "gremlin": "g", "grid bug": "x", "guard": "@", "guardian naga hatchling": "N", "guardian naga": "N", "guide": "@", "healer": "@", "hell hound pup": "d", "hell hound": "d", "hezrou": "&", "high priest": "@", "hill giant": "H", "hill orc": "o", "hobbit": "h", "hobgoblin": "o", "homunculus": "i", "horned devil": "&", "horse": "u", "housecat": "f", "human mummy": "M", "human zombie": "Z", "human": "@", "hunter": "@", "ice devil": "&", "ice troll": "T", "ice vortex": "v", "iguana": ":", "imp": "i", "incubus": "&", "iron golem": "'", "iron piercer": "p", "jabberwock": "J", "jackal": "d", "jaguar": "f", "jellyfish": ";", "ki-rin": "A", "killer bee": "a", "kitten": "f", "knight": "@", "kobold lord": "k", "kobold mummy": "M", "kobold shaman": "k", "kobold zombie": "Z", "kobold": "k", "kraken": ";", "large cat": "f", "large dog": "d", "large kobold": "k", "large mimic": "m", "leather golem": "'", "lemure": "i", "leocrotta": "q", "leprechaun": "l", "lich": "L", "lichen": "F", "lieutenant": "@", "little dog": "d", "lizard": ":", "long worm": "w", "lurker above": "t", "lynx": "f", "mail daemon": "&", "manes": "i", "marilith": "&", "master lich": "L", "master mind flayer": "h", "mastodon": "q", "mind flayer": "h", "minotaur": "H", "monk": "@", "monkey": "Y", "mountain centaur": "C", "mountain nymph": "n", "mumak": "q", "nalfeshnee": "&", "neanderthal": "@", "newt": ":", "ninja": "@", "nurse": "@", "ochre jelly": "j", "ogre king": "O", "ogre lord": "O", "ogre": "O", "orange dragon": "D", "orc mummy": "M", "orc shaman": "o", "orc zombie": "Z", "orc": "o", "orc-captain": "o", "owlbear": "Y", "page": "@", "panther": "f", "paper golem": "'", "piranha": ";", "pit fiend": "&", "pit viper": "S", "plains centaur": "C", "pony": "u", "priest": "@", "priestess": "@", "prisoner": "@", "purple worm": "w", "pyrolisk": "c", "python": "S", "quantum mechanic": "Q", "quasit": "i", "queen bee": "a", "quivering blob": "b", "rabid rat": "r", "ranger": "@", "raven": "B", "red dragon": "D", "red mold": "F", "red naga hatchling": "N", "red naga": "N", "rock mole": "r", "rock piercer": "p", "rock troll": "T", "rogue": "@", "rope golem": "'", "roshi": "@", "rothe": "q", "rust monster": "R", "salamander": ":", "samurai": "@", "sandestin": "&", "sasquatch": "Y", "scorpion": "s", "sergeant": "@", "sewer rat": "r", "shade": " ", "shark": ";", "shocking sphere": "e", "shopkeeper": "@", "shrieker": "F", "silver dragon": "D", "skeleton": "Z", "small mimic": "m", "snake": "S", "soldier ant": "a", "soldier": "@", "spotted jelly": "j", "stalker": "E", "steam vortex": "v", "stone giant": "H", "stone golem": "'", "storm giant": "H", "straw golem": "'", "student": "@", "succubus": "&", "tengu": "i", "thug": "@", "tiger": "f", "titan": "H", "titanothere": "q", "tourist": "@", "trapper": "t", "troll": "T", "umber hulk": "U", "valkyrie": "@", "vampire bat": "B", "vampire lord": "V", "vampire": "V", "violet fungus": "F", "vrock": "&", "warg": "d", "warhorse": "u", "warrior": "@", "watch captain": "@", "watchman": "@", "water demon": "&", "water elemental": "E", "water moccasin": "S", "water nymph": "n", "water troll": "T", "werejackal": "d", "wererat": "r", "werewolf": "d", "white dragon": "D", "white unicorn": "u", "winged gargoyle": "g", "winter wolf cub": "d", "winter wolf": "d", "wizard": "@", "wolf": "d", "wood golem": "'", "wood nymph": "n", "woodchuck": "r", "wraith": "W", "wumpus": "q", "xan": "x", "xorn": "X", "yellow dragon": "D", "yellow light": "y", "yellow mold": "F", "yeti": "Y", "zruty": "z" } err = ok = 0 for(name in monsters) { code = monsters[name] result = F(name) if (result != code) console.log('ERROR',++err, name, result, code) else ++ok } console.log('Errors',err,'OK', ok) ``` [Answer] # Javascript, 1185 bytes ``` s=>{h=0;for(i of s)h=(h<<5)-h+i.charCodeAt()|0;for(v of "Aqgh201etxitsxy0_&ctpzfekt09j36uafamqw46mz1qcxvnnoego4212nxfivutt09qyac4td1ayiotfh3dvub5fggzjqa58h37bnva3dzy_D9wlywkgkifldlp6t46v97basg905f8wadwt0w49q0gk9c8edz9e33uj6esjl_Hkkt54kr0qdlxs6hxdxxyegrdzcmz8ymvg_Ki0enu0ct1shv_o193ve2y3tpa71xu3pud405o7_We09jfsayx_Tw2gk0spoqab5c9k_s7timco3yh674rp1_Vppq2k9t1q_b3mo3tac13_E0r50a7vi5a0kgim_Y2omnjbkq59mw5njf5t_Lu9z2bj6w2128_:n0gngsocqeuh5czhyiedwd3a_w9lf1hv1rra7r_qmckg7rbhlldbvros4f44h_B32t12yzdci83_yjkb3va_Nt2cbaqd46toc29anic1qq3es_P3mkmtv2l4j8r_ukjb44lwm5vkaz5hwkh_j3oo7uj9ip_Fzuk8mh1rpfw7obl6s9fsq_hzmwz3f7kdhiaj4enlxha1_c0q0yu8tnf_'nf7c1sks8rzgxhw83vjq0s76xhrvppbgn_Slr90h5su3zokncwi2m_doi5t2p4vw6dryycyhtl6eujb1ta26752ta7hr19d9vceq_Rqk8tsy_vuxwglitt4u25zfhj5q_M4j7tjk9cryvqn8101u5h646p_Ztzwr09t8ckxx3hbsl6r7dqv7qxmnwt_;u7r3e9trqqkmdj5tlx_apoj0ngpcqy6r7t8gw9_e2wtyw9oyve8uxlf_C8tpo3hlb3_gxji2n2nl4_ kwft9p_maxcdzat5e_rcy28c360mmndp8ksxh_pegqkkuur3_Gh6f8pheo0nn2_xu6yjdx_iz538jwkbwuh4ge7ymj_f3eytt6khltgxj13itedbz_Jlgk_knskybpe8n69a_llnv_tuxgkxc_nod5ob3cft_Oij0a222q3_Q6af_Uc5x_Xzjn_z6iq".split`_`)if(~v.slice(1).match(/.../g).indexOf(h.toString(36).slice(-3)))return v[0];return"@"} ``` Uses a golfed version of the Javascript string hash found [here.](http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/) The actual hash stored in the table (that long string) takes the absolute value of the hash produced by that method, converts it to base-36, and drops all but the three least significant digits. [Answer] # Python 3, ~~1915~~ 1900 bytes Changelog: * Work with and output ASCII code instead of the character itself (saved 15 bytes) Pass the monster name as first command line argument, receive the character on stdout. ``` import sys D=b'`"\x08\x04\x02&@Yx\xf6\x90a\x00Z\x00\x00c\x00X\x00\x00f\x00z\x00\x00hS\x12\x06\t@PSTft?z\x0fnK\nH\x87\xa2ig\t\t\x12 &;@FZkoq\x05\xfc~?\x1b\x80\xc2,z\r\xf3Y\x141\x9cS\x10\x80jU\x06\x08\t&;@BKpqr\x9f\xbe\xbb\xf9O\xcde\x03!kK\x11\x07\x07&:@WYsu\x1boDv\xc9i\x90lS$\x06\r@Sdirw\x1f\x1d\x198\xb3\xb2\x91\x0fm\xa5\x03A@mB#\x07\x07@GPWdiv\x7f;n\xb3Bk\xa5ng\x07\x0c\x16&@EHSVcdfqru\x01\xfen\x83q\xd8\xf3\x1c.\xe5\xac^\x87\t\xaaT\xd4D\x9c\xe1*Io;\x03\x05\x06@desu\x01\xf7\x95R0\x88pc \x08\n:@KMNknq\xfd\xfe\ru\xb2z\xea\\\x9b\x05qC\x08\x07\x06&@AGOfhy\xe2\xbbA\xf2ArS\x1e\x08\x08&@JVYdfi_\x1c\xd8/k\x89\xa8\xe0sw\x08\x0b\x1c&;@Kdfhijou\t\xe0[# \\\x9a\xd3F(L\xfapM\tp\xa8t\xccp\x8d\x11e+\x05\x0c\x8a\x08t+)\x04\x02@PQT\xf2\x94uG\x1c\x06\t&@Uilq\x0f\ryl\xc4`\xa5\x10\x90v\x85\r\x0e$&:@FKLNORSWYry\x9f\x97\xf8\xae\xb8\xdf\xdd\xc1\xcdl\xb2\xc9L|\xbb;\x92\xb8j\xb0\xa99\xdd\x9c\xb8\xd0\x8bh\x95\x88T\xb3;1\xb6\x0bwb\x06\x0c\x11&:;@DGHOVhkm\x02\xfe\x8fO{\xd9u\xac&\xd7\x90\x9fe\xc0\xf44GxW\x07\x07\x0bADHScdv?>\xdd<:\xb7s.\x8cI\x07yR\x07\x07\t&:@bcht;Zx\x16sO\x8d\xab\xc3ze\x0b\x08\x14&@ABCaqs\x01}\xbe=\x15\xc6\xcdL\xa1\xc8\x9e.\xf7\x02\xc1Xq4\x99\t{G\x16\x06\t@Faefg\x1f\x9bU$2P`\xa8\x80|G\x15\x06\x07&\';@Go\x1c1\\\xa7*\x0bS}s\x06\n" &@AHLYZdh\xf6\x1e\t\xb93N2\xc27\xd6\xd8\xd8*\xe5L\xa3\xa4f\x860A\xfa:7.\xdd\x9b)\xb80\x85\xc4\xb4\x83~W\x0e\x07\r&:@ERbd>\x1b\xda\x15\xd4\x92\x0eM\xacJH\x04c\x7fG\x00\x06\x08:@dghx\x1f\xbc\xf4Z\xa1%\xd3C' R=range N=sys.argv[1].lower() B=0 for c in N:B|=ord(c)&0x7f;B<<=7 B%=2**62-1 P=N.split() F=ord(P[-1][0])^(ord(P[-1][1])>>2) while D: f=D[0];ik,j,h,n=D[1:5];i=ik>>4;k=ik&15;D=D[5:];c=D[:h];m=D[h:h+n];m=int.from_bytes(m,"big");s=1;C=j;b=(h-1).bit_length() for x in R(i-1):s<<=k;s|=1 s<<=j;z=(B&s)>>j;x=0;u=1 for y in R(i):x<<=1;x|=bool(z&u);u<<=k if f!=F:D=D[h+n:];continue while m: if m&(2**i-1)==x:m>>=i;C=c[m&(2**b-1)];break m>>=b+i break print(C) ``` When I read the question, I thought "I need to compress this". The first step was to lowercase all names. Looking at the data, I felt that somehow using the first letter of the last word should do the trick as a rough first guess on which letters the monster might have. As it turns out, that was a powerful initial guess. The following table is "first character of last word", "number of hits", "monster characters": ``` 'd' (37) => & @ D L R d h 'g' (31) => & ' : @ G H Z g o 's' (30) => & : ; @ E F H K P S Y Z e k o s 'm' (28) => & @ F H M Q R S Y i m q r 'c' (24) => : @ A C H S b c d f s v 'p' (20) => & ; @ P S c d f p u 'w' (20) => @ G W d q r u w 'a' (19) => & @ A L Y a t 'h' (17) => & @ N U d f h i o u 'l' (17) => : @ F G K L O V f h i k l q y 'n' (15) => & : @ N W n 't' (14) => @ H T f i q t 'b' (14) => & @ B a b h q x 'k' (13) => ; @ A G K O f h k 'e' (12) => & ; @ E H e 'o' (12) => & @ O P T Y o 'z' ( 9) => Z z 'v' ( 9) => & @ S V v 'r' ( 8) => @ B q r 'j' ( 8) => & ; J d f j 'f' ( 6) => & F d h 'i' ( 5) => & : D V i 'u' ( 4) => o u 'y' ( 3) => & @ Y 'x' ( 2) => X x 'q' ( 1) => i ``` To further improve the spreadout, I modified the key slightly, by XOR-ing the second character of the last word, shifted to bits to the right, into the first character (let us call this construct `first_key`): ``` '}' (29) => & @ A H L Y Z d h 'v' (25) => & : @ F K L N O R S W Y r y 'x' (25) => A D H S c d v 's' (21) => & ; @ K d f h i j o u 'p' (21) => : @ K M N k n q 'z' (19) => & @ A B C a q s 'n' (19) => & @ E H S V c d f q r u '|' (18) => & ' ; @ G o 'l' (17) => @ S d i r w '~' (16) => & : @ E R b d '{' (15) => @ F a e f g 'w' (14) => & : ; @ D G H O V h k m 'i' (14) => & ; @ F Z k o q 'j' (13) => & ; @ B K p q r 'u' (12) => & @ U i l q 'm' (12) => @ G P W d i v '\x7f' (11) => : @ d g h x 'o' (11) => @ d e s u 'h' (11) => @ P S T f t 'y' (10) => & : @ b c h t 'r' ( 9) => & @ J V Y d f i 'k' ( 9) => & : @ W Y s u 'a' ( 8) => Z 'q' ( 7) => & @ A G O f h 't' ( 6) => @ P Q T '`' ( 4) => & @ Y x 'c' ( 1) => X 'f' ( 1) => z ``` As you can see, this gives us nine names which can uniquely mapped just with that information. Nice! Now I needed to find the remaining mapping. For this I started by converting the full (lower-cased) name to an integer: ``` def name_to_int(name): bits = 0 for c in name: bits |= ord(c) & 0x7f bits <<= 7 return bits ``` This is simply concatenating together the 7bit ASCII values of the names into a huge integer. We take this modulo `4611686018427387903` (2⁶²-1) for the next steps. Now I try to find a bitmask which yields an integer which in turn nicely distinguishes the different monster characters. The bit masks consist of evenly spread ones (such as `101010101` or `1000100010001`) and are parametrised by the number of bits (`i>=1`) and the spread (`k>=1`). In addition, the masks are left-shifted for up to `32*i` bits. Those are AND-ed with the integerised name and the resulting integer is used as a key in a mapping. The best (scored by `i*number_of_mapping_entries`) conflict-free mapping is used. The integers obtained from AND-ing the mask and the integerised name are shifted back by `j` bits and stripped of their zeroes (we store `i`, `k` and `j` along with the mapping to be able to reconstruct that), saving a lot of space. So now we have a two-level mapping: from `first_key` to the hashmap, and the hashmap maps the full name to the monster char uniquely. We need to store that somehow. Each entry of the top-level mapping looks like this: ``` Row = struct.Struct( ">" "B" # first word char "B" # number of bits (i) and bit spacing (k) "B" # shift (j) or character to map to if i = 0 "B" # number of monster characters "B" # map entry bytes ) ``` followed by the monster characters and the second level mapping. The second level mapping is serialised by packing it into a large integer and converting it to bytes. Each value and key is shifted consecutively into the integer, which makes the mapping reconstructible (the number of bits per key/value is inferrable from the number of characters and `i`, both stored in the row entry). If an entry has only a single possible monster character to map to, `i` is zero, number of characters and the mapping are also zero bytes. The character is stored where `j` would normally be stored. The full data is 651 bytes in size, serialised as python byte string its 1426 bytes. The decoding program essentially does it the other way round: first it extracts the `first_key` and searches in the data for the corresponding entry. Then it calculates the hash of the name and searches through the hashmap for the corresponding entry. ## Unobfuscated decoder ``` #!/usr/bin/python3 import sys import math data = b'`"\x08\x04\x02&@Yx\xf6\x90a\x00Z\x00\x00c\x00X\x00\x00f\x00z\x00\x00hS\x12\x06\t@PSTft?z\x0fnK\nH\x87\xa2ig\t\t\x12 &;@FZkoq\x05\xfc~?\x1b\x80\xc2,z\r\xf3Y\x141\x9cS\x10\x80jU\x06\x08\t&;@BKpqr\x9f\xbe\xbb\xf9O\xcde\x03!kK\x11\x07\x07&:@WYsu\x1boDv\xc9i\x90lS$\x06\r@Sdirw\x1f\x1d\x198\xb3\xb2\x91\x0fm\xa5\x03A@mB#\x07\x07@GPWdiv\x7f;n\xb3Bk\xa5ng\x07\x0c\x16&@EHSVcdfqru\x01\xfen\x83q\xd8\xf3\x1c.\xe5\xac^\x87\t\xaaT\xd4D\x9c\xe1*Io;\x03\x05\x06@desu\x01\xf7\x95R0\x88pc \x08\n:@KMNknq\xfd\xfe\ru\xb2z\xea\\\x9b\x05qC\x08\x07\x06&@AGOfhy\xe2\xbbA\xf2ArS\x1e\x08\x08&@JVYdfi_\x1c\xd8/k\x89\xa8\xe0sw\x08\x0b\x1c&;@Kdfhijou\t\xe0[# \\\x9a\xd3F(L\xfapM\tp\xa8t\xccp\x8d\x11e+\x05\x0c\x8a\x08t+)\x04\x02@PQT\xf2\x94uG\x1c\x06\t&@Uilq\x0f\ryl\xc4`\xa5\x10\x90v\x85\r\x0e$&:@FKLNORSWYry\x9f\x97\xf8\xae\xb8\xdf\xdd\xc1\xcdl\xb2\xc9L|\xbb;\x92\xb8j\xb0\xa99\xdd\x9c\xb8\xd0\x8bh\x95\x88T\xb3;1\xb6\x0bwb\x06\x0c\x11&:;@DGHOVhkm\x02\xfe\x8fO{\xd9u\xac&\xd7\x90\x9fe\xc0\xf44GxW\x07\x07\x0bADHScdv?>\xdd<:\xb7s.\x8cI\x07yR\x07\x07\t&:@bcht;Zx\x16sO\x8d\xab\xc3ze\x0b\x08\x14&@ABCaqs\x01}\xbe=\x15\xc6\xcdL\xa1\xc8\x9e.\xf7\x02\xc1Xq4\x99\t{G\x16\x06\t@Faefg\x1f\x9bU$2P`\xa8\x80|G\x15\x06\x07&\';@Go\x1c1\\\xa7*\x0bS}s\x06\n" &@AHLYZdh\xf6\x1e\t\xb93N2\xc27\xd6\xd8\xd8*\xe5L\xa3\xa4f\x860A\xfa:7.\xdd\x9b)\xb80\x85\xc4\xb4\x83~W\x0e\x07\r&:@ERbd>\x1b\xda\x15\xd4\x92\x0eM\xacJH\x04c\x7fG\x00\x06\x08:@dghx\x1f\xbc\xf4Z\xa1%\xd3C' def name_to_int(name): bits = 0 for c in name: bits |= ord(c) & 0x7f bits <<= 7 return bits def make_mask(nbits, k): mask = 1 for i in range(nbits-1): mask <<= k mask |= 1 return mask def collapse_mask(value, nbits, k): bits = 0 shift = 0 for i in range(nbits): bits <<= 1 bits |= bool(value & (1<<shift)) shift += k return bits name = sys.argv[1].casefold() last_word = name.split()[-1] last_word_char = chr(ord(last_word[0]) ^ (ord(last_word[1]) >> 2)) while data: first_char = chr(data[0]) ik, j, nchars, nbytes = data[1:5] i = ik >> 4 k = ik & 15 data = data[5:] if first_char != last_word_char: # skip this entry data = data[nchars+nbytes:] continue chars, mapping = data[:nchars], data[nchars:nchars+nbytes] result = j if i == 0: break mapping = int.from_bytes(mapping, "big") name_bits = name_to_int(name) % (2**62-1) mask = make_mask(i, k) << j key = collapse_mask((name_bits & mask) >> j, i, k) bits_per_key = i key_mask = 2**(bits_per_key)-1 bits_per_value = math.ceil(math.log(len(chars), 2)) value_mask = 2**(bits_per_value)-1 while mapping: if mapping & key_mask == key: mapping >>= bits_per_key result = chars[mapping & value_mask] break mapping >>= bits_per_value+bits_per_key break print(chr(result)) ``` ## Analysis tool This is the tool I made and used to generate the data -- read at your own risk: ``` #!/usr/bin/python3 import base64 import collections import math import json import struct import zlib data = json.load(open("data.json")) reverse_pseudomap = {} forward_pseudomap = {} forward_info = {} reverse_fullmap = {} hits = collections.Counter() monster_char_hitmap = collections.Counter() for name, char in data.items(): name = name.casefold() parts = name.split() monster_char_hitmap[char] += 1 # if len(parts) > 1: # key = first_char + parts[0][0] # else: # key = first_char + last_part[1] key = chr(ord(parts[-1][0]) ^ (ord(parts[-1][1]) >> 2)) # key = parts[-1][0] hits[key] += 1 reverse_pseudomap.setdefault(char, set()).add(key) forward_pseudomap.setdefault(key, set()).add(char) forward_info.setdefault(key, {})[name] = char reverse_fullmap.setdefault(char, set()).add(name) for char, hit_count in sorted(hits.items(), key=lambda x: x[1], reverse=True): monsters = forward_pseudomap[char] print(" {!r} ({:2d}) => {}".format( char, hit_count, " ".join(sorted(monsters)) )) def make_mask(nbits, k): mask = 1 for i in range(nbits-1): mask <<= k mask |= 1 return mask def collapse_mask(value, nbits, k): bits = 0 shift = 0 for i in range(nbits): bits <<= 1 bits |= bool(value & (1<<shift)) shift += k return bits def expand_mask(value, nbits, k): bits = 0 for i in range(nbits): bits <<= k bits |= value & 1 value >>= 1 return bits assert collapse_mask(expand_mask(0b110110, 6, 3), 6, 3) assert expand_mask(collapse_mask(0b1010101, 7, 3), 7, 3) def name_to_int(name): # mapped_name = "".join({"-": "3", " ": "4"}.get(c, c) for c in name) # if len(mapped_name) % 8 != 0: # if len(mapped_name) % 2 == 0: # mapped_name += "7" # mapped_name = mapped_name + "="*(8 - (len(mapped_name) % 8)) # print(mapped_name) # return base64.b32decode( # mapped_name, # casefold=True, # ) bits = 0 for c in name: bits |= ord(c) & 0x7f bits <<= 7 return bits compressed_maps = {} max_bit_size = 0 nmapentries = 0 for first_char, monsters in sorted(forward_info.items()): monster_chars = forward_pseudomap[first_char] print("trying to find classifier for {!r}".format(first_char)) print(" {} monsters with {} symbols".format( len(monsters), len(monster_chars)) ) bits = math.log(len(monster_chars), 2) print(" {:.2f} bits of clever entropy needed".format( bits )) bits = math.ceil(bits) int_monsters = { name_to_int(name): char for name, char in monsters.items() } reverse_map = {} for name, char in int_monsters.items(): reverse_map.setdefault(char, set()).add(name) solution = None solution_score = float("inf") if bits == 0: char = ord(list(int_monsters.values())[0][0]) solution = 0, 0, char, {} for i in range(bits, 3*bits+1): print(" trying to find solution with {} bits".format(i)) for k in [2, 3, 5, 7, 11]: mask = make_mask(i, k) for j in range(0, 32*bits): bucketed = {} for int_name, char in int_monsters.items(): bucket = (int_name % (2**62-1)) & mask try: if bucketed[bucket] != char: break except KeyError: bucketed[bucket] = char else: new_solution_score = i*len(bucketed) if new_solution_score < solution_score: print(" found mapping: i={}, k={}, j={}, mapping={}".format( i, k, j, bucketed )) solution = i, k, j, bucketed solution_score = new_solution_score mask <<= 1 if solution is not None: print(" solution found!") chars = "".join(sorted(set(int_monsters.values()))) i, k, j, mapping = solution # sanity check 1 if i > 0: mask = make_mask(i, k) << j for int_name, char in int_monsters.items(): key = (int_name % (2**62-1)) & mask assert mapping[key] == char compressed_mapping = {} for hash_key, char in mapping.items(): hash_key = collapse_mask(hash_key >> j, i, k) max_bit_size = max(hash_key.bit_length(), max_bit_size) compressed_mapping[hash_key] = chars.index(char) nmapentries += len(compressed_mapping) compressed_maps[first_char] = i, k, j, chars, compressed_mapping print(" ", compressed_maps[first_char]) print() print("max_bit_size =", max_bit_size) print("nmapentries =", nmapentries) print("approx size =", (1+math.ceil(max_bit_size/8))*nmapentries) # first we need to map first word chars to compressed mappings Row = struct.Struct( ">" "B" # first word char "B" # number of bits (i) and bit spacing (k) "B" # shift (j) or character to map to if i = 0 "B" # number of characters "B" # map entry bytes ) def map_to_bytes(i, nchars, mapping): bits_per_value = math.ceil(math.log(nchars, 2)) bits_per_key = i bits = 0 # ensure that the smallest value is encoded last for key, value in sorted(mapping.items(), reverse=True): assert key.bit_length() <= bits_per_key assert value.bit_length() <= bits_per_value bits <<= bits_per_value bits |= value bits <<= bits_per_key bits |= key return bits.to_bytes(math.ceil(bits.bit_length() / 8), "big") def bytes_to_map(i, nchars, data): data = int.from_bytes(data, "big") bits_per_value = math.ceil(math.log(nchars, 2)) bits_per_key = i key_mask = 2**(bits_per_key)-1 value_mask = 2**(bits_per_value)-1 mapping = {} while data: key = data & key_mask data >>= bits_per_key value = data & value_mask data >>= bits_per_value assert key not in mapping mapping[key] = value return mapping parts = bytearray() for first_char, (i, k, j, chars, mapping) in sorted(compressed_maps.items()): raw_data = map_to_bytes(i, len(chars), mapping) recovered_mapping = bytes_to_map(i, len(chars), raw_data) assert recovered_mapping == mapping, "{}\n{}\n{}\n{} {}".format( mapping, recovered_mapping, raw_data, i, len(chars), ) assert len(raw_data) <= 255 print(" {!r} => {} {} {} {} {}".format( first_char, i, k, j, len(chars), raw_data )) assert k <= 15 assert i <= 15 if i == 0: chars = "" row = Row.pack( ord(first_char), (i << 4) | k, j, len(chars), len(raw_data), ) row += chars.encode("ascii") row += raw_data parts.extend(row) parts = bytes(parts) print(parts) print(len(parts)) print(len(str(parts))) print(len(str(zlib.compress(parts, 9)))) ``` ## Test driver ``` #!/usr/bin/python3 import json import subprocess import sys with open("data.json") as f: data = json.load(f) for name, char in data.items(): stdout = subprocess.check_output(["python3", sys.argv[1], name]) stdout = stdout.decode().rstrip("\n") if char != stdout: print("mismatch for {!r}: {!r} != {!r}".format( name, char, stdout )) ``` [Answer] ## awk 73 + 2060 bytes ``` s{while(!(i=index(s,$0)))sub(/.$/,"");print substr(s,i+length(),1)}{s=$0} ``` The data was prepared to this: ``` "Aleax": "A", Al A # first of alphabet truncate to len=1 "Angel": "A", An A "Arch Priest": "@", Arch @ # this needs to come "Archon": "A", Archo A # before this "Ashikaga Takauji": "@", Ash @ "Asmodeus": "&", Asm & ``` (2060 chars) ie. to shortest unique string with the monster character appended to the name and finally to this form: ``` AlAAnAArch@ArchoAAsh@Asm& ``` (there needs to be a fall back char in the beginning of the string to mark a non-match) When searching for a match the name is shortened char by char from the end until there is a match and the next char after match is returned: ``` $ cat monster Aleax $ awk -f program.awk monsters_string monster A ``` I can still shave off a few bytes from the monsters string with some organizing: ``` AAnArch@ArchoAsh@Asm& ``` Considering the size of the data with monsters names starting with `A` would reduce from 38 bytes to 22 means dropping data size from 2060 to 1193 on the average. this is still **work in progress** and the monster string will be published a bit later. ]
[Question] [ The so-called [Will Rogers phenomenon](https://en.wikipedia.org/wiki/Will_Rogers_phenomenon) describes a way to tweak statistics by raising the average in two (multi)sets when one element is moved between the two sets. As a simple example, consider the two sets ``` A = {1, 2, 3} B = {4, 5, 6} ``` Their arithmetic means are `2` and `5`, respectively. If we move the `4` to `A`: ``` A = {1, 2, 3, 4} B = {5, 6} ``` Now the averages are `2.5` and `5.5`, respectively, so both averages have been raised through a simple regrouping. As another example, consider ``` A = {3, 4, 5, 6} --> A = {3, 5, 6} B = {2, 3, 4, 5} --> B = {2, 3, 4, 4, 5} ``` On the other hand, it's not possible to raise both averages for the sets ``` A = {1, 5, 9} B = {4, 5, 7, 8} ``` ## The Challenge Given two lists of non-negative integers, determine whether it is possible to raise both averages by moving a single integer from one list to the other. The average of an empty list is not defined, so if one of the lists contains only one element, this element cannot be moved. You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter. Input may be taken in any convenient string or list format. You must not assume that the elements in each list are unique, nor that they are sorted. You may assume that both lists contain at least one element. Output should be [truthy](http://meta.codegolf.stackexchange.com/a/2194/8478) if both averages can be raised by moving a single integer and [falsy](http://meta.codegolf.stackexchange.com/a/2194/8478) otherwise. This is code golf, so the shortest answer (in bytes) wins. ## Test Cases Truthy: ``` [1], [2, 3] [1, 2, 3], [4, 5, 6] [3, 4, 5, 6], [2, 3, 4, 5] [6, 5, 9, 5, 6, 0], [6, 2, 0, 9, 5, 2] [0, 4], [9, 1, 0, 2, 8, 0, 5, 5, 4, 9] ``` Falsy: ``` [1], [2] [2, 4], [5] [1, 5], [2, 3, 4, 5] [2, 1, 2, 3, 1, 3], [5, 1, 6] [4, 4, 5, 2, 4, 0], [9, 2, 10, 1, 9, 0] ``` ## 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 ``` ``` <script>site = 'meta.codegolf'; postID = 5314; isAnswer = true; QUESTION_ID = 53913</script><script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script><script>jQuery(function(){var u='https://api.stackexchange.com/2.2/';if(isAnswer)u+='answers/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJeRCD';else u+='questions/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJO6t)';jQuery.get(u,function(b){function d(s){return jQuery('<textarea>').html(s).text()};function r(l){return new RegExp('<pre class="snippet-code-'+l+'\\b[^>]*><code>([\\s\\S]*?)</code></pre>')};b=b.items[0].body;var j=r('js').exec(b),c=r('css').exec(b),h=r('html').exec(b);if(c!==null)jQuery('head').append(jQuery('<style>').text(d(c[1])));if (h!==null)jQuery('body').append(d(h[1]));if(j!==null)jQuery('body').append(jQuery('<script>').text(d(j[1])))})})</script> ``` [Answer] # Pyth, ~~29~~ ~~28~~ ~~26~~ 24 bytes *Thanks to @Jakube for saving me 3 bytes with `.p` and `L`.* Very simple, checks if any elements in list 2 are greater than mean of list 1 and less than mean of list 2, then repeats with list 1 and list 2 switched. ``` Lcsblbff&>YyhT<YyeTeT.pQ ``` Prints an a non-empty list for truthy, and `[]` for falsey. ``` L Define y(b). Pyth has no builtin for mean c Float div sb Sum of b lb Length of b f .pQ Filter all permutations of input f eT Filter the last element of the filter var & Logical and >Y Inner filter var greater than y Call the mean function we defined earlier hT First element of outer filter var <Y Inner filter var less than y Mean of eT Last element of outer filternvar ``` [Try it online here](http://pyth.herokuapp.com/?code=Lcsblbff%26%3EYyhT%3CYyeTeT.pQ&input=%5B1%2C+2%2C+3%5D%2C+%5B4%2C+5%2C+6%5D&debug=1). [Test Suite.](http://pyth.herokuapp.com/?code=V.QLcsblbff%26%3EYyhT%3CYyeTeT.pN&input=%5B1%5D%2C+%5B2%2C+3%5D%0A%5B1%2C+2%2C+3%5D%2C+%5B4%2C+5%2C+6%5D%0A%5B3%2C+4%2C+5%2C+6%5D%2C+%5B2%2C+3%2C+4%2C+5%5D%0A%5B6%2C+5%2C+9%2C+5%2C+6%2C+0%5D%2C+%5B6%2C+2%2C+0%2C+9%2C+5%2C+2%5D%0A%5B0%2C+4%5D%2C+%5B9%2C+1%2C+0%2C+2%2C+8%2C+0%2C+5%2C+5%2C+4%2C+9%5D%0A%5B1%5D%2C+%5B2%5D%0A%5B2%2C+4%5D%2C+%5B5%5D%0A%5B1%2C+5%5D%2C+%5B2%2C+3%2C+4%2C+5%5D%0A%5B2%2C+1%2C+2%2C+3%2C+1%2C+3%5D%2C+%5B5%2C+1%2C+6%5D%0A%5B4%2C+4%2C+5%2C+2%2C+4%2C+0%5D%2C+%5B9%2C+2%2C+10%2C+1%2C+9%2C+0%5D&debug=1) [Answer] ## Python 3, 74 ``` lambda*L:any(sum(C)/len(C)>x>sum(D)/len(D)for(C,D)in[L,L[::-1]]for x in C) ``` Takes two lists as input. Checks if the first list has an element that's bigger than it's average but smaller than the other one's. Then, does the same for the two inputs swapped. Having a two-layer list comprehension was shorter than defining a separate function to try the two orders (82): ``` f=lambda A,B:any(sum(A)/len(A)>x>sum(B)/len(B)for x in A) lambda A,B:f(A,B)|f(B,A) ``` [Answer] # Haskell, ~~58~~ 57 ``` x%y=any(\n->(\g->g x<0&&g y>0)$sum.map(n-))x x?y=x%y||y%x ``` we can check if we enlarge or lower the average by checking whether the element to remove or include is bigger or smaller than the average. we can check that by checking if the average is smaller or bigger than an element by removing that element from the array, and checking whether the new array's average is negative or positive, which in turn is just as checking whether the sum is positive or negative. checking that is put very simply as `sum.map(-n+)`. [Answer] # Mathematica, ~~49~~ 47 bytes ``` m=Mean;MemberQ[#2,x_/;m@#<x<m@#2]&@@#~SortBy~m& ``` Evaluates to a pure function that expects input in the form `{list1, list2}`. [Answer] # APL, ~~45~~ 40 bytes Saved 5 bytes thanks to Moris Zucca! ``` {U←∊⍺⍵[⊃⍒M←(+/÷≢)¨⍺⍵]⋄1∊(U<⌈/M)∧(U>⌊/M)} ``` This creates an unnamed dyadic function that accepts arrays on the left and right and returns 1 or 0. ``` { M←(+/÷≢)¨⍺⍵ ⍝ Compute the mean of each array U←∊⍺⍵[⊃⍒M] ⍝ Get the array with the larger mean 1∊(U<⌈/M)∧(U>⌊/M) ⍝ Any smaller mean < U < larger mean } ``` You can [try it online](http://tryapl.org/?a=6%205%209%205%206%200%7BU%u2190%u220A%u237A%u2375%5B%u2283%u2352M%u2190%28+/%F7%u2262%29%A8%u237A%u2375%5D%u22C41%u220A%28U%3C%u2308/M%29%u2227%28U%3E%u230A/M%29%7D6%202%200%209%205%202&run). [Answer] # R, ~~66~~ 52 Bytes As an unnamed function, that accepts 2 vectors. Got rid of some spurious whichs. ``` function(a,b)any(a<(m=mean)(a)&a>m(b),b<m(b)&b>m(a)) ``` Tests ``` > f= + function(a,b)any(a<(m=mean)(a)&a>m(b),b<m(b)&b>m(a)) > f(c(1), c(2, 3)) [1] TRUE > f(c(1, 2, 3), c(4, 5, 6)) [1] TRUE > f(c(3, 4, 5, 6), c(2, 3, 4, 5)) [1] TRUE > f(c(6, 5, 9, 5, 6, 0), c(6, 2, 0, 9, 5, 2)) [1] TRUE > f(c(0, 4), c(9, 1, 0, 2, 8, 0, 5, 5, 4, 9)) [1] TRUE > > f(c(1), c(2)) [1] FALSE > f(c(2, 4), c(5)) [1] FALSE > f(c(1, 5), c(2, 3, 4, 5)) [1] FALSE > f(c(2, 1, 2, 3, 1, 3), c(5, 1, 6)) [1] FALSE > f(c(4, 4, 5, 2, 4, 0), c(9, 2, 10, 1, 9, 0)) [1] FALSE > ``` [Answer] ## SAS/IML, 67 ``` start m(a,b);return((a>b[:]&&a<a[:])||(b>a[:]&&b<b[:]))[<>];finish; ``` It uses subscript reduction operators to get the answer, returning 0 if no element is found that matches the requirements or 1 if one is found. Non-golfed, here I return the actual value itself using matrix multiplication: ``` proc iml; b={1 2 3 4 5 6 7 8 9 }; a={2 3 4 5 6}; start m(a,b); return (a#(a>b[:] && a < a[:]) || b#(b>a[:] && b < b[:]))[<>]; finish; z= m(a,b); print z; quit; ``` Tests: ``` %macro test(a,b,n); z&n=m({&a},{&b}); print z&n; %mend test; proc iml; b={1 2 3 4 5 }; a={2 3 4 5 6 7}; start m(a,b);return((a>b[:]&&a<a[:])||(b>a[:]&&b<b[:]))[<>];finish; * True; %test(1,2 3,1); %test(1 2 3,4 5 6,2); %test(3 4 5 6, 2 3 4 5,3); %test(6 5 9 5 6 0,6 2 0 9 5 2,4); %test(0 4, 9 1 0 2 8 0 5 5 4 9,5); * False; %test(1,2,6); %test(2 4, 5,7); %test(1 5, 2 3 4 5,8); %test(2 1 2 3 1 3, 5 1 6,9); %test(4 4 5 2 4 0, 9 2 10 1 9 0,10); quit; ``` (Condensed for readability) > > z1 1 > > > z2 1 > > > z3 1 > > > z4 1 > > > z5 1 > > > z6 0 > > > z7 0 > > > z8 0 > > > z9 0 > > > z10 0 > > > [Answer] # Python 2.7, ~~102~~ ~~98~~ 96 ``` lambda p:any([1for i in 0,1for e in p[i]if g[i^1]<e<g[i]]for g in[[sum(l)*1./len(l)for l in p]]) ``` Takes the input as array of the 2 inputs and returns boolean. The logic is -find the avg of the 2 lists, then find an element such that it's less than the avg of its own list and but greater than the average of the other list. [Testing it for the given inputs is demo-ed here](http://ideone.com/OXvXae) [Answer] # CJam, 28 bytes ``` {{_:+1$,d/\+}%$~(m],@0=i)>&} ``` This is an anonymous function that pops a two-dimensional array from the stack and leaves an array of movable elements in return. In supported browsers, you can verify all test cases at once in the [CJam interpreter](http://cjam.aditsu.net/#code=q~%5D%7B%7B_%3A%2B1%24%2Cd%2F%5C%2B%7D%25%24~(m%5D%2C%400%3Di)%3E%26%7D%25%3Ap&input=%5B%5B1%5D%20%5B2%203%5D%5D%0A%5B%5B1%202%203%5D%20%5B4%205%206%5D%5D%0A%5B%5B3%204%205%206%5D%20%5B2%203%204%205%5D%5D%0A%5B%5B6%205%209%205%206%200%5D%20%5B6%202%200%209%205%202%5D%5D%0A%5B%5B0%204%5D%20%5B9%201%200%202%208%200%205%205%204%209%5D%5D%0A%5B%5B1%5D%20%5B2%5D%5D%0A%5B%5B2%204%5D%20%5B5%5D%5D%0A%5B%5B1%205%5D%20%5B2%203%204%205%5D%5D%0A%5B%5B2%201%202%203%201%203%5D%20%5B5%201%206%5D%5D%0A%5B%5B4%204%205%202%204%200%5D%20%5B9%202%2010%201%209%200%5D%5D). ### Test cases **Code** ``` q~]{{_:+1$,d/\+}%$~(m],@0=i)>&}%:p ``` **Input** ``` [[1] [2 3]] [[1 2 3] [4 5 6]] [[3 4 5 6] [2 3 4 5]] [[6 5 9 5 6 0] [6 2 0 9 5 2]] [[0 4] [9 1 0 2 8 0 5 5 4 9]] [[1] [2]] [[2 4] [5]] [[1 5] [2 3 4 5]] [[2 1 2 3 1 3] [5 1 6]] [[4 4 5 2 4 0] [9 2 10 1 9 0]] ``` **Output** ``` [2] [4] [4] [5] [4] "" "" "" "" "" ``` ### How it works If A and B are the arrays and **avg(A) ≤ avg(B)** we simply check if **B ∩ {⌊avg(A)⌋+1, …, ⌈avg(B)⌉-1}** is non-empty. Any element in this intersection could be moved from **B** to **A** to increase both averages. ``` { }% e# For each of the arrays: _:+ e# Compute the sum of its elements. 1$, e# Compute its length. d/ e# Cast to Double and perform division. \+ e# Prepend the computed average to the array. $ e# Sort the arrays (by the averages). ~ e# Dump both arrays on the stack. ( e# Shift out the higher average. m] e# Round up to the nearest integer b. , e# Push [0 ... b-1]. @0= e# Replace the array with lower average by its average. i) e# Round down to the nearest integer a and add 1. > e# Skip the first a integer of the range. e# This pushes [a+1 ... b-1]. & e# Intersect the result with the remaining array. ``` This pushes the array of all elements of the array with higher average that can be moved to increase both averages. This array is empty/falsy if and only if no elements can be moved to achieve this result. [Answer] # Ruby, 86 ``` A=->x{x.reduce(0.0,:+)/x.size} F=->q{b,a=q.sort_by{|x|A[x]};a.any?{|x|x<A[a]&&x>A[b]}} ``` Takes as input an array containing the two arrays. Tries to find a sub average item from the group with the higher average that is greater than the average of the other group. Test: <http://ideone.com/444W4U> [Answer] ## Matlab, 54 Using an anonymous function: ``` f=@(A,B)any([B>mean(A)&B<mean(B) A>mean(B)&A<mean(A)]) ``` Examples: ``` >> f=@(A,B)any([B>mean(A)&B<mean(B) A>mean(B)&A<mean(A)]) f = @(A,B)any([B>mean(A)&B<mean(B),A>mean(B)&A<mean(A)]) >> f([1 2 3],[4 5 6]) ans = 1 >> f([3 4 5 6],[2 3 4 5]) ans = 1 >> f([1 5 9],[4 5 7 8]) ans = 0 ``` [Answer] ## C#, 104 ``` bool f(int[]a,int[]b){double i=a.Average(),j=b.Average();return a.Any(x=>x<i&&x>j)||b.Any(x=>x<j&&x>i);} ``` Example Calls: ``` f(new []{1,2,3}, new []{4,5,6}) f(new []{1}, new []{2, 3}) f(new []{1, 2, 3}, new []{4, 5, 6}) f(new []{3, 4, 5, 6}, new []{2, 3, 4, 5}) f(new []{6, 5, 9, 5, 6, 0}, new []{6, 2, 0, 9, 5, 2}) f(new []{0, 4}, new []{9, 1, 0, 2, 8, 0, 5, 5, 4, 9}) f(new []{1}, new []{2}) f(new []{2, 4}, new []{5}) f(new []{1, 5}, new []{2, 3, 4, 5}) f(new []{2, 1, 2, 3, 1, 3}, new []{5, 1, 6}) f(new []{4, 4, 5, 2, 4, 0}, new []{9, 2, 10, 1, 9, 0}) ``` [Answer] # C++14, 157 bytes As unnamed lambda, returns by the last parameter `r`. Assumes `A`,`B` to be containers like `vector<int>` or `array<int,>`. ``` [](auto A,auto B,int&r){auto m=[](auto C){auto s=0.;for(auto x:C)s+=x;return s/C.size();};r=0;for(auto x:A)r+=x<m(A)&&x>m(B);for(auto x:B)r+=x<m(B)&&x>m(A);} ``` Ungolfed: ``` auto f= [](auto A,auto B,int&r){ auto m=[](auto C){ auto s=0.; for(auto x:C) s+=x; return s/C.size(); }; r=0; for (auto x:A) r+=x<m(A)&&x>m(B); for (auto x:B) r+=x<m(B)&&x>m(A); } ; ``` Usage: ``` int main() { std::vector<int> a={1,2,3}, b={4,5,6}; // a={1,5,9}, b={4,5,7,8}; int r; f(a,b,r); std::cout << r << std::endl; } ``` ]
[Question] [ # Goal [Morse code](https://en.wikipedia.org/wiki/Morse_code) is often represented as sound. Given a stream of bits that represent whether sound is on or off, translate the stream into letters and numbers and spaces. [![International Morse Code](https://i.stack.imgur.com/UFJqy.png)](https://i.stack.imgur.com/UFJqy.png) # Specifics * The bit stream is analysed based on the length of repeating ON/OFF bits. + 1 ON bit is a dot + 3 ON bits are a dash + 1 OFF bit delimits dots and dashes + 3 OFF bits delimits characters + 7 OFF bits delimits words (space) * The input may be a string or array. Only two unique characters/values of your choice are allowed in the input. (eg. 0/1, true/false, comma/space) * The output returns a string or is printed to the standard output. # Example ``` Input: 101010100010001011101010001011101010001110111011100000001011101110001110111011100010111010001011101010001110101 Analysis: \--H--/ E \---L---/ \---L---/ \----O----/\-- --/\---W---/ \----O----/ \--R--/ \---L---/ \--D--/ Output: HELLO WORLD ``` # Assumptions * The stream always starts and ends with an ON bit. * There is no leading or trailing whitespace. * The input is always valid. * All letters (case-insensitive) and digits are supported. # Test Cases ``` 101010100010001011101010001011101010001110111011100000001011101110001110111011100010111010001011101010001110101 HELLO WORLD 10100000001011100011101110000000101110000000101011101000101000101010001010101 I AM A FISH 1010111011101110001110111011101110111000101110111011101110001110111010101 2017 101010001110111011100010101 SOS ``` # Scoring This is code golf. The lowest byte-count code by this time next week wins. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~65~~ ~~62~~ ~~60~~ 57 bytes -3 thanks to ngn. Tacit prefix function. ``` ⎕CY'dfns' morse'/|[-.]+'⎕S'&'∘(⊃∘'/. -'¨6|'1+|(00)+'⎕S 1) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO96FHbhMy8zBIuEONR31RPfyBt8B/Ico5UT0nLK1bnSgOK5OYXFaeq69dE6@rFaqsDZYPV1dQfdczQeNTVDKTU9fUUdNUPrTCrUTfUrtEwMNCEKFIw1ARZwgWy4b8CGKQpqBsaQKABFBsaIvhIbENDOIYAZD6qLEwfFhMMDNW5UGxGNssAqw1wNrKpMBE4jW4umosMDTGwgQFWMUOEmzHMxOZToCoA "APL (Dyalog Unicode) – Try It Online") Header, `f←`, and Footer are just to allow calling the function from Input while retaining TIO's byte count. In a normal APL session (corresponding to TIO's Input field), [it would not be needed](https://tio.run/##SyzI0U2pTMzJT////1HfVE//R20TDMBM50j1lLS8YnUujdz8ouJUdf2aaF29WG11oFSwupr6o44ZGo@6moGUur6egq76oRVmNeqG2jUaBgaaEEUKhpqa6oYGEGgAxYaGCD4S29AQjiEAmY8qC9OHxQQDQ3UA "APL (Dyalog Unicode) – Try It Online"). `⎕CY'dfns'` **c**op**y** the *dfns* workspace (library) `(`…`)` apply this tacit function:  `'1+|(00)+'⎕S 1` PCRE **S**earch 1-runs and even-length 0-runs and return matches' lengths  `6|` division remainder when divided by 6  `⊃∘'/. -'¨` for each match length, pick the corresponding character from this string `'/|[-.]+'⎕S'&'∘` PCRE **S**earch slashes and dash/dot-runs and return those `morse` translate from Morse code to regular text [Answer] # [Python 2](https://docs.python.org/2/), ~~142~~ 135 bytes ``` lambda s:''.join(' E-T----Z-Q---RSWU--2FH-V980NIMA--1CBYX-6--GDOK534PLJ-7'[int('0'+l.replace('111','3'),16)%57]for l in s.split('000')) ``` [Try it online!](https://tio.run/##bY9Lb8IwDMfvfIpckBuBK5v3kDgw2AZ78Rqwse1QGNU6hbZqufDpuyCgFFpHTmwn/58df7f99dxSZLe@ImVtlj@WCJsA5p/nuAaIO3xDbQsc6X08mU8RS/c9nN006LX/0kbkzu3HO9YQH7qDp2q5Mnx@xDp8Ou7WAIKCMoO1r6zV2gBmhiKUQRa5JvPV@rftBUIJxxWhGfrK2QuIQMrID7Rc2FpCh0VH14g4T8TMsR8smV/ennQZBGKQuYvWSRhltojjJPZUic8U@Gom5pQTZdb4PHUamvXZ/bPoHw "Python 2 – Try It Online") **Explanation:** Splits the string into letters on `000` (`0` thus means space) Replaces each `111` with `3`, and converts into base 16. Then each number is modded by `57`, which gives a range of `0..54`, which is the index of the current character. --- Previous version that converted to base 3: # [Python 2](https://docs.python.org/2/), ~~273~~ ~~252~~ 247 bytes ``` lambda s:''.join(chr(dict(zip([0,242,161,134,125,122,121,202,229,238,241]+[2]*7+[5,67,70,22,1,43,25,40,4,53,23,49,8,7,26,52,77,16,13,2,14,41,17,68,71,76],[32]+range(48,91)))[int('0'+l.replace('111','2').replace('0',''),3)])for l in s.split('000')) ``` [Try it online!](https://tio.run/##bY/bboMwDIbv9xTcJRm/KtsEUibtSRgXrIeViQGivdlenrnqSulKIis@/Z@d/vt06FoZ969vY1N9vW@r6PhizOqzq1u7OQx2W29O9qfubUEQL@CMwYkHS6qmsTCEBCI5JFlrD5dxIeVziIsUWUBQnbbBJ1CJJ3ik6ibwOdYIkAypIAQlKxja6uF1RkCmZUbIShSJlPFQtR8769fI2TlX1O3JGjJxsxp2fVNtdtYws4ER424p0oRxSFzp9t0QNVHdRsfVsW/qs5rIODf2g7KiverpcunPlDfFM595ssuZx/fVq26BQGzc093oOYwWR0z@HHvNTO8D@N9OzA9GtJjj29aP0KXPntvGXw "Python 2 – Try It Online") Previous version that converted to binary: # [Python 2](https://docs.python.org/2/), ~~282~~ ~~261~~ 256 bytes ``` lambda s:''.join(chr(dict(zip([0,489335,96119,22391,5495,1367,341,1877,7637,30581,122333]+[2]*7+[23,469,1885,117,1,349,477,85,5,6007,471,373,119,29,1911,1501,7639,93,21,7,87,343,375,1879,7543,1909],[32]+range(48,91)))[int('0'+l,2)])for l in s.split('000')) ``` [Try it online!](https://tio.run/##bU9BcoMwDLz3FdxsN5qMZGGMOtOXUA5p0jR0KGGAS/t5KpomIQ32yNZKq127/RoOx8aP@@eXsd58vu42Sf9kzPrjWDV2e@jsrtoO9rtqbYGQ5sIcQDIiAe9ZCEIqAYizCJwSUB4jxIwVYcgVK4m5XBW@fIx6MqSZKCvXGYpAOiSQ6owWAmSIUZFWI8OvhXKFVCYgTbICwuA1hXzyYyWGyVMgBkUkKCUU7MtVt2ne32yag5BzrqiawRo0qxq8K93@2CV1UjVJv@7buppaiMa5se2UmOytITxt/AuiK57lRJc4rTm@7Z7nFhSQjHu4sZ6L4aLFJZ/LniuX@07435uI7gJxsUbXV9@LLn12oo0/ "Python 2 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 123 bytes ``` ->s{s.split(/0000?/).map{|r|r[0]?"YE9_0IZTO_BHKU58V_GR_SFA__1_4NP_60X_____C__D_ML7WQ3__2__J"[r.to_i(2)%253%132%74]:" "}*""} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664ulivuCAns0RD3wAI7PU19XITC6primqKog1i7ZUiXS3jDTyjQvzjnTy8Q00twuLdg@KD3Rzj4w3jTfwC4s0MIuJBwDk@3iXe18c8PNA4Pt4oPt5LKbpIryQ/PlPDSFPVyNRY1dDYSNXcJNZKSUGpVktJqfZ/QWlJsUJatJKhAQQaQLGhIYKPxDY0hGMIQOajysL0YTHBwFAplgvZZmSzDLDaAGcjmwoTgdPo5qK5yNAQAxsYYBUzRLgZw0xsPgWp@g8A "Ruby – Try It Online") Split the input string on character limit. Use 3 or 4 OFF bits so that spaces are converted to empty strings. Take the base 2 value of every character, and bring into a reasonable range (less than 60 possible values) using modulo on 3 successive divisions. [Answer] # [Python](https://tio.run/##bVHJboQwDL3zFbmZqGgUz3SZYnHovkzb6b4hDrQFNYgCmuTSr6dEMIG2OHqJ7Ze8OE71rT/LYlbXKsjjr7ePmGkvDQAmWSkLP3WB2P3R5dXe2fJkcfh0@3BHdPP6cvC8f35NF3T8eCp2aU5EO9TaNnbOtMGMNrcglIV2AWGjERMgU5aF6EdJrhKWsbRcNbMsmJyoKpfabOHcm/LIMNIw2jLCcLVOlH6PVRKEDqBoh@iA2McDH9GitWH8m12fG1EQCF575VBEjEpbfyi3ztjVCv6pAfEfhBjNYV9lLzb2qIZ2IqdvatdEv1qZ71Gu5NypfwA), ~~175~~ 168 bytes ``` s=lambda t,f=''.join:f('; TEMNAIOGKDWRUS;;QZYCXBJP;L;FVH09;8;;;7;;;;;;;61;;;;;;;2;;;3;45'[int('1'+f('0'if j[1:]else j for j in i.split('0')),2)]for i in t.split('000')) ``` First convert the string into list of 0(dash)/1(dot) string, add a prefix `1` (to prevent leading zeroes and deal with whitespaces), then convert to binary. Since every code have length no more than 5, the result ranges from 0 to 63 and can be listed in a string. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~67~~ 62 bytes ``` ṣ0L€«2ḅ2“>.&" þ/7;=¥çı¿¢×ÆФ怌©¦Çß÷µ¬£®Ñ½ðȷñ‘iịØB;⁶¤ œṣ0ẋ3¤Ç€ ``` [Try it online!](https://tio.run/##y0rNyan8///hzsUGPo@a1hxabfRwR6vRo4Y5dnpqSgqH9@mbW9seWnp4@ZGNh/YfWnR4@uG2wxMOLTm8DKj26KRDKw8tO9x@eP7h7Ye2HlpzaPGhdYcnHtp7eMOJ7Yc3PmqYkflwd/fhGU7Wjxq3HVrCdXQyyJKHu7qNgfrbgfr///8fbaijYKCjACExEVzWEFUNsgimLDEmYFWDaTJWNVh14RE3jAUA "Jelly – Try It Online") [Answer] # [Visual Basic .NET (.NET Core)](https://www.microsoft.com/net/core/platform), 252 bytes *-7 bytes thanks to @recursive* ``` Function A(i) For Each w In i.Split({"0000000"},0) For Each l In w.Split({"000"},0) Dim c=0 For Each p In l.Split("0") c=c*2+1+p.Length\2 Next A &="!ETIANMSURWDKGOHVF!L!PJBXCYZQ!!54!3!!!2!!!!!!!16!!!!!!!7!!!8!90"(c) Next A+=" " Next End Function ``` A function that takes a string of `1`s and `0`s, and returns a string. (Actually, only the `0` for the `OFF` is a hard requirement. Anything not `OFF` is assumed to be `ON`). The string literal is Morse code setup as a binary heap in array form. VB.NET lets you index strings as arrays of characters. The `\` is integer division, taking the left sub heap for `1` or the right sub heap for `111`. I used `!` as a blank for when there isn't a value in that heap spot. It's only necessary to properly pad out the indices. VB.NET lets you return by assigning a value to the function name (in this case, `A`). I just iteratively do string concatenations (`&`) to build up the output string. The very first time I need to use `&` because using `+` leaves a leading null char, but any other time I can use `+`, which behaves the same as `&` for strings. [Try it online!](https://tio.run/##hVJbT4MwFH6WX9H2wYAoafH@wANu4KYwL6hT48vWNa4JlgXBmRh/Ow7LpSpxpzk5l37n1tO36Q5NUlaEySyPGQhJ4eeCZjwRwNW5oflJCrwJnYMlGArArWgR80z/QFgS@tzGCiguQUsVJAF9/gKog1vgogTGFRBhZGjUoVu2ScyFFTDxnM2fbG3E3jPNBZsOgt7N0B2F0e31uH9@ejG482EAL89O7nsPj1cQ7u/BXQihDSWRg0o5XPERPMZIp0aVzXQQQFL3xAzUwxZRPgXhhAtto5eI1yRm1jjlGQu4YLqrI4LlwRUT0tqKTkjDklT7520d15EBE2QY/zSipsadBRtdLVJ7GrmmzK9@CfnDGHf6SDvRuhJdzyKDyu2slvIt5ecsvgA "Visual Basic .NET (.NET Core) – Try It Online") [Answer] # JavaScript (ES6), ~~170~~ 131 bytes ``` s=>s.split`000`.map(e=>' ETIANMSURWDKGOHVF L PJBXCYZQ'[c=+`0b${1+e.replace(/0?(111|1)/g,d=>+(d>1))}`]||'473168290 5'[c%11]).join`` ``` --- **How it works:** If you change the dots to 0s and the dashes to 1s, and prefix with a 1, you get binary numbers, which when converted to decimal gives you: 1. Letters: 2 - 18, 20, and 22 - 29. These can be converted to the correct letters by indexing into `' ETIANMSURWDKGOHVF L PJBXCYZQ'`. 2. Numbers: 32, 33, 35, 39, 47, 48, 56, 60, 62, and 63. If we take these numbers modulus 11, we get the numbers 0 - 8 and 10, which can be converted to the correct numbers by indexing into `'473168290 5'`. The program splits on characters, then converts each character into dots and dashes, which are converted into the appropriate output based on the above rules. --- **Test Cases:** ``` let f= s=>s.split`000`.map(e=>' ETIANMSURWDKGOHVF L PJBXCYZQ'[c=+`0b${1+e.replace(/0?(111|1)/g,d=>+(d>1))}`]||'473168290 5'[c%11]).join`` console.log(f('101010100010001011101010001011101010001110111011100000001011101110001110111011100010111010001011101010001110101')) console.log(f('10100000001011100011101110000000101110000000101011101000101000101010001010101')); console.log(f('1010111011101110001110111011101110111000101110111011101110001110111010101')); console.log(f('101010001110111011100010101')); ``` [Answer] # [Python 2](https://docs.python.org/2/), 127 bytes ``` lambda s:''.join("IVMB T K 9LZF 1HWO3 GUS4 8 7A E QR 26 NJX Y0P 5D C"[(int('0'+l)^2162146)%59]for l in s.split('000')) ``` [Try it online!](https://tio.run/##bY/dboJAEIXv@xQnJGbZmJgZCihNelGrrVb7o1bbqm2CMaQYBCLc@PQUY0UQdnN2Z2ZnvpkN9/Fv4GuJc7tMPHu7WtuIboRobALXV5X@7LkNvAMDWMP5A7j38XqNx@lERwvNO6CL0RiaCeDl6TM98UVvMDrAvbJQXT9WBYm6J380NjXWTVkzrG8n2MGD6yNqRKHnHnKIhJRJuEsr4KiC6bjpX8xnP2czZzquvF98PdVVEIiFvCq0zsOoskVm57GnSHaXwBczMZdEVBnj89RlaNVnD2nJHw "Python 2 – Try It Online") Building off of **TFeld**'s solution by removing *replace* and by working in base 10, at the cost of a bitwise xor and a longer reference string. [Answer] # PHP, ~~321~~ 284 bytes *Saved 37 bytes thanks to @ovs* ``` $a=array_flip([242,161,134,125,122,121,202,229,238,241,5,67,70,22,1,43,25,40,4,53,23,49,8,7,26,52,77,16,13,2,14,41,17,68,71,76]);foreach(split('0000000',$argv[1])as$w){foreach(split('000',$w)as$m){echo($v=$a[base_convert(str_replace([111,0],[2,],$m),3,10)])>9?chr($v+55):$v;}echo' ';} ``` Previous version (321 bytes) ``` $a=array_flip([22222,12222,11222,11122,11112,11111,21111,22111,22211,22221,12,2111,2121,211,1,1121,221,1111,11,1222,212,1211,22,21,222,1221,2212,121,111,2,112,1112,122,2112,2122,2211]);foreach(split('0000000',$argv[1])as$w){foreach(split('000',$w)as$m){echo($v=$a[str_replace([111,0],[2,],$m)])>9?chr($v+55):$v;}echo' ';} ``` [Try it online!](https://eval.in/901674) Ungolfed version : ``` $a=array_flip( // Building an array $a with every Morse letter representation (1=dot, 2=dash) and flip it [22222,12222,11222,11122,11112, // 01234 11111,21111,22111,22211,22221, // 56789 12,2111,2121,211,1,1121,221, // ABCDEFG 1111,11,1222,212,1211,22, // HIJKLM 21,222,1221,2212,121,111,2, // NOPQRST 112,1112,122,2112,2122,2211]); // UVWXYZ foreach (split('0000000', $argv[1]) as $w){ // for each word (separate with 7 consecutive zeroes) foreach (split('000',$w) as $m){ // for each letter (separate with 3 consecutive zeroes) echo ($v = $a[str_replace([111,0],[2,],$m)]) > 9 // Replace '111' with '2' and '0' with nothing and find $v, the corresponding entry in the array $a ? chr($v+55) // If > 9th element, then letter => echo the ASCII code equal to $v+55 : $v; // Else echo $v } echo ' '; // Echo a space } ``` [Answer] # [GNU sed](https://www.gnu.org/software/sed/), 261 + 1 = 262 bytes +1 byte for `-r` flag. ``` s/000/;/g s/111/_/g s/0//g s/$/;:51111141111_3111__211___i1____6_11117__1118___119____10_____H1111V111_F11_1L1_11P1__1J1___B_111X_11_C_1_1Y_1__Z__11Q__1_S111U11_R1_1W1__D_11K_1_N__1G__1O___I11A1_M__E1T_/ : s/([1_]+);(.*([^1_])\1)/\3\2/ t y/i/1/ s/;/ /g s/:.*//g ``` [Try it online!](https://tio.run/##bU/JUoNQELzzFR48QKxkphNXOLnvcV@DzkXL4mIsycWfF3sgIag8qnuWZvq9yV9fiiIXVZVE3oJcAIiVmUoZFiWJV@Bn2ckGTtZ3sszJVs2FNfOwbh42vA11tgMXb31oj8AJgXPO4ciHt3zonmTbRuWBZI9ucUGyK4o31C4p3VHZoXDM/pDiPnFGh0NgE3ZqtotrkyDmk8MR7GkpSsJeJxw9M49SRJIO0r4Ek@BLMoHwt0QWyg3jXoerFgW0@nQKXl7XjRyoUZ1m/VudzbU4KIKqmjtoq2@dN71mnTpWbn9uB/5BtbWH@fumTm27KL7HH5Ns/J4X3c8f "sed 4.2.2 – Try It Online") ## Explanation This is a very basic lookup table solution. The first three lines transform the input so dashes are `_`s and dots are `1`s. First, `000`s are replaced with `;`, so characters are separated by `;` and words by `;;0`. Then `111`s are replaced by `_` and all remaining `0`s are discarded, leaving `1`s for dots. ``` s/000/;/g s/111/_/g s/0//g ``` The next line appends the lookup table. It takes the form `cmcmcm...` where `c` is a character and `m` is the sequence of `_`s and `1`s representing it. `i` is substituted for `1` in the table for disambiguation. Since regular expressions in sed are always greedy, the table is sorted from longest to shortest code (so e.g. `1_` matches `A1_` instead of `i1____`). ``` s/$/;:51111141111_3111__211___i1____6_11117__1118___119____10_____H1111V111_F11_1L1_11P1__1J1___B_111X_11_C_1_1Y_1__Z__11Q__1_S111U11_R1_1W1__D_11K_1_N__1G__1O___I11A1_M__E1T_/ ``` Next, in a loop, each sequence of `_`s and `1`s (and the subsequent `;`) is replaced by the corresponding character: ``` : s/([1_]+);(.*([^1_])\1)/\3\2/ t ``` Finally, cleanup: `i`s are replaced with `1`s, remaining `;`s are spaces, and the lookup table is deleted: ``` y/i/1/ s/;/ /g s/:.*//g ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 355 bytes ``` s->{var r="";for(var t:s.split("0000000")){for(var u:t.split("000"))for(int x[]={1,7,5,21,29,23,87,93,119,85,117,341,375,343,373,471,477,349,469,1877,1367,1909,1879,1501,1911,1885,7637,5495,7543,7639,6007,30581,22391,122333,96119,489335},i=36;i-->0;)if(u.equals(Long.toString(x[i],2)))r+="ETISNAURMHD5WVLKGFB64ZXPOC73YQJ82910".charAt(i);r+=" ";}return r;} ``` [Try it online!](https://tio.run/##bVJZj9owEH7nV1h5ilUT2XEukwaJtrs99uhBb8SDyxLWNCTUcdCuEL@dTgiwKcXReI5v5hvH47lcye787vdWLZaFNqg00qgJmkPYqYzKnIHW8rF0SqOnchF3ltWvDPBJJssS3UiVo3UHoX10X7wq1B1aAGYPjVb5bDRGUs9KvEtFLe60yidGFblzuTeeNwWkUX2UJtuy21@vpEY6saw4LbRdO6YHJ1pmytgWbZaF8fqAVj3TQgGpAZUb9DAaJ2tGQuITlxFXEJeTKCSCE8YEiXxQIeEeIzz0QXPQnHghA6njgniBICwCh/EANkF3Lmw@ZeAy2CKgCQMOPTwBlg8s4AoSUAoc1I@gscsFZILinIig7u1FgnN/Q1TCg1h1u30aY5XalTP9U8mstK@LfOaYorkX@2GkxsTFGOtniXXx@e3wdvDl082bV/63r9dXry9fBN7P7x/evwz5j4/vIlcwajmTe6kHxlY4rmuQFW/01FQ6RzrebOOTuTTDdoaNKlJ7hyNkMdp8dC@MPfktm7GjNKvt/4se6s4wUGaRduM2FT3b4Gi3SQ@Roz6hPTkPY/8JpWdj7OnEp5TnfhOSdjnYWcilnWIHXuWFnNzbw8fSTOGaK9PrLWG@JstxPZFNZ7P9Cw "Java (JDK) – Try It Online") ## Credits * -3 bytes saved thanks to @Jeutnarg. * -6 bytes thanks to @ceilingcat [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 67 bytes ``` ŒrḌṣ7ṣ€3ṣ€€1’H_4F€€ḅ3i@€€“ṗƙ⁶}zyȮẓŀȯ¦CFæ¢+ı(¥5ç1®¬ȷ4MÑÆ£Ç)×DGL‘ịØBK ``` [Try it online!](https://tio.run/##y0rNyan8///opKKHO3oe7lxsDsSPmtYYQyggMnzUMNMj3sQNwnu4o9U40wHCftQw5@HO6cdmPmrcVltVeWLdw12TjzacWH9ombPb4WWHFmkf2ahxaKnp4eWGh9YdWnNiu4nv4YmH2w4tPtyueXi6i7vPo4YZD3d3H57h5P3fBWja4XYgEfn/fzQXp6EBBBpAsaEhgo/ENjSEYwhA5qPKwvRhMcHAUAdiI7IZBlhNhrORTYOJwGmYeWguMDTEwAYGWMUMEW6Em4XNRwaGXLEA "Jelly – Try It Online") [Answer] # JavaScript (ES6), ~~104~~ ~~102~~ ~~101~~ 99 bytes ``` s=>s.split`000`.map(n=>" _T__9VEFO0K7MX_CGS__LU1RYIJ845__Z_B_D6QP_3__AHNW2"[n*1741%8360%51]).join`` ``` ### Test cases ``` let f = s=>s.split`000`.map(n=>" _T__9VEFO0K7MX_CGS__LU1RYIJ845__Z_B_D6QP_3__AHNW2"[n*1741%8360%51]).join`` console.log(f("101010100010001011101010001011101010001110111011100000001011101110001110111011100010111010001011101010001110101")) console.log(f("10100000001011100011101110000000101110000000101011101000101000101010001010101")) console.log(f("1010111011101110001110111011101110111000101110111011101110001110111010101")) console.log(f("101010001110111011100010101")) ``` ### How? Because converting from binary to decimal costs bytes, we use a hash function which works directly on binary blocks interpreted in base 10. **Example** ``` dot dash dot dot = 101110101 101110101 * 1741 = 176032685841 176032685841 % 8360 = 3081 3081 % 51 = 21 --> The 21st character in the lookup table is 'L' (0-indexed). ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~144~~ ~~138~~ ~~130~~ 103 bytes ``` T`d`@# ^|@@@ @?# E {T`L#@`R6_BI_Z5S1C_GD8__\L\HNF3P__7_`\w@# T`589B-INPRSZ#@`490XYKT2\OVAMJWUQ_`\w## ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyQhJcFBmSuuxsHBgUuBS8HBXpnLlas6JMFH2SEhyCzeyTM@yjTY0Dne3cUiPj7GJ8bDz804ID7ePD4hphyoMSTB1MLSSdfTLyAoOAqoxcTSICLSO8Qoxj/M0dcrPDQQpE5Z@f9/QwMINIBiQ0MEH4ltaAjHEIDMR5WF6cNigoEhF4SHMMEAq7lwNrJZMBE4DTENzXZDQwxsYIBVzBDhPqhJ2PxiYAgA "Retina – Try It Online") Link includes test cases. Explanation: ``` T`d`@# ``` Change the binary digits to other characters because 0 and 1 are valid outputs. ``` ^|@@@ ``` Insert a space before every character and two spaces between words. ``` @?# E ``` Assume that all characters are Es. ``` {T`L#@`R6_BI_Z5S1C_GD8__\L\HNF3P__7_`\w@# ``` Translate all letters assuming that they will be followed by a dot. For instance, if we have an E, and we see a second dot (we consumed the first when we inserted the E) then it translates to an I. For letters that can only be legally followed by a dash, they are translated with that assumption, and then the dash is consumed by the next stage. Other letters are deleted (keeping `L` costs a byte). ``` T`589B-INPRSZ#@`490XYKT2\OVAMJWUQ_`\w## ``` If it transpires that they were in fact followed by a dash, then fix up the mistranslations. This also consumes the dash when it was assumed by the previous stage. Both translations are repeated until all of the dots and dashes are consumed. [Answer] # [Perl 5](https://www.perl.org/), 241 + 1 (`-p`) = 242 bytes ``` %k=map{(23,469,1885,117,1,349,477,85,5,6007,471,373,119,29,1911,1501,7639,93,21,7,87,343,375,1879,7543,1909,489335,96119,22391,5495,1367,341,1877,7637,30581,122333)[$i++]=>$_}A..Z,0..9;map{$\.=$k{oct"0b$_"}for split/000/;$\.=$"}split/0{7}/}{ ``` [Try it online!](https://tio.run/##bY7tSsQwEEVfRUoFZWfTmU6TybBU8AF8AT9YVBTKrrbs9l/Jqxsni6KChEDOmTuXTC@Hvc/5fNe/PU7LRcvQBQWK0QORAAF3Cp0ImPAQEMXIrLDNFVrLKhGQRwIJrKAMrT0hiq2yBa0oioJ4I1K0tqjMHjScClpWAt@pxTiUHSp5KWVG6KOxhZgv7@phtXror@ptunbuFtA53ZRf1/eur3fL@DxX@FRvq/Q6Hs6O036YG0RsNqd5lb7MIqlJS86Edujn4h/6Zf9z31TOxzjNw/h@zOsb70zk9fQJ "Perl 5 – Try It Online") [Answer] # PHP, 181+1 bytes ``` foreach(explode(_,strtr($argn. 0,[1110=>1,10=>0,"0000"=>_A,"00"=>_]))as$t)echo$t<A?~$t[-5]?(10+substr_count($t,0)*(1-2*$t[-5]))%10:__ETIANMSURWDKGOHVF_L_PJBXCYZQ[bindec("1$t")]:" "; ``` Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/f47aed535d352e741dfdeb01ea13e4ac6249dec4). [Answer] ## [ES6](http://www.ecma-international.org/ecma-262/6.0/ "ES6"), 268 bytes Uses ASCII encoding after mapping from a base36 representation of the morse to an index position. Not my best golf day, but it only took around 15 mins. ``` s=>s.split('00000').map(w=>String.fromCharCode.apply({},w.split('000').map(c=>"ahkn,225z,h9z,48n,11z,9h,1g5,5w5,nlh,2me5,,,,,,,,n,d1,1gd,39,1,9p,d9,2d,5,4mv,d3,ad,3b,t,1h3,15p,5w7,2l,l,7,2f,9j,af,1g7,1h1".split(',').indexOf(parseInt(c,2).toString(36))+48))).join(' ') ``` Easier to read (kinda): ``` s=> s .split('00000') .map(w=> String.fromCharCode.apply({}, w.split('000') .map(c=> "ahkn,225z,h9z,48n,11z,9h,1g5,5w5,nlh,2me5,,,,,,,,n,d1,1gd,39,1,9p,d9,2d,5,4mv,d3,ad,3b,t,1h3,15p,5w7,2l,l,7,2f,9j,af,1g7,1h1" .split(',') .indexOf( parseInt(c,2).toString(36) )+48) ) ).join(' ') ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 288 bytes Thought about reading in the data as binary from a file but that gets hard to explain. Base 36 seemed like a good compromise way to store the data efficiently lexically. Takes a string of 0's and 1's as input. Does a series of replacements, starting with the runs of 7 zeros, then the runs of 3, then the longest binary letters down to the shortest. Order of replacement is important. ``` StringReplace[#,Thread@Rule[Join[{"0000000","000"},#~FromDigits~36~IntegerString~2&/@StringSplit@"ahkn 2me5 225z nlh h9z 5w7 5w5 5tj 4mv 48n 1h3 1h1 1gd 1g7 1g5 15p 11z d9 d3 d1 af ad 9p 9j 9h 3b 39 2l 2f 2d t n l 7 5 1"],Insert[Characters@" 09182Q7YJ3OZCX6P4GKBWLFV5MDRUHNASTIE","",2]]]& ``` [Try it online!](https://tio.run/##bY9bS8NAFIT/yrCFPgXMbrpt8yBEW6utt9rWa8jD2myyqck2pKtCxfz1GImXCp7DBzMczsBkwiiZCZMsRRXtV3NTJDqeyTwVS@m3rIUqpAi92XMq/ck60f4bsZsh1qci71arHBXrbJjEidmUTrccayNjWTRJJWvveY2c52liPCLUkwbLJAdjfAudKih3C/7aq@HgZoVO9oJOX4Mqp4aCxmFNr4aD8hyUbhG6CB2EFCKCCOHmcFdwFZxHOC5YChaBhTDQSFFHg5LAGuuNLIw/UKIQSyOLjUdgu7TPrnr3E@fyYXDXnXaOTw9vz0Y3/Hw4uz65OJgvxkd1V2KxIAja1bSuYrzII9Ru1v6C0l@/oyn9oZld//f6/fdPgk1J9QE "Wolfram Language (Mathematica) – Try It Online") [Answer] ## [Perl 5](https://www.perl.org/), 195 bytes **194 bytes code + 1 for `-p`.** ``` %h=map{$_,(A..Z,0..9)[$i++]}unpack"S26I2S7I","\xd5]u]\xddUw\xd7uw w\xdd\xd7 ]WWwWw uwwwwwWwWUU\xd5 uw\xdd\xdd";s/0{7}/ /g;s/(\d+?)(000|\b)/$h{oct"0b$1"}/ge ``` I couldn't get this working with just a standard packed binary string, I had to escape the higher-byte chars otherwise I'd be on 171, if anyone knows what I've missed, or why it's breaking that'd be great! [Try it online!](https://tio.run/##bY9Ra4MwFIVvHkTYe@mTMIIDRac3BSejlLHHPhcRNmW0tbSyrcpauQPnX5/V2arbTLjknHOTL0m6@XhzSjWe4bS82c3el2muvpjao2U9mWhZ9/qzGhtGWGT7dLl@5YvJ3XyycOfc5GMIPiOHhXIGDEJWmYh5IAGNK@myjBEoQHKdS3WihDACGXzwGTFfJiWTiWQgYkA@jXzJY16921Eyqg/9AIFPDzbmbmFf29tKakFkPOgaIn4FK91Wd3myPnJcqYIX9nZTlgKbiecSovM9LURbzej7393LuQECiqvGdQQc5La6z7ok7drQ/twuxL9CHMxE974zaegvVe87SY9xsj@Ut@kJ "Perl 5 – Try It Online") ### Explanation The binary string is a [`pack`ed](http://perldoc.perl.org/perlpacktut.html) list of the numbers that relate to the morse characters (`101011101` - `349` for `F` etc) and this is zipped with the ranges `A..Z,0..9` and used as a lookup. The `s///` expressions replace all runs of seven `0`s with space and then all runs of digits, separated with three `0`s or word boundaries `\b`, with their corresponding key from the `%h` hash. ]
[Question] [ This question is inspired by the cover of the book "Godel, Escher, Bach": [![](https://i.stack.imgur.com/yg9UJ.jpg)](https://i.stack.imgur.com/yg9UJ.jpg) The challenge here is to write a function that tells if three given letters can produce a 3D sculpture that can be read from three sides. For this exercise, the only letters you can use are 26 5px \* 5px bitmaps: ![](https://s29.postimg.org/ohfm5uphz/letters.png) Or in binary (A to Z): ``` 01110 11110 01111 11110 11111 11111 11111 10001 11111 11111 10001 10000 10001 10001 01110 11110 01110 11110 01111 11111 10001 10001 10001 10001 10001 11111 10001 10001 10000 10001 10000 10000 10000 10001 00100 00100 10010 10000 11011 11001 10001 10001 10001 10001 10000 00100 10001 10001 10001 01010 01010 00010 10001 11110 10000 10001 11100 11110 10011 11111 00100 00100 11100 10000 10101 10101 10001 10001 10001 11111 01110 00100 10001 01010 10001 00100 00100 00100 11111 10001 10000 10001 10000 10000 10001 10001 00100 10100 10010 10000 10001 10011 10001 11110 10011 10010 00001 00100 10001 01010 10101 01010 00100 01000 10001 11110 01111 11110 11111 10000 11111 10001 11111 11100 10001 11111 10001 10001 01110 10000 01111 10001 11110 00100 01110 00100 01010 10001 00100 11111 ``` The sculpture is formed by three letters in the following order: * letter one on top, * letter two on the left * letter three on the right * the bottom of letter one is bound to the top of the letter two. Example: ![](https://s21.postimg.org/vz0htem4n/schema.png) Your function may accept as input three uppercase letters (three chars or three strings of one letter), and output a boolean (true/false or 0/1) telling if the corresponding sculpture can exist. Example: ``` f("B","E","G") // true (because if you "sculpt out" B on top + E on the left + G on the right, and watch the three sides of the sculpture, you'll see exactly B, E and G as they are defined) f("B","G","E") // false (because if you "sculpt out" B on top + G on the left + E on the right, and watch the three sides of the sculpture, you won't see a complete G and a complete E. Their shapes bother each other) ``` NB: you may return true even if the sculpture contains "flying pixels" (cubes or group of cubes that are attached to nothing). Standard loopholes apply. More precisely, you can't use external input besides the three letters, and you can't hardcode the 17576 possible answers in your source code Shortest answer in characters in any language wins! Have fun :) [Answer] # Mathematica 423 I added a section called "How blocking works". ## Ungolfed (\*The binary data of the alphabet are stored as a single string in `s`. `vars` imports it and converts it into an array.) ``` vars=IntegerDigits[#,10,5]&/@Transpose[ImportString[s,"Table"]]; get[char_]:=(ToCharacterCode[char]-64)[[1]]; cube=Flatten[Table[{i,j,k},{i,5},{j,5},{k,5}],2]; (* character slice along axis *) slice[char_,layer_,axis_,bit_]:=Insert[(Reverse@#),layer,axis]&/@Position[Reverse@vars[[get[char]]],bit] (* cuboid assembly *) charBlocks[{char_,axis_,bit_}]:=Flatten[Table[slice[char,k,axis,bit],{k,5}],1] (* letters are those whose HOLES should be sculped out of the full cube *) sculpturePoints[letters_(*{char_,axis_,bit_}*)]:=Complement[cube,Union[Join@@(charBlocks/@letters(*{char,axis,bit}*))]]; collapse[letters_(*{char_,axis_,bit_}*),axis_]:=Union[Reverse/@(Delete[#,axis]&/@sculpturePoints[letters(*{char,axis,bit}*)])](*/.{x_,y_}\[RuleDelayed] {6-x,y}*) vQ[l_]:=collapse[l,3]==collapse[{l[[1]]},3]\[And]collapse[l,2]==collapse[{l[[2]]},2]\[And]collapse[l,1]==collapse[{l[[3]]},1] validQ@l_:= vQ[{{l[[1]],3,0},{l[[2]],2,0},{l[[3]],1,0}}] perspective[letts_,view_:1]:= Graphics3D[{AbsolutePointSize[10],Cuboid/@sculpturePoints[letts]}, ImageSize-> 120, ViewPoint-> Switch[view,1,{0,0,\[Infinity]},2,{0,-\[Infinity],0},3,{\[Infinity],0,0},4,Top,5,Front,6,Right,True,{0,0,\[Infinity]}], PlotLabel-> Switch[view,1,"top orthogonal view",2,"front orthogonal view",3,"right orthogonal view",4,"top close-up view",5,"front close-up view",6,"right close-up view"], ImagePadding->10] ``` --- ## Example Is the cube `{"B", "G", "E"}` valid? (i.e. Will the three letters project correctly onto the walls?) ``` validQ[{"B", "G", "E"}] ``` > > False > > > **Illustrations** The figures below show how BGE is rendered. The upper row of figures takes orthogonal perspectives, as if the viewer were positioned at infinite distances from the cube. The lower row shows how the blocks would look from close up. The 3D figures can be manually rotated to inspect precisely where the individual unit cubes are positioned. A problem occurs with the letter "G". There is nothing connecting the serif to the rest of the letter. ``` pts = {{"B", 3, 0}, {"G", 2, 0}, {"E", 1, 0}} GraphicsGrid@Partition[Table[perspective[pts, view], {view, 1, 6}], 3] ``` ![bge](https://i.stack.imgur.com/DaMLd.png) --- BEG, however, should work fine. ``` validQ[{"B", "E", "G"}] ``` > > True > > > ``` pts2 = {{"B", 3, 0}, {"E", 2, 0}, {"G", 1, 0}} GraphicsGrid@Partition[Table[perspective[pts2, view], {view, 1, 6}], 3] ``` ![beg](https://i.stack.imgur.com/rbuCY.png) --- ## How Does Blocking Work? Please excuse me if this seems obvious, but perhaps some folks will want to visualize how how letters interfere with each other, canceling their 3D pixels. Let's follow what happens to the letter G, in the BGE cube rendering. We'll be paying special attention to the [voxel](http://en.wikipedia.org/wiki/Voxel) (3D pixel or unit cube) below. That is the pixel that disappears in the BGE cube. It is the pixel corresponding to Row 4, Column 5 in the bit array and in the corresponding array plot. ![blocking 1](https://i.stack.imgur.com/OtHdw.png) --- In the x y plane, the pixel corresponds to the gray disk at point (5,2). But because we're going to work in 3D, we need to consider the 5 positions in the *shaft* from (5,1,2) to (5,5,2). If any of those pixels survives sculpting by the letters B and E, we'll be able to see the pixel of interest in the 3D projection on the wall. ![blocking 2](https://i.stack.imgur.com/ydaNI.png) --- Letters interfere when pixels are removed from the solid block. In the left, the black arrow represents the carving out of pixels, corresponding to the bit at the bottom right; it has the value 0 for the letter B. Carving out removes the pixel at (5,1,2), along with those directly above and below it. Four pixels remain to be accounted for. ![blocking 3](https://i.stack.imgur.com/ME6sl.png) But as the right pane shows, the letter E sculpts out the remaining pixels of interest, (5,2,2) (5,3,2), (5,4,2) and (5,5,2). (This is due to the fact that the letter E has bits equal to 0 in the fourth row, from column 2 through column 5.) As a result, not a single pixel remains among those that were needed to ensure shade at point (5,2) on the far wall (for the letter G). Instead, there will be a bright spot corresponding to a hole in the letter G! The cube BGE is no good because it incorrectly renders G. ## Golfed 423 chars The function `h` served the same role as `validQ` in the unGolfed code. The rendering function, `perspective`, is not included because it does not contribute to, and is not required by, the challenge. ``` x=Reverse;q=Flatten; g@c_:=(ToCharacterCode[c]-64)[[1]]; r[{c_,a_,b_}]:=q[Table[Insert[(x@#),k,a]&/@Position[x@(IntegerDigits[#,10,5]&/@ Transpose[ImportString[s,"Table"]])[[g[c]]],b],{k,5}],1] p@l_:=Complement[q[Table[{i,j,k},{i,5},{j,5},{k,5}],2],Union[Join@@(r/@l)]]; w[l_,a_]:=Union[x/@(Delete[#,a]&/@p[l])] v@l_:=w[l,3]==w[{l[[1]]},3]\[And]w[l,2]==w[{l[[2]]},2]\[And]w[l,1]==w[{l[[3]]},1] h@l_:= v[{{l[[1]],3,0},{l[[2]],2,0},{l[[3]],1,0}}] ``` [Answer] # Prolog, ~~440~~, 414 ``` :- encoding(utf8). i(I) :- between(0,4,I). h(T,L,R,X,Y,Z) :- i(X),i(Y),i(Z),I is 4-X,c(T,Z,I),c(L,Z,Y),c(R,X,Y). f(T,L,R) :- forall((i(U),i(V),I is 4-V),((\+c(T,U,V);h(T,L,R,I,Y,U)),(\+c(L,U,V);h(T,L,R,X,V,U)),(\+c(R,U,V);h(T,L,R,U,V,Z)))). c(C,X,Y) :- char_code(C,N),i(X),i(Y),Z is X+5*Y+25*(N-65),I is floor(Z/15),O is (Z mod 15),string_code(I,"䙎㹟䘑߯硁䙏縑ԁࠟя摟䠑䠑ᐑ粤Ⴟ䔅┉ё籁垑䙑曓䗱㩑䙏㡏晑䘞䕟㡞縐Ⴄ䙄㩑⩑䒪噑⩊䕤ᅱ粤ࢨ?",V),1 is (V-32)>>O/\1. ``` The program is called like this: ``` ?- f('B','E','G'). true. ?- f('B','G','E'). false. ``` `Prolog` seemed to be a good choice, since it's easy to represent the problem in first order logic. Also `Prolog` provides potent functionality for solving this kind of problem. **However, since the code is golfed, I guess I should add some explanation.** ### Mildly golfed version ``` :- encoding(utf8). i(I) :- between(0,4,I). t(C,X,Z) :- I is 4-X,c(C,Z,I). l(C,Y,Z) :- c(C,Z,Y). r(C,X,Y) :- c(C,X,Y). h(T,L,R,X,Y,Z) :- i(X),i(Y),i(Z),t(T,X,Z),l(L,Y,Z),r(R,X,Y). u(T,L,R) :- forall((i(U),i(V),I is 4-V,c(T,U,V)),h(T,L,R,I,Y,U)). v(T,L,R) :- forall((i(U),i(V),c(L,U,V)),h(T,L,R,X,V,U)). w(T,L,R) :- forall((i(U),i(V),c(R,U,V)),h(T,L,R,U,V,Z)). f(T,L,R) :- u(T,L,R),v(T,L,R),w(T,L,R). c(C,X,Y) :- char_code(C,N),i(X),i(Y),Z is X+5*Y+25*(N-65),I is floor(Z/15),O is (Z mod 15),string_code(I,"䙎㹟䘑߯硁䙏縑ԁࠟя摟䠑䠑ᐑ粤Ⴟ䔅┉ё籁垑䙑曓䗱㩑䙏㡏晑䘞䕟㡞縐Ⴄ䙄㩑⩑䒪噑⩊䕤ᅱ粤ࢨ?",V),1 is (V-32)>>O/\1. ``` The coordinates corresponding to the pixels on each side of the dice can be easily converted to a 3D coordinate system. I use `T`,`L` and `R` for top(1), left(2) and right(3) side. `u` and `v` are used for the coordinates in the images: * **T**: `(u,v) -> (4-v, ?, u)` * **L**: `(u,v) -> (?, v, u)` * **R**: `(u,v) -> (u, v, ?)` The results for each active (i.e. black) pixel are combined to a set of "3D-pixels" that can be acitvated without changing the look of the object from this side. The intersection of the sets for each side are all 3D-pixels, that can be activated without adding pixels, that would obstruct the view (i.e. looking from at least one side there would be a pixel that shouldn't be there). All that remains is to check for each side, if there is a pixel in the intersection that blocks the view, where it's necessary. This leads to the predicates in the program: * **f**: does the final check; takes the letters at the top, the left side and the right side * **u**, **v** and **w**: do the checks, if for every pixel active on the side there is a 3D-pixel in the intersection, that blocks the view * **h**: checks, for the existence of a pixel in the intersection * **t**,**l**,**r**: checks, if a 3D-pixel can be blocked from top, left and right side. * **c**: checks for the pixel in the image of a letter. The string in there may look a bit strange, but it's only a compact way to store the image data. It's simply a character sequence with the following values(hex notation): ``` [464e,3e5f,4611,7ef,7841,464f,7e11,501,81f,44f,645f,4811,4811,1411,7ca4,10bf,4505,2509,451,7c41,5791,4651,66d3,45f1,3a51,464f,384f,6651,461e,455f,385e,7e10,10a4,4644,3a51,2a51,44aa,5651,2a4a,4564,1171,7ca4,8a8,3f] ``` Each of these characters stores the data for 3 pixel rows in letter image(s) (=15 pixel). The pixels are also reordered so that the data is stored at one location and not divided across multiple rows, like the data of the OP. ## Mathematic formulation ![formula](https://chart.googleapis.com/chart?cht=tx&chl=I%3D%5C%7Bn%20%5Cin%20%5Cmathbb%7BN%7D%20%7C%200%20%5Cleq%20n%20%5Cleq%204%20%5C%7D) ### Input data ![formula](https://chart.googleapis.com/chart?cht=tx&chl=C_%5Cbeta%20%3D%20%5C%7B(u%2Cv)%20%7C%20%5Ctext%7Bpixel%20at%20position%20%7D%20(u%2Cv)%20%5Ctext%7B%20is%20black%20in%20image%20for%20char%20%7D%5Cbeta%5C%7D) ### Conversion from pixel in one char to set of 3D-pixels that obstruct the view for this pixel ![formula](https://chart.googleapis.com/chart?cht=tx&chl=T((u%2Cv))%20%3D%20%5C%7B(x%2Cy%2Cz)%20%5Cin%20I%5E3%20%7C%20x%3D4-v%20%5Cwedge%20u%3Dz)%5C%7D) ![formula](https://chart.googleapis.com/chart?cht=tx&chl=L((u%2Cv))%20%3D%20%5C%7B(x%2Cy%2Cz)%20%5Cin%20I%5E3%20%7C%20y%3Dv%20%5Cwedge%20u%3Dz)%5C%7D) ![formula](https://chart.googleapis.com/chart?cht=tx&chl=R((u%2Cv))%20%3D%20%5C%7B(x%2Cy%2Cz)%20%5Cin%20I%5E3%20%7Cx%3Du%20%5Cwedge%20y%3Dv)%5C%7D) ### Pixels that can be added safely(without obstructing the view in the wrong place) ![formula](https://chart.googleapis.com/chart?cht=tx&chl=H(%5Calpha%2C%5Cbeta%2C%5Cgamma)%3D%5C%7Bp%5Cin%20I%5E3%7Cp_s%5Cin%20C_%5Calpha%5Cwedge%20p%5Cin%20T(p_s)%5C%7D%5Ccap%5C%7Bp%5Cin%20I%5E3%7Cp_s%5Cin%20C_%5Cbeta%5Cwedge%20p%5Cin%20L(p_s)%5C%7D%5Ccap%5C%7Bp%5Cin%20I%5E3%7Cp_s%5Cin%20C_%5Cgamma%5Cwedge%20p%5Cin%20R(p_s)%5C%7D) ### Checks for each side, that the pixels that need to be obstructed can be obstructed safely ![formula](https://chart.googleapis.com/chart?cht=tx&chl=u(%5Calpha%2C%5Cbeta%2C%5Cgamma)%3D%5Cforall%20p%5Cin%20I%5E2%5C%3B%5C%3B%5Cexists%20p%27%20%5Cin%20H(%5Calpha%2C%5Cbeta%2C%5Cgamma)%5C%3B%5C%3B%3A(p%5Cin%20C_%5Calpha%5Crightarrow%20p%27%5Cin%20T(p))) ![formula](https://chart.googleapis.com/chart?cht=tx&chl=v(%5Calpha%2C%5Cbeta%2C%5Cgamma)%3D%5Cforall%20p%5Cin%20I%5E2%5C%3B%5C%3B%5Cexists%20p%27%20%5Cin%20H(%5Calpha%2C%5Cbeta%2C%5Cgamma)%5C%3B%5C%3B%3A(p%5Cin%20C_%5Cbeta%5Crightarrow%20p%27%5Cin%20L(p))) ![formula](https://chart.googleapis.com/chart?cht=tx&chl=w(%5Calpha%2C%5Cbeta%2C%5Cgamma)%3D%5Cforall%20p%5Cin%20I%5E2%5C%3B%5C%3B%5Cexists%20p%27%20%5Cin%20H(%5Calpha%2C%5Cbeta%2C%5Cgamma)%5C%3B%5C%3B%3A(p%5Cin%20C_%5Cgamma%5Crightarrow%20p%27%5Cin%20R(p))) ### Combinatin of checks for each side ![formula](https://chart.googleapis.com/chart?cht=tx&chl=f(%5Calpha%2C%5Cbeta%2C%5Cgamma)%3Du(%5Calpha%2C%5Cbeta%2C%5Cgamma)%5Cwedge%20v(%5Calpha%2C%5Cbeta%2C%5Cgamma)%5Cwedge%20w(%5Calpha%2C%5Cbeta%2C%5Cgamma)) [Answer] # J - ~~223~~ ~~197~~ 191 char A function taking a three char list as argument. ``` (_5#:\".'1b',"#:'fiiifalllvhhhheehhhvhhllvgkkkvnlhhvv444vhhvhhggvhjha44v1111vv848vv248vehhheciiivfjhhedmkkvilll9ggvggu111uo616ou121uha4ahg878ghpljh')((-:0<+/"1,+/"2,:+/)*`(*"1/)/)@:{~_65+3&u: ``` This golf relies heavily on a powerful feature of J called *rank*, which gives us the "sculpt out" and "watch side of" operations almost for free. To oversimplify it a bit, rank refers to the dimensionality of a noun or of a verb's natural arguments. J has multidimensional arrays, and it is obvious that, say, a 3D array can be interpreted as a single 3D array, or as a list of matrices, or a 2D array of vectors, or a 3D array of scalars. So every operation in J can have its application controlled w.r.t. how to be spread over the argument. Rank 0 means apply on the scalars, rank 1 means apply on the vectors, and so on. ``` 1 + 2 + 3 + 4 NB. add these things together 10 +/ 1 2 3 4 NB. sum the list by adding its items together 10 i. 3 4 NB. 2D array, with shape 3-by-4 0 1 2 3 4 5 6 7 8 9 10 11 +/"2 i. 3 4 NB. add the items of the matrix together 12 15 18 21 0 1 2 3 + 4 5 6 7 + 8 9 10 11 NB. equivalent 12 15 18 21 +/"1 i. 3 4 NB. now sum each vector! 6 22 38 +/"0 i. 3 4 NB. now sum each scalar! 0 1 2 3 4 5 6 7 8 9 10 11 ``` This becomes very powerful when you introduce dyadic (two-argument) functions, because if the shapes of the two arguments (after accounting for rank) are agreeable, J will do some implicit looping: ``` 10 + 1 NB. scalar addition 11 10 20 30 + 4 5 6 NB. vector addition, pointwise 14 25 36 10 + 4 5 6 NB. looping! 14 15 16 10 20 + 4 5 6 NB. shapes do not agree... |length error | 10 20 +4 5 6 ``` When all your shapes are agreeable and you can specify the rank yourself, there are many ways to combine arguments. Here we show off some of the ways that you can multiply a 2D matrix and a 3D array. ``` n =: i. 5 5 n 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <"2 n *"2 (5 5 5 $ 1) NB. multiply by 2-cells +--------------+--------------+--------------+--------------+--------------+ | 0 1 2 3 4| 0 1 2 3 4| 0 1 2 3 4| 0 1 2 3 4| 0 1 2 3 4| | 5 6 7 8 9| 5 6 7 8 9| 5 6 7 8 9| 5 6 7 8 9| 5 6 7 8 9| |10 11 12 13 14|10 11 12 13 14|10 11 12 13 14|10 11 12 13 14|10 11 12 13 14| |15 16 17 18 19|15 16 17 18 19|15 16 17 18 19|15 16 17 18 19|15 16 17 18 19| |20 21 22 23 24|20 21 22 23 24|20 21 22 23 24|20 21 22 23 24|20 21 22 23 24| +--------------+--------------+--------------+--------------+--------------+ <"2 n *"1 (5 5 5 $ 1) NB. multiply by vectors +---------+---------+--------------+--------------+--------------+ |0 1 2 3 4|5 6 7 8 9|10 11 12 13 14|15 16 17 18 19|20 21 22 23 24| |0 1 2 3 4|5 6 7 8 9|10 11 12 13 14|15 16 17 18 19|20 21 22 23 24| |0 1 2 3 4|5 6 7 8 9|10 11 12 13 14|15 16 17 18 19|20 21 22 23 24| |0 1 2 3 4|5 6 7 8 9|10 11 12 13 14|15 16 17 18 19|20 21 22 23 24| |0 1 2 3 4|5 6 7 8 9|10 11 12 13 14|15 16 17 18 19|20 21 22 23 24| +---------+---------+--------------+--------------+--------------+ <"2 n *"0 (5 5 5 $ 1) NB. multiply by scalars +---------+---------+--------------+--------------+--------------+ |0 0 0 0 0|5 5 5 5 5|10 10 10 10 10|15 15 15 15 15|20 20 20 20 20| |1 1 1 1 1|6 6 6 6 6|11 11 11 11 11|16 16 16 16 16|21 21 21 21 21| |2 2 2 2 2|7 7 7 7 7|12 12 12 12 12|17 17 17 17 17|22 22 22 22 22| |3 3 3 3 3|8 8 8 8 8|13 13 13 13 13|18 18 18 18 18|23 23 23 23 23| |4 4 4 4 4|9 9 9 9 9|14 14 14 14 14|19 19 19 19 19|24 24 24 24 24| +---------+---------+--------------+--------------+--------------+ ``` You'll notice that this doesn't actually carve in the letters in the orientation the question asks for, it just writes them in however is convenient for rank logic. Unless we reverse or rotate the letters before we apply them, it won't work right. But correcting things like that would take up precious characters, so instead we'll encode the letters such that, when J carves them in naturally, *some* triple of faces will be in the correct orientations and relative positions. It turns out the shortest solution is to rotate all the letterforms a quarter-turn counterclockwise. Considering J's third dimension to represent the front-to-back axis, the crude diagram below shows why this scheme works. ![visualization of cube](https://i.stack.imgur.com/VeiVy.png) Figure A: The three sides of the cube that J carves into. Figure B: The three sides which have the letters oriented like the question asks. This choice in encoding saves 12 characters over the previous method, and makes the whole thing neater. The actual golf creates the cube out of the `"1` and `"2` carves with some funky logic, due to an unrelated optimization. Then we have to check the faces. Since we encode the block as 1s and 0s, we can just sum along each axis in the way we want (these are the `+/"1`, `+/"2`, and `+/` bits), adjust to booleans (`0<`), and then compare them all directly to the original 90°-turned-letters. The compression scheme encodes each 5px row of each letter as the base 32 representation of a binary number. By exploiting a number of syntactic sugars and operator overloadings, `".'1b',"#:` is the shortest way to turn the list of characters into base 36 numbers. Well, technically, base 32, but J thinks it's unary, so who's counting? Usage is below. Note that strings are character arrays in J, so a three item list `'A','B','C'` can be written `'ABC'` for short. Also, booleans are 1/0. ``` NB. can be used inline... (_5#:\".'1b',"#:'fiiifalllvhhhheehhhvhhllvgkkkvnlhhvv444vhhvhhggvhjha44v1111vv848vv248vehhheciiivfjhhedmkkvilll9ggvggu111uo616ou121uha4ahg878ghpljh')((-:0<+/"1,+/"2,:+/)*`(*"1/)/)@:{~_65+3&u:'BEG' 1 NB. or assigned to a name geb=:(_5#:\".'1b',"#:'fiiifalllvhhhheehhhvhhllvgkkkvnlhhvv444vhhvhhggvhjha44v1111vv848vv248vehhheciiivfjhhedmkkvilll9ggvggu111uo616ou121uha4ahg878ghpljh')((-:0<+/"1,+/"2,:+/)*`(*"1/)/)@:{~_65+3&u: geb 'BGE' 0 ``` [Answer] # Python, ~~687~~ ~~682~~ 671 ``` import itertools as t,bz2 s=range(5) c=dict([(i,1)for i in t.product(*3*[s])]) z=dict([(chr(i+65),[map(int,bz2.decompress('QlpoOTFBWSZTWXndUmsAATjYAGAQQABgADABGkAlPJU0GACEkjwP0TQlK9lxsG7aomrsbpyyosGdpR6HFVZM8bntihQctsSiOLrWKHHuO7ueAyiR6zRgxbMOLU2IQyhAEAdIJYB0ITlZwUqUlAzEylBsw41g9JyLx6RdFFDQEVJMBTQUcoH0DEPQ8hBhXBIYkXDmCF6E/F3JFOFCQed1Saw='.decode('base64')).split('\n')[j].split()[i])for j in s])for i in range(26)]) def m(a,g): for e in c:c[e]&=g[e[a]][e[a-2]] def f(a): g=map(list,[[0]*5]*5) for e in c:g[e[a]][e[a-2]]|=c[e] return g r=lambda g:map(list,zip(*g)[::-1]) def v(T,L,R):T,L,R=r(r(z[T])),r(z[L]),z[R];m(1,T);m(2,L);m(0,R);return(T,L,R)==(f(1),f(2),f(0)) ``` Call with `v`: ``` v('B','E','G') => True v('B','G','E') => False ``` Everything below is from my previous ungolfed version which includes helpful drawing functions. Feel free to use it as a jumping off point. ``` import string as s import itertools as t az = """01110 11110 01111 11110 11111 11111 11111 10001 11111 11111 10001 10000 10001 10001 01110 11110 01110 11110 01111 11111 10001 10001 10001 10001 10001 11111 10001 10001 10000 10001 10000 10000 10000 10001 00100 00100 10010 10000 11011 11001 10001 10001 10001 10001 10000 00100 10001 10001 10001 01010 01010 00010 10001 11110 10000 10001 11100 11110 10011 11111 00100 00100 11100 10000 10101 10101 10001 10001 10001 11111 01110 00100 10001 01010 10001 00100 00100 00100 11111 10001 10000 10001 10000 10000 10001 10001 00100 10100 10010 10000 10001 10011 10001 11110 10011 10010 00001 00100 10001 01010 10101 01010 00100 01000 10001 11110 01111 11110 11111 10000 11111 10001 11111 11100 10001 11111 10001 10001 01110 10000 01111 10001 11110 00100 01110 00100 01010 10001 00100 11111""".split('\n') dim = range(len(az)) az = dict([(c, [map(int, az[j].split()[i]) for j in dim]) for i, c in enumerate(s.uppercase)]) cube = dict([(i, 1) for i in t.product(*3*[dim])]) def mask(axis, grid): for c in cube: if not grid[c[axis]][c[axis - 2]]: cube[c] = 0 def face(axis): grid = [[0 for j in dim] for i in dim] for c in cube: if cube[c]: grid[c[axis]][c[axis - 2]] = 1 return grid def rot(grid): return map(list, zip(*grid)[::-1]) def draw(grid, filled='X', empty=' '): s = '' for y in dim: for x in dim: s += filled if grid[y][x] else empty s += '\n' print s def drawAll(): print 'TOP:\n' draw(rot(rot(face(1)))) print 'LEFT:\n' draw(rot(rot(rot(face(2))))) print 'RIGHT:\n' draw(face(0)) def valid(top, left, right): top, left, right = rot(rot(az[top])), rot(az[left]), az[right] mask(1, top) mask(2, left) mask(0, right) return top == face(1)and left == face(2) and right == face(0) letters = 'BEG' if valid(*letters): print letters, 'is valid.\n' else: print letters, 'is not valid!\n' drawAll() ``` Call `valid` to run it: ``` valid('B', 'E', 'G') #returns True valid('B', 'G', 'E') #returns False ``` Right now the code is setup to test the validity of `B E G` and print out the resulting faces: ``` BEG is valid. TOP: XXXX X X XXXX X X XXXX LEFT: XXXXX X XXX X XXXXX RIGHT: XXXXX X X XX X X XXXXX ``` Running it on `B G E` we can see that the G is incorrect: ``` BGE is not valid! TOP: XXXX X X XXXX X X XXXX LEFT: XXXXX X X XX X XXXXX RIGHT: XXXXX X XXX X XXXXX ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 150 [bytes](https://github.com/abrudz/SBCS) ``` x y z←(⎕A⍳⍞)⌷¨⊂26 5 5⍴(8⍴2)⊤⎕AV⍳'5∘⍉⍉c∨wÌþ∩⍀ýFó  â⍒⍪┤ÌÙÍ⊃?>áóU│yEå≥∧+├Û└KEÐ┐⌹;⍉ùigë/⋄⍪,ËwÙ4○$⊣7×c⍺þS¢|⍋îÜ⍀â:b⌷Î' (x,y,z)≡(∨⌿,∨⌿⍤2,∨/)x×⍤2⊢z∘.×⍤1⊢y ``` [Try it online!](https://tio.run/##RVBdS8JgFMbb/YUu2kXgRitpZEVBUbBUuoy6N0MJhLrTjS7Covb1yoiFSRK6JllBNwvCIIOdf/L8EXtnYIfDOc/DeThfxbPqwrFerJ5WxjBvyuO6qIsGrj0JzbttsAjsUYb7GQ9gN9QVMStmwT6kNR5UGXaYqA65LJ2FeQ9mcS/BHNTIpRHMF7CLFH3vUhR34y4FYLdgr/BDXm4Tg325tUk9ig7gN/QZjfqw@jCf5@F36AG@v6eRB9@DO9zgjWl4UqG3DJwr3kQhp0btZbSc1Bzsp1VqlcC@aLQfB@dgziy9U4dPp2D9iK9PzbQg1RVdMWRYPYlvCPdH@UtgoZrAjFynVkJgBwa/ZnHCljjTk9eMxYmVhR0tJ0xxTpvifL7wjwv5Xw "APL (Dyalog Unicode) – Try It Online") A full program that takes three uppercase letters from stdin and prints 0 (false) or 1 (true) to stdout. We already have [an answer in J](https://codegolf.stackexchange.com/a/34877/78410) which has an excellent primer on multi-dimensional arrays and function rank. This answer uses the same concept. (Plus an obvious advantage that we can efficiently encode the binary arrays using the single-byte character encoding.) ### How it works ``` ⍝ Extract the three bit matrices x y z←(⎕A⍳⍞)⌷¨⊂26 5 5⍴(8⍴2)⊤⎕AV⍳'5∘⍉⍉c∨wÌþ∩⍀ýFó  â⍒⍪┤ÌÙÍ⊃?>áóU│yEå≥∧+├Û└KEÐ┐⌹;⍉ùigë/⋄⍪,ËwÙ4○$⊣7×c⍺þS¢|⍋îÜ⍀â:b⌷Î' ⎕AV⍳'...' ⍝ Char value of each char w.r.t. the code page (8⍴2)⊤ ⍝ Convert each number to 8 bits, making 8-row matrix 26 5 5⍴ ⍝ Take the bits and form 26×5×5 brick (⎕A⍳⍞)⌷¨⊂ ⍝ Take 3-char input and extract the corresponding 5×5 matrices x y z← ⍝ Assign to three variables (x,y,z)≡(∨⌿,∨⌿⍤2,∨/)x×⍤2⊢z∘.×⍤1⊢y z∘.×⍤1⊢y ⍝ Combine front and right faces ⍝ so that three dimensions are oriented naturally x×⍤2⊢ ⍝ Combine the top face (∨⌿,∨⌿⍤2,∨/) ⍝ Compute the top, front, and right views of the pixels (x,y,z)≡ ⍝ Check if they all match the original faces ``` [Answer] # Python 3 + numpy, 327C ``` from numpy import* B=hstack([ord(x)>>i&1for x in'옮弟ჹ羂옱쏷)ជ࿂︹缘龌ℿ쓥剴ℌᾄ起츱ꎚㆋឺ௣옮忬⧼ﯠႄ挒⺌ꕆ豈ꪱ袨冊䈑∾Ϣ'for i in range(16)])[:-6].reshape(26,5,5) T=transpose def f(*X): A=ones((5,5,5));F=list(zip([A,T(A,(1,0,2)),T(fliplr(A),(2,0,1))],[B[ord(x)-65]for x in X])) for r,f in F:r[array([f]*5)==0]=0 return all([all(r.sum(0)>=f)for r,f in F]) ``` This golf solution need an external library, numpy, which is quite popular so I think it's fine to use it. The unicode string is in 41 chars, while the same thing in @fabian's prolog answer is 44. The most interesting here is that the indexing of numpy array. In `a[ix]`, `ix` can be an boolean array with the same shape as `a`. It's the same as saying `a[i, j, k] where ix[i, j, k] == True`. ## Ungolfed Version ``` import numpy as np table = '옮弟ჹ羂옱쏷)ជ࿂︹缘龌ℿ쓥剴ℌᾄ起츱ꎚㆋឺ௣옮忬⧼ﯠႄ挒⺌ꕆ豈ꪱ袨冊䈑∾Ϣ' def expand_bits(x): return [ord(x) >> i & 1 for i in range(16)] # B.shape = (26, 5, 5), B[i] is the letter image matrix of the i(th) char B = np.hstack([expand_bits(x) for x in table])[:-6].reshape(26, 5, 5) def f(*chars): """ cube: ---------- axis: / /| --------->2 / 1 / | /| / / | / | / / | / | |---------| 3 | v | | | / 1 | | 2 | / v | | / 0 | | / ----------- """ cube = np.ones((5, 5, 5)) cube_views = [ cube, cube.transpose((1, 0, 2)), # rotate to make face 2 as face 1 np.fliplr(cube).transpose(2, 0, 1), # rotate to make face 3 as face 1 ] faces = [B[ord(char) - ord('A')] for char in chars] # mark all white pixels as 0 in cube for cube_view, face in zip(cube_views, faces): # extrude face to create extractor extractor = np.array([face] * 5) cube_view[extractor == 0] = 0 return np.all([ # cube_view.sum(0): sum along the first axis np.all(cube_view.sum(0) >= face) for cube_view, face in zip(cube_views, faces) ]) ``` ## Script to compress table ``` import numpy as np def make_chars(): s = """ 01110 11110 01111 11110 11111 11111 11111 10001 11111 11111 10001 10000 10001 10001 01110 11110 01110 11110 01111 11111 10001 10001 10001 10001 10001 11111 10001 10001 10000 10001 10000 10000 10000 10001 00100 00100 10010 10000 11011 11001 10001 10001 10001 10001 10000 00100 10001 10001 10001 01010 01010 00010 10001 11110 10000 10001 11100 11110 10011 11111 00100 00100 11100 10000 10101 10101 10001 10001 10001 11111 01110 00100 10001 01010 10001 00100 00100 00100 11111 10001 10000 10001 10000 10000 10001 10001 00100 10100 10010 10000 10001 10011 10001 11110 10011 10010 00001 00100 10001 01010 10101 01010 00100 01000 10001 11110 01111 11110 11111 10000 11111 10001 11111 11100 10001 11111 10001 10001 01110 10000 01111 10001 11110 00100 01110 00100 01010 10001 00100 11111 """.strip().split('\n') bits = np.zeros((26, 5, 5), dtype=np.bool) for c_id in range(26): for i in range(5): for j in range(5): bits[c_id, i, j] = s[i][j + c_id * 7] == '1' bits = np.hstack([bits.flat, [0] * 7]) bytes_ = bytearray() for i in range(0, len(bits) - 8, 8): x = 0 for j in range(8): x |= bits[i + j] << j bytes_.append(x) chars = bytes_.decode('utf16') return chars ``` ]
[Question] [ A snakified string looks like this: ``` T AnE eOf ifi ing h s x l A k e r isI amp Sna dSt ``` ## Your Task Take a string `s` and a size `n`, then output the snakified string. The inputs `ThisIsAnExampleOfaSnakifiedString` and `3` would produce the example above. ## Specifications * `s` will only contain ASCII characters between code points 33 and 126 inclusive (no spaces or newlines). * `s` will be between 1 and 100 characters long. * `n` is an integer representing the size of each output string segment. Each line of characters (up/down or left/right) that make up the curves in the "snake" is `n` characters long. See the test cases for examples. * `n` will be between 3 and 10 inclusive. * The output string always starts pointing downwards. * Trailing spaces on each line are allowed. * Trailing newlines at the end of the output are also allowed. * Leading spaces are not allowed. * [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") means shortest code in bytes wins. ## Test Cases ``` a 3 a ---------- Hello,World! 3 H Wor e , l llo d! ---------- ProgrammingPuzzlesAndCodeGolf 4 P ngPu Code r i z d G o m z n o gram lesA lf ---------- IHopeYourProgramWorksForInputStringsWhichAre100CharactersLongBecauseThisTestCaseWillFailIfItDoesNot. 5 I gramW tStri 100Ch gBeca CaseW DoesN H o o u n e a n u t i t o o r r p g r r o s s l I t p P k n s A a L e e l f . eYour sForI Which cters ThisT FailI ---------- !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ 10 ! <=>?@ABCDE `abcdefghi " ; F _ j # : G ^ k $ 9 H ] l % 8 I \ m & 7 J [ n ' 6 K Z o ~ ( 5 L Y p } ) 4 M X q | *+,-./0123 NOPQRSTUVW rstuvwxyz{ ``` [Answer] # Ruby, 87 bytes ``` ->s,n{p=0 a=(' '*(w=s.size)+$/)*n w.times{|i|a[p]=s[i];p+=[w+1,1,-w-1,1][i/(n-1)%4]} a} ``` Some minor abuse of the rule `Trailing spaces on each line are allowed.` Each line of output is `w` characters long, plus a newline, where `w` is the length of the original string, i.e. long enough to hold the whole input. Hence there is quite a lot of unnecessary whitespace to the right for large `n`. **Ungolfed in test program** ``` f=->s,n{ p=0 #pointer to where the next character must be plotted to a=(' '*(w=s.size)+$/)*n #w=length of input. make a string of n lines of w spaces, newline terminated w.times{|i| #for each character in the input (index i) a[p]=s[i] #copy the character to the position of the pointer p+=[w+1,1,-w-1,1][i/(n-1)%4] #move down,right,up,right and repeat. change direction every n-1 characters } a} #return a puts $/,f['a',3] puts $/,f['Hello,World!',3] puts $/,f['ProgrammingPuzzlesAndCodeGolf',4] puts $/,f['IHopeYourProgramWorksForInputStringsWhichAre100CharactersLongBecauseThisTestCaseWillFailIfItDoesNot.',5] puts $/,f['!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~',10] ``` [Answer] # Pyth, ~~48~~ ~~45~~ ~~44~~ ~~43~~ 42 bytes ``` =Y0juXGZX@G~+Z-!J%/HtQ4q2J~+Y%J2@zHlzm*;lz ``` [Try it online.](https://pyth.herokuapp.com/?code=%3DY0juXGZX%40G%7E%2BZ-!J%25%2FHtQ4q2J%7E%2BY%25J2%40zHlzm*%3Blz&input=5%0AIHopeYourProgramWorksForInputStringsWhichAre100CharactersLongBecauseThisTestCaseWillFailIfItDoesNot&debug=0) This approach does the same trailing whitespace abuse as the Ruby answer. [Answer] ## JavaScript (ES6), 143 bytes ``` (s,n)=>[...s].map((c,i)=>(a[x][y]=c,i/=n)&1?y++:i&2?x--:x++,a=[...Array(n--)].map(_=>[]),x=y=0)&&a.map(b=>[...b].map(c=>c||' ').join``).join`\n` ``` Where `\n` represents a literal newline. Ungolfed: ``` function snakify(string, width) { var i; var result = new Array(width); for (i = 0; i < width; i++) result[i] = []; var x = 0; var y = 0; for (i = 0; i < string.length; i++) { result[x][y] = string[i]; switch (i / (width - 1) & 3) { case 0: x++; break; case 1: y++; break; case 2: x--; break; case 3: y++; break; } for (i = 0; i < width; i++) { for (j = 0; j < r[i].length; j++) { if (!r[i][j]) r[i][j] = " "; } r[i] = r[i].join(""); } return r.join("\n"); } ``` [Answer] ## Pyth, ~~85~~ ~~74~~ 59 bytes ~~`Kl@Q0J0=Y*]d-+*@Q1K@Q1 1FNr1@Q1=XY-+*KNN1b;VK=XYJ@@Q0N=+J@[+K1 1-_K1 1).&3/N-@Q1 1;sY`~~ ~~`=G@Q1=H@Q0KlHJ0=Y*]dt+*GKGFNr1G=XYt+*KNNb;VK=XYJ@HN=+J@[hK1t_K1).&3/NtG;sY`~~ ``` Klz=Ym;+*QKQVQ=XYt+*KhNhNb;VK=XYZ@zN=+Z@[hK1_hK1).&3/NtQ;sY ``` Thanks to @FryAmTheEggman for greatly helping me ! Golfed as much as I could. [Try it here !](https://pyth.herokuapp.com/?code=Klz%3DYm%3B%2B%2aQKQVQ%3DXYt%2B%2aKhNhNb%3BVK%3DXYZ%40zN%3D%2BZ%40%5BhK1_hK1%29.%263%2FNtQ%3BsY&input=5%0AIHopeYourProgramWorksForInputStringsWhichAre100CharactersLongBecauseThisTestCaseWillFailIfItDoesNot.&debug=0) For some reason, line wrapping make the output weird. You may want to have a look at the [output on full page](http://hastebin.com/raw/yatacofedi) ## Explanation Breathe a second, and focus. This can be broken down in three sections, like almost any "classic" algorithm. ### The first section It's where variables are initialized. It can be splitted into two parts : ``` Klz=Ym;+*QKQ Klz Assign len(input[0]) to K. (length of input String) =Ym;+*QKQ Assign an empty list to Y of length K*input[1]-input[1]-1, where input[1] is the size of the snake (thus the height of the final string) ``` the second part : ``` VQ=XYt+*KhNhNb; VQ For N in range(0, input[1]), where input[1] is the size of the snake = Assign to Y. Y is implicit, it is the last variable we used. XYt+*KhNhNb Y[K*N+N-1]="\n". Can be broken down in four parts : X Replace function. X <A: list> <B: int> <C: any> is A[B]=C Y A: The array we initialized in the first section. t+*KhNhN B: K*(N+1)+N+1 (N is the for loop variable) b C: Newline character ("\n") ; End the loop. ``` ### The second section It contains the actual logic. ``` VK=XYZ@zN=+Z@[hK1_hK1).&3/NtQ; VK For N in range(0, K), where K is the length of the input string (see first section) = Assign to Y. Y is implicit, it is the last variable we used. XYZ@zN Same as in section 2. This is a replacement function. Y[Z] = input[0][N]. Z is initially 0. =+Z@[hK1_hK1).&3/NtQ Again this can be broken down : =+Z Add to Z [hK1_hK1) Array containing directions. Respectively [K+1, 1, -K-1, 1] @ .&3/NtQ Lookup in the array, on index .&3/N-@Q1 1: .&3 Bitwise AND. .& <int> <int> /NtQ (input[1]-1)/N, where input[1] is the size of the snake ; End the loop ``` ### The third section This is the output part. Not really interesting... ``` sY Join the array Y. Implicitly print. ``` ## BONUS I wrote the pyth program from this python script. ``` input=["ThisIsAnExampleOfASnakifiedString", 4]; width=len(input[0]); height=input[1]; pointer=0; directions = [width+1,1,-width-1,1] #Respectively Down, right, up, right (left is replaced by right because of snake's nature. Doesn't go left). output=[' ' for i in range(0, width*height+height-1)]; for N in range(1, height): output[width*N+N-1]="\n"; for N in range(0, len(input[0])): output[pointer]=input[0][N]; pointer+=directions[3&(N/(height-1))]; print "".join(output); ``` [Answer] # JavaScript (ES6), 122 bytes ``` document.write("<pre>"+( // --- Solution --- s=>n=>[...s].map((c,i)=>(a[p]=c,p+=[l+1,1,-l-1,1][i/n%4|0]),p=0,a=[...(" ".repeat(l=s.length)+` `).repeat(n--)])&&a.join`` // ---------------- )("IHopeYourProgramWorksForInputStringsWhichAre100CharactersLongBecauseThisTestCaseWillFailIfItDoesNot.")(5)) ``` Same algorithm as @LevelRiverSt's answer. [Answer] # C, 138 bytes ``` char*h[]={"\e[B\e[D","","\e[A\e[D",""},t[999];i;main(n){system("clear");for(scanf("%s%d",t,&n),--n;t[i];++i)printf("%c%s",t[i],h[i/n%4]);} ``` This uses ANSI escapes. Works in linux terminal. Ungolfed: ``` char*h[]={"\e[B\e[D","","\e[A\e[D",""}, /* cursor movement - h[0] moves the cursor one down and one left, h[2] moves the cursor one up and one left. */ t[999];i; main(n){ system("clear"); for(scanf("%s%d",t,&n),--n;t[i];++i) printf("%c%s",t[i],h[i/n%4]); } ``` [Answer] # JavaScript (ES6), 131 Algorithm: mapping the position `x,y` in output to the index in the input string, somehow like [this](https://codegolf.stackexchange.com/a/77233/21348) (unrelated) answer. I borrowed from @LevelRiverSt the trick of keeping the horizontal width equal to the input length. ``` a=>m=>eval('for(--m,t=y=``;y<=m;++y,t+=`\n`)for(x=0;a[x];)t+=a[2*(x-x%m)+((h=x++%(2*m))?h-m?!y&h>m?h:y<m|h>m?NaN:m+h:m-y:y)]||`.`') ``` **Less golfed** This was the first working draft before golfing ``` f=(a,n)=>{ l=a.length m=n-1 s=m*2 // horizontal period b=-~(~-l/s)*m // total horizontal len, useless in golfed version t='' for(y=0;y<n;y++) { for(x=0;x<b;x++) { k = x / m | 0 h = x % s if (h ==0 ) c=k*s+y else if (h == m) c=k*s+m-y else if (y == 0 && h>m) c=k*s+h else if (y == m && h<m) c=k*s+m+h else c=-1 t+=a[c]||' ' } t+='\n' } return t } ``` **Test** ``` F=a=>m=>eval('for(--m,t=y=``;y<=m;++y,t+=`\n`)for(x=0;a[x];)t+=a[2*(x-x%m)+((h=x++%(2*m))?h-m?!y&h>m?h:y<m|h>m?NaN:m+h:m-y:y)]||` `') function test() { var n=+N.value var s=S.value O.textContent=F(s)(n) } test() ``` ``` #S {width:80%} #N {width:5%} ``` ``` <input id=N value=5 type=number oninput='test()'> <input id=S 5 oninput='test()' value='IHopeYourProgramWorksForInputStringsWhichAre100CharactersLongBecauseThisTestCaseWillFailIfItDoesNot.'> <pre id=O></pre> ``` [Answer] ## Pyth, 122 bytes ``` =k@Q0J-@Q1 1K*4J=T*@Q1[*lkd;Vlk=Z+*%NJ/%N*J2J*/N*J2J=Y.a-+**/%N*J2J!/%NK*J2J*%NJ!/%N*J2J**!/%N*J2J/%NK*J2J XTYX@TYZ@kN;jbT ``` I've made a formula to calculate the x, y positions of each character based on the segment size / modulo, but they got larger than I expected :c Explanation: ``` =k@Q0 # Initialize var with the text J-@Q1 1 # Initialize var with the segment size (minus 1) K*4J # Initialize var with the "block" size (where the pattern start to repeat) =T*@Q1[*lkd; # Initialize output var with an empty array of strings Vlk # Interate over the text =Z+*%NJ/%N*J2J*/N*J2J # Matemagics to calculate X position =Y.a-+**/%N*J2J!/%NK*J2J*%NJ!/%N*J2J**!/%N*J2J/%NK*J2J # Matemagics to calculate Y position XTYX@TYZ@kN; # Assign the letter being iterated at x,y in the output jbT # Join with newlines and print the output ``` [Test here](https://pyth.herokuapp.com/?code=%3Dk%40Q0J-%40Q1%201K*4J%3DT*%40Q1[*lkd%3BVlk%3DZ%2B*%25NJ%2F%25N*J2J*%2FN*J2J%3DY.a-%2B**%2F%25N*J2J!%2F%25NK*J2J*%25NJ!%2F%25N*J2J**!%2F%25N*J2J%2F%25NK*J2J%20XTYX%40TYZ%40kN%3BjbT&input=[%22IHopeYourProgramWorksForInputStringsWhichAre100CharactersLongBecauseThisTestCaseWillFailIfItDoesNot.%22%2C5]&test_suite=1&test_suite_input=[%22a%22%2C%203]%0A[%22Hello%2CWorld!%22%2C%203]%0A[%22ProgrammingPuzzlesAndCodeGolf%22%2C%204]%0A[%22IHopeYourProgramWorksForInputStringsWhichAre100CharactersLongBecauseThisTestCaseWillFailIfItDoesNot.%22%2C%205]%0A[%22!%5C%22%23%24%25%26%27%28%29*%2B%2C-.%2F0123456789%3A%3B%3C%3D%3E%3F%40ABCDEFGHIJKLMNOPQRSTUVWXYZ[%5C]%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D~%22%2C%2010]&debug=0) For the Math formulas, I used mod to generate 0/1 flags and then multiplied by a factor based on the input `n`, added the spreadsheet with each step on the snippet bellow ``` td{padding-top:1px;padding-right:1px;padding-left:1px;color:black;font-size:11.0pt;font-weight:400;font-style:normal;text-decoration:none;font-family:Calibri,sans-serif}.x1{text-align:general;vertical-align:bottom;white-space:nowrap}.x2{text-align:general;vertical-align:bottom;border-right:.5pt solid gray;border-bottom:.5pt solid gray;border-left:.5pt solid gray;white-space:nowrap}.x3{text-align:general;vertical-align:bottom;border-top:.5pt solid gray;border-right:.5pt solid gray;border-bottom:.5pt solid gray;border-left:.5pt solid windowtext;white-space:nowrap}.x4{text-align:general;vertical-align:bottom;border:.5pt solid gray;white-space:nowrap}.x5{text-align:general;vertical-align:bottom;border:.5pt solid gray;background:#c5d9f1;white-space:nowrap}.x6{text-align:general;vertical-align:bottom;border:.5pt solid gray;background:#ebf1de;white-space:nowrap}.x7{text-align:general;vertical-align:bottom;border-top:.5pt solid gray;border-right:.5pt solid windowtext;border-bottom:.5pt solid gray;border-left:.5pt solid gray;background:#ebf1de;white-space:nowrap}.x8{text-align:general;vertical-align:bottom;border-top:.5pt solid gray;border-right:.5pt solid gray;border-bottom:.5pt solid gray;border-left:.5pt solid windowtext;background:#d9d9d9;white-space:nowrap}.x9{text-align:general;vertical-align:bottom;border:.5pt solid gray;background:#d9d9d9;white-space:nowrap}.x10{text-align:right;vertical-align:bottom;border:.5pt solid gray;white-space:nowrap}.x11{text-align:general;vertical-align:bottom;border-top:.5pt solid gray;border-right:.5pt solid gray;border-bottom:.5pt solid windowtext;border-left:.5pt solid windowtext;background:#d9d9d9;white-space:nowrap}.x12{text-align:general;vertical-align:bottom;border-top:.5pt solid gray;border-right:.5pt solid gray;border-bottom:.5pt solid windowtext;border-left:.5pt solid gray;background:#d9d9d9;white-space:nowrap}.x13{text-align:right;vertical-align:bottom;border-top:.5pt solid gray;border-right:.5pt solid gray;border-bottom:.5pt solid windowtext;border-left:.5pt solid gray;white-space:nowrap}.x14{text-align:general;vertical-align:bottom;border-top:.5pt solid gray;border-right:.5pt solid gray;border-bottom:.5pt solid windowtext;border-left:.5pt solid gray;white-space:nowrap}.x15{text-align:general;vertical-align:bottom;border-top:.5pt solid gray;border-right:.5pt solid gray;border-bottom:.5pt solid windowtext;border-left:.5pt solid gray;background:#c5d9f1;white-space:nowrap}.x16{text-align:general;vertical-align:bottom;border-top:.5pt solid gray;border-right:.5pt solid gray;border-bottom:.5pt solid windowtext;border-left:.5pt solid gray;background:#ebf1de;white-space:nowrap}.x17{text-align:general;vertical-align:bottom;border-top:.5pt solid gray;border-right:.5pt solid windowtext;border-bottom:.5pt solid windowtext;border-left:.5pt solid gray;background:#ebf1de;white-space:nowrap}.x18{text-align:general;vertical-align:bottom;border-right:.5pt solid gray;border-bottom:0;border-left:.5pt solid gray;white-space:nowrap}.x19{text-align:general;vertical-align:bottom;border-right:.5pt solid gray;border-bottom:.5pt solid gray;border-left:.5pt solid windowtext;white-space:nowrap}.x20{text-align:general;vertical-align:bottom;border-right:.5pt solid gray;border-bottom:.5pt solid gray;border-left:.5pt solid gray;background:#c5d9f1;white-space:nowrap}.x21{text-align:general;vertical-align:bottom;border-right:.5pt solid gray;border-bottom:.5pt solid gray;border-left:.5pt solid gray;background:#ebf1de;white-space:nowrap}.x22{text-align:general;vertical-align:bottom;border-right:.5pt solid windowtext;border-bottom:.5pt solid gray;border-left:.5pt solid gray;background:#ebf1de;white-space:nowrap}.x23{text-align:center;vertical-align:bottom;border:.5pt solid windowtext;white-space:nowrap}.x24{text-align:center;vertical-align:bottom;border-right:.5pt solid windowtext;border-bottom:0;border-left:.5pt solid windowtext;white-space:nowrap} ``` ``` <table style="border-collapse:collapse;table-layout:fixed;width:761pt" border="0" cellpadding="0" cellspacing="0" width="1015"> <colgroup><col style="width:16pt" width="21"> <col style="mso-width-alt:2742;width:56pt" span="2" width="75"> <col style="width:23pt" width="31"> <col style="width:50pt" width="67"> <col style="width:60pt" width="80"> <col style="width:85pt" width="113"> <col style="width:26pt" width="35"> <col style="width:41pt" width="54"> <col style="width:29pt" width="39"> <col style="width:41pt" width="55"> <col style="width:104pt" width="138"> <col style="width:29pt" width="39"> <col style="width:41pt" width="54"> <col style="width:65pt" width="87"> <col style="width:39pt" width="52"> </colgroup><tbody><tr style="height:15.0pt" height="20"> <td class="x23" style="height:15.0pt;width:16pt" width="21" height="20">d</td> <td class="x23" style="width:56pt" width="75">e</td> <td class="x23" style="width:56pt" width="75">f</td> <td class="x24" style="width:23pt" width="31">&nbsp;</td> <td class="x23" style="width:50pt" width="67">h</td> <td class="x23" style="width:60pt" width="80">i</td> <td class="x23" style="width:85pt" width="113">j</td> <td class="x23" style="width:26pt" width="35">k</td> <td class="x23" style="width:41pt" width="54">l</td> <td class="x23" style="width:29pt" width="39">m</td> <td class="x23" style="width:41pt" width="55">n</td> <td class="x23" style="width:104pt" width="138">o</td> <td class="x23" style="width:29pt" width="39">p</td> <td class="x23" style="width:41pt" width="54">q</td> <td class="x23" style="width:65pt" width="87">r</td> <td class="x23" style="width:39pt" width="52">s</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x23" style="height:15.0pt" height="20">i</td> <td class="x23">expected x</td> <td class="x23">expected y</td> <td class="x24" style="">&nbsp;</td> <td class="x23">pos % seg</td> <td class="x23">pos/(seg*2)</td> <td class="x23">pos%(seg*2)/seg</td> <td class="x23">not j</td> <td class="x23">seg*i+h</td> <td class="x23">i*seg</td> <td class="x23">j*l+k*m</td> <td class="x23">pos%(seg*4)/(seg*2)</td> <td class="x23">not o</td> <td class="x23">j*p*seg</td> <td class="x23">abs(o*seg-h)</td> <td class="x23">q*j+r*k</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x19" style="height:15.0pt" align="right" height="20">0</td> <td class="x2" style="" align="right">0</td> <td class="x2" style="" align="right">0</td> <td class="x18" style="">&nbsp;</td> <td class="x2" style="" align="right">0</td> <td class="x2" style="" align="right">0</td> <td class="x2" style="" align="right">0</td> <td class="x2" style="" align="right">1</td> <td class="x2" style="" align="right">0</td> <td class="x20" style="" align="right">0</td> <td class="x21" style="" align="right">0</td> <td class="x2" style="" align="right">0</td> <td class="x2" style="" align="right">1</td> <td class="x2" style="" align="right">0</td> <td class="x20" style="" align="right">0</td> <td class="x22" style="" align="right">0</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x3" style="height:15.0pt;border-top:none" align="right" height="20">1</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x18" style="">&nbsp;</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x4" align="right">1</td> <td class="x5" align="right">0</td> <td class="x6" align="right">0</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x5" align="right">1</td> <td class="x7" align="right">1</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x3" style="height:15.0pt;border-top:none" align="right" height="20">2</td> <td class="x4" align="right">0</td> <td class="x4" align="right">2</td> <td class="x18" style="">&nbsp;</td> <td class="x4" align="right">2</td> <td class="x4" align="right">0</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x4" align="right">2</td> <td class="x5" align="right">0</td> <td class="x6" align="right">0</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x5" align="right">2</td> <td class="x7" align="right">2</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x8" style="height:15.0pt;border-top:none" align="right" height="20">3</td> <td class="x9" align="right">0</td> <td class="x9" align="right">3</td> <td class="x18" style="">&nbsp;</td> <td class="x10">0</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x5" align="right">0</td> <td class="x4" align="right">0</td> <td class="x6" align="right">0</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x5" align="right">3</td> <td class="x4" align="right">0</td> <td class="x7" align="right">3</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x8" style="height:15.0pt;border-top:none" align="right" height="20">4</td> <td class="x9" align="right">1</td> <td class="x9" align="right">3</td> <td class="x18" style="">&nbsp;</td> <td class="x10">1</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x5" align="right">1</td> <td class="x4" align="right">0</td> <td class="x6" align="right">1</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x5" align="right">3</td> <td class="x4" align="right">1</td> <td class="x7" align="right">3</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x8" style="height:15.0pt;border-top:none" align="right" height="20">5</td> <td class="x9" align="right">2</td> <td class="x9" align="right">3</td> <td class="x18" style="">&nbsp;</td> <td class="x10">2</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x5" align="right">2</td> <td class="x4" align="right">0</td> <td class="x6" align="right">2</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x5" align="right">3</td> <td class="x4" align="right">2</td> <td class="x7" align="right">3</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x3" style="height:15.0pt;border-top:none" align="right" height="20">6</td> <td class="x4" align="right">3</td> <td class="x4" align="right">3</td> <td class="x18" style="">&nbsp;</td> <td class="x10">0</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x4" align="right">3</td> <td class="x5" align="right">3</td> <td class="x6" align="right">3</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x4" align="right">0</td> <td class="x5" align="right">3</td> <td class="x7" align="right">3</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x3" style="height:15.0pt;border-top:none" align="right" height="20">7</td> <td class="x4" align="right">3</td> <td class="x4" align="right">2</td> <td class="x18" style="">&nbsp;</td> <td class="x10">1</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x4" align="right">4</td> <td class="x5" align="right">3</td> <td class="x6" align="right">3</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x4" align="right">0</td> <td class="x5" align="right">2</td> <td class="x7" align="right">2</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x3" style="height:15.0pt;border-top:none" align="right" height="20">8</td> <td class="x4" align="right">3</td> <td class="x4" align="right">1</td> <td class="x18" style="">&nbsp;</td> <td class="x10">2</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x4" align="right">5</td> <td class="x5" align="right">3</td> <td class="x6" align="right">3</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x4" align="right">0</td> <td class="x5" align="right">1</td> <td class="x7" align="right">1</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x8" style="height:15.0pt;border-top:none" align="right" height="20">9</td> <td class="x9" align="right">3</td> <td class="x9" align="right">0</td> <td class="x18" style="">&nbsp;</td> <td class="x10">0</td> <td class="x4" align="right">1</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x5" align="right">3</td> <td class="x4" align="right">3</td> <td class="x6" align="right">3</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x5" align="right">0</td> <td class="x4" align="right">3</td> <td class="x7" align="right">0</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x8" style="height:15.0pt;border-top:none" align="right" height="20">10</td> <td class="x9" align="right">4</td> <td class="x9" align="right">0</td> <td class="x18" style="">&nbsp;</td> <td class="x10">1</td> <td class="x4" align="right">1</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x5" align="right">4</td> <td class="x4" align="right">3</td> <td class="x6" align="right">4</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x5" align="right">0</td> <td class="x4" align="right">2</td> <td class="x7" align="right">0</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x8" style="height:15.0pt;border-top:none" align="right" height="20">11</td> <td class="x9" align="right">5</td> <td class="x9" align="right">0</td> <td class="x18" style="">&nbsp;</td> <td class="x10">2</td> <td class="x4" align="right">1</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x5" align="right">5</td> <td class="x4" align="right">3</td> <td class="x6" align="right">5</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x5" align="right">0</td> <td class="x4" align="right">1</td> <td class="x7" align="right">0</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x3" style="height:15.0pt;border-top:none" align="right" height="20">12</td> <td class="x4" align="right">6</td> <td class="x4" align="right">0</td> <td class="x18" style="">&nbsp;</td> <td class="x10">0</td> <td class="x4" align="right">2</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x4" align="right">6</td> <td class="x5" align="right">6</td> <td class="x6" align="right">6</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x5" align="right">0</td> <td class="x7" align="right">0</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x3" style="height:15.0pt;border-top:none" align="right" height="20">13</td> <td class="x4" align="right">6</td> <td class="x4" align="right">1</td> <td class="x18" style="">&nbsp;</td> <td class="x10">1</td> <td class="x4" align="right">2</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x4" align="right">7</td> <td class="x5" align="right">6</td> <td class="x6" align="right">6</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x5" align="right">1</td> <td class="x7" align="right">1</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x3" style="height:15.0pt;border-top:none" align="right" height="20">14</td> <td class="x4" align="right">6</td> <td class="x4" align="right">2</td> <td class="x18" style="">&nbsp;</td> <td class="x10">2</td> <td class="x4" align="right">2</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x4" align="right">8</td> <td class="x5" align="right">6</td> <td class="x6" align="right">6</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x5" align="right">2</td> <td class="x7" align="right">2</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x8" style="height:15.0pt;border-top:none" align="right" height="20">15</td> <td class="x9" align="right">6</td> <td class="x9" align="right">3</td> <td class="x18" style="">&nbsp;</td> <td class="x10">0</td> <td class="x4" align="right">2</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x5" align="right">6</td> <td class="x4" align="right">6</td> <td class="x6" align="right">6</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x5" align="right">3</td> <td class="x4" align="right">0</td> <td class="x7" align="right">3</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x8" style="height:15.0pt;border-top:none" align="right" height="20">16</td> <td class="x9" align="right">7</td> <td class="x9" align="right">3</td> <td class="x18" style="">&nbsp;</td> <td class="x10">1</td> <td class="x4" align="right">2</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x5" align="right">7</td> <td class="x4" align="right">6</td> <td class="x6" align="right">7</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x5" align="right">3</td> <td class="x4" align="right">1</td> <td class="x7" align="right">3</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x8" style="height:15.0pt;border-top:none" align="right" height="20">17</td> <td class="x9" align="right">8</td> <td class="x9" align="right">3</td> <td class="x18" style="">&nbsp;</td> <td class="x10">2</td> <td class="x4" align="right">2</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x5" align="right">8</td> <td class="x4" align="right">6</td> <td class="x6" align="right">8</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x5" align="right">3</td> <td class="x4" align="right">2</td> <td class="x7" align="right">3</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x3" style="height:15.0pt;border-top:none" align="right" height="20">18</td> <td class="x4" align="right">9</td> <td class="x4" align="right">3</td> <td class="x18" style="">&nbsp;</td> <td class="x10">0</td> <td class="x4" align="right">3</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x4" align="right">9</td> <td class="x5" align="right">9</td> <td class="x6" align="right">9</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x4" align="right">0</td> <td class="x5" align="right">3</td> <td class="x7" align="right">3</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x3" style="height:15.0pt;border-top:none" align="right" height="20">19</td> <td class="x4" align="right">9</td> <td class="x4" align="right">2</td> <td class="x18" style="">&nbsp;</td> <td class="x10">1</td> <td class="x4" align="right">3</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x4" align="right">10</td> <td class="x5" align="right">9</td> <td class="x6" align="right">9</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x4" align="right">0</td> <td class="x5" align="right">2</td> <td class="x7" align="right">2</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x3" style="height:15.0pt;border-top:none" align="right" height="20">20</td> <td class="x4" align="right">9</td> <td class="x4" align="right">1</td> <td class="x18" style="">&nbsp;</td> <td class="x10">2</td> <td class="x4" align="right">3</td> <td class="x4" align="right">0</td> <td class="x4" align="right">1</td> <td class="x4" align="right">11</td> <td class="x5" align="right">9</td> <td class="x6" align="right">9</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x4" align="right">0</td> <td class="x5" align="right">1</td> <td class="x7" align="right">1</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x8" style="height:15.0pt;border-top:none" align="right" height="20">21</td> <td class="x9" align="right">9</td> <td class="x9" align="right">0</td> <td class="x18" style="">&nbsp;</td> <td class="x10">0</td> <td class="x4" align="right">3</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x5" align="right">9</td> <td class="x4" align="right">9</td> <td class="x6" align="right">9</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x5" align="right">0</td> <td class="x4" align="right">3</td> <td class="x7" align="right">0</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x8" style="height:15.0pt;border-top:none" align="right" height="20">22</td> <td class="x9" align="right">10</td> <td class="x9" align="right">0</td> <td class="x18" style="">&nbsp;</td> <td class="x10">1</td> <td class="x4" align="right">3</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x5" align="right">10</td> <td class="x4" align="right">9</td> <td class="x6" align="right">10</td> <td class="x4" align="right">1</td> <td class="x4" align="right">0</td> <td class="x5" align="right">0</td> <td class="x4" align="right">2</td> <td class="x7" align="right">0</td> </tr> <tr style="height:15.0pt" height="20"> <td class="x11" style="height:15.0pt;border-top:none" align="right" height="20">23</td> <td class="x12" align="right">11</td> <td class="x12" align="right">0</td> <td class="x18" style="">&nbsp;</td> <td class="x13">2</td> <td class="x14" align="right">3</td> <td class="x14" align="right">1</td> <td class="x14" align="right">0</td> <td class="x15" align="right">11</td> <td class="x14" align="right">9</td> <td class="x16" align="right">11</td> <td class="x14" align="right">1</td> <td class="x14" align="right">0</td> <td class="x15" align="right">0</td> <td class="x14" align="right">1</td> <td class="x17" align="right">0</td> </tr> </tr> </tbody></table> ``` [Answer] # PHP, ~~127~~ ~~126~~ ~~124~~ ~~120~~ ~~119~~ ~~118~~ ~~117~~ ~~110~~ 106 bytes Uses ISO-8859-1 encoding. ``` for(;($q=&$o[$y+=$d]||$q=~ÿ)&&~Ï^$q[$x+=!$d]=$argv[1][$a];$a++%($argv[2]-1)?:$d-=-!$y?:1)?><?=join(~õ,$o); ``` Run like this (`-d` added for aesthetics only): ``` php -r 'for(;($q=&$o[$y+=$d]||$q=~ÿ)&&~Ï^$q[$x+=!$d]=$argv[1][$a];$a++%($argv[2]-1)?:$d-=-!$y?:1)?><?=join(~õ,$o);' "Hello W0rld!" 3 2>/dev/null;echo ``` Ungolfed: ``` // Iterate over ... for ( ; // ... the characters of the input string. Prepend `0` so a 0 in the input // becomes truthy. 0 . $char = $argv[1][$a]; // Use modulo to determine the end of a stretch (where direction is // changed). // Change direction (`0` is right, `-1` is up and `1` is down). When // y coordinate is `0`, increment the direction, else decrement. $a++ % ($argv[2] - 1) ?: $direction += $y ? -1 : 1 ) ( // Increase or decrease y coordinate for direction -1 or 1 respectively. // Check whether the array index at new y coordinate is already set. $reference =& $output[$y += $direction] || // If not, create it as a string (otherwise would be array of chars). // Null byte, won't be printed to prevent leading char. $reference = ~ÿ; // Increment x coordinate for direction 0. Set the output char at the // current coordinates to the char of the current iteration. ) & $reference[$x += !$direction] = $char; // Output all lines, separated by a newline. echo join(~õ, $output); ``` ## Tweaks * Saved a byte by using `<` instead of `!=` * Saved 2 bytes by setting the string to `0` at first, so I don't have to prepend another `0` (in case the first output in a line was a `0`), yielding truthy `00`. * Saved 4 bytes by using a reference instead of repeating `$o[$y]` * Saved a byte by using modulo instead of `==` for comparing direction with 1 to change x coordinate * Saved a byte by removing type cast `null` to `int` for string offset, as string offset is cast to int anyway * Saved a byte by using short print tag * Saved 7 bytes by improving the direction logic * Saved 4 bytes by directly assigning the char to prevent intermediate `$c` ]
[Question] [ You are given a string composed with the characters `0123456789+*()`. You can assume that string is always a valid mathematical expression. Your task is to remove the unnecessary parentheses, assuming multiplication has higher priority than addition. The parentheses should be removed only when they are not needed *structurally*: * because of multiplication higher priority: `3+(4*5)` => `3+4*5` * because of multiplication or addition associativity: `3*(4*5)` => `3*4*5` * when they are redundant around an expression: `3*((4+5))` => `3*(4+5)` Parentheses *should be kept* when they could be simplified because of specific number values: * `1*(2+3)` should not be simplified to `1*2+3` * `0*(1+0)` should not be simplified to `0*1+0` Examples: ``` (4*12)+11 ==> 4*12+11 (1+2)*3 ==> (1+2)*3 3*(4*5) ==> 3*4*5 ((((523)))) ==> 523 (1+1) ==> 1+1 1*(2*(3+4)*5)*6 ==> 1*2*(3+4)*5*6 1*(2+3) ==> 1*(2+3) 0*(1+0) ==> 0*(1+0) (((2+92+82)*46*70*(24*62)+(94+25))+6) ==> (2+92+82)*46*70*24*62+94+25+6 ``` [Answer] # Mathematica, ~~105~~ ~~97~~ 91 bytes *-6 bytes thanks to [Roman](https://codegolf.stackexchange.com/users/87058)!* ``` a=StringReplace;ToString@ToExpression@a[#,{"*"->"**","+"->"~~"}]~a~{" ** "->"*","~~"->"+"}& ``` Replaces `+` and `*` with `~~` (`StringExpression`) and `**` (`NonCommutativeMultiply`) respectively, evaluates it, stringifies it, and replaces the operators back. [Answer] # JavaScript (ES6) 163 ~~178~~ **Edit** 15 bytes saved thx @IsmaelMiguel ``` a=>eval(`s=[]${_=';for(b=0;a!=b;a=b.replace(/'}\\(([^()]*)\\)(?=(.?))/,(x,y,z,p)=>~y.indexOf('+')?-s.push(b[p-1]=='*'|z=='*'?x:y):y))b=a;${_}-\\d+/,x=>s[~x]))b=a`) ``` *Less golfed* ``` a=>{ for(s=[],b=''; a!=b; a=b.replace(/\(([^()]*)\)(?=(.?))/,(x,y,z,p)=>y.indexOf('+')<0?y:-s.push(b[p-1]=='*'|z=='*'?x:y))) b=a; for(b=0; a!=b; a=b.replace(/-\d+/,x=>s[~x])) b=a; return a } ``` **Test** ``` f=a=>eval(`s=[]${_=';for(b=0;a!=b;a=b.replace(/'}\\(([^()]*)\\)(?=(.?))/,(x,y,z,p)=>~y.indexOf('+') ?-s.push(b[p-1]=='*'|z=='*'?x:y) :y))b=a;${_}-\\d+/,x=>s[~x]))b=a`) console.log=x=>O.textContent+=x+'\n' test=`(4*12)+11 ==> 4*12+11 (1+2)*3 ==> (1+2)*3 3*(4*5) ==> 3*4*5 ((((523)))) ==> 523 (1+1) ==> 1+1 1*(2*(3+4)*5)*6 ==> 1*2*(3+4)*5*6 1*(2+3) ==> 1*(2+3) 0*(1+0) ==> 0*(1+0) (((2+92+82)*46*70*(24*62)+(94+25))+6) ==> (2+92+82)*46*70*24*62+94+25+6` test.split`\n`.forEach(r=>{ var t,k,x [t,,k]=r.match(/\S+/g) x=f(t) console.log((x==k?'OK ':'KO ')+t+' -> '+x+(x==k?'':' expected '+k)) }) ``` ``` <pre id=O></pre> ``` [Answer] # Python3 + [PEG implementation in Python](https://gist.github.com/orlp/363a4261f6a884311cbbe6a146a3052b), 271 bytes ``` import peg e=lambda o,m=0:o.choice and str(o)or(m and o[1][1]and"("+e(o[1])+")"or e(o[1]))if hasattr(o,"choice")else o[1]and e(o[0],1)+"".join(str(x[0])+e(x[1],1)for x in o[1])or e(o[0]) print(e(peg.compile_grammar('e=f("+"f)*f=p("*"p)*p="("e")"/[0-9]+').parse(input()))) ``` A while back I made a [PEG implementation in Python](https://gist.github.com/orlp/363a4261f6a884311cbbe6a146a3052b). I guess I can use that here. Parses the expression into a tree, and only keeps parenthesis if the child is addition, and the parent is multiplication. [Answer] # Perl, 132 bytes 129 bytes source + 3 for `-p` flag: ``` #!perl -p 0while s!\(([^\(\)]+)\)!$f{++$i}=$1,"_$i"!e;s!_$i!($v=$f{$i})=~/[+]/&&($l.$r)=~/[*]/?"($v)":$v!e while($l,$i,$r)=/(.?)_(\d+)(.?)/ ``` Using: ``` echo "1*(2*(3+4)*5)*6" | perl script.pl ``` [Answer] # Ruby, ~~140~~ 130 bytes 127 bytes source + 3 for `-p` flag: ``` t={} r=?% 0while$_.gsub!(/\(([^()]+)\)/){t[r+=r]=$1;r} 0while$_.gsub!(/%+/){|m|(s=t[m])[?+]&&($'[0]==?*||$`[/\*$/])??(+s+?):s} ``` And ungolfed: ``` tokens = Hash.new key = '%' # convert tokens to token keys in the original string, innermost first 0 while $_.gsub!(/\(([^()]+)\)/) { # find the innermost parenthetical key += key # make a unique key for this token tokens[key] = $1 key # replace the parenthetical with the token key in the original string } # uncomment to see what's going on here # require 'pp' # pp $_ # pp tokens # convert token keys back to tokens, outermost first 0 while $_.gsub!(/%+/) {|key| str = tokens[key] if str['+'] and ($'[0]=='*' or $`[/\*$/]) # test if token needs parens '(' + str + ')' else str end } # -p flag implicity prints $_ ``` [Answer] # Retina, 155 bytes ``` {`\(((\d+|\((((\()|(?<-5>\))|[^()])*(?(5)^))\))(\*(\d+|\((((\()|(?<-10>\))|[^()])*(?(10)^))\)))*)\) $1 (?<!\*)\((((\()|(?<-3>\))|[^()])*(?(3)^))\)(?!\*) $1 ``` [Try it online!](http://retina.tryitonline.net/#code=e2BcKCgoXGQrfFwoKCgoXCgpfCg_PC01PlwpKXxbXigpXSkrKD8oNSleKSlcKSkoXCooXGQrfFwoKCgoXCgpfCg_PC0xMD5cKSl8W14oKV0pKyg_KDEwKV4pKVwpKSkqKVwpCiQxCig_PCFcKilcKCgoKFwoKXwoPzwtMz5cKSl8W14oKV0pKyg_KDMpXikpXCkoPyFcKikKJDE&input=KDEqKDIrMykrNCkqNQ) [Verify all testcases at once.](http://retina.tryitonline.net/#code=JXtgXCgoKFxkK3xcKCgoKFwoKXwoPzwtNT5cKSl8W14oKV0pKyg_KDUpXikpXCkpKFwqKFxkK3xcKCgoKFwoKXwoPzwtMTA-XCkpfFteKCldKSsoPygxMCleKSlcKSkpKilcKQokMQooPzwhXCopXCgoKChcKCl8KD88LTM-XCkpfFteKCldKSsoPygzKV4pKVwpKD8hXCopCiQx&input=KDQqMTIpKzExCigxKzIpKjMKMyooNCo1KQooKCgoNTIzKSkpKQooKDErMikpKzMKKDErMSkKKCgoMis5Mis4MikqNDYqNzAqKDI0KjYyKSsoOTQrMjUpKSs2KQoxKigyKigzKzQpKjUpKjYKKDEqKDIrMykrNCkqNQ&debug=on) ### Explanation The main thing is this code: ``` (((\()|(?<-3>\))|[^()])*(?(3)^) ``` This regex can match any string in which the brackets are balanced, e.g. `1+(2+(3))+4` or `2+3`. For the ease of explanation, let this regex be `B`. Also, let us use `<` and `>` instead for the brackets, as well as `p` and `m` for `\+` and `\*`. The code becomes: ``` {`<((\d+|<B>)(m(\d+|<B>))*)> $1 (?<!m)<B>(?!m) $1 ``` The first two lines match for brackets which consist of only multiplication, e.g. `(1*2*3)` or even `(1*(2+3)*4)`. They are replaced by their content inside. The last two lines match for brackets which are not preceded and which are not followed by multiplication. They are replaced by their content inside. The initial `{`` means "replace until idempotent", meaning that the replacements are done until they either no longer match or they are replaced with themselves. In this case, the replacements are done until they no longer match. [Answer] # Python 3, ~~274~~ ~~269~~ ~~359~~ ~~337~~ 336 bytes This method basically removes every possible pair of parentheses and checks to see if it still evaluates the same. ``` from re import * def f(x): *n,=sub('\D','',x);x=sub('\d','9',x);v,i,r,l=eval(x),0,lambda d,a,s:d.replace(s,"?",a).replace(s,"",1).replace("?",s),lambda:len(findall('\(',x)) while i<l(): j=0 while j<l(): h=r(r(x,i,"("),j,")") try: if eval(h)==v:i=j=-1;x=h;break except:0 j+=1 i+=1 return sub('9','%s',x)%tuple(n) ``` **Test Harness** ``` print(f("(4*12)+11")=="4*12+11") print(f("(1+2)*3") =="(1+2)*3") print(f("3*(4*5)")=="3*4*5") print(f("((((523))))")=="523") print(f("(1+1)")=="1+1") print(f("1*(2*(3+4)*5)*6")=="1*2*(3+4)*5*6") print(f("(((2+92+82)*46*70*(24*62)+(94+25))+6)")=="(2+92+82)*46*70*24*62+94+25+6") print(f("1*(2+3)")=="1*(2+3)") print(f("0*(1+0)")=="0*(1+0)") ``` **Updates** * **-1** [16-10-04] Removed extra space * **-22** [16-05-07] Made use of the `re` lib * **+90** [16-05-07] Updated to handle the new test cases * **-5** [16-05-07] Removed parameter from the length (`l`) lambda [Answer] **PHP, 358 bytes** ``` function a($a){static$c=[];$d=count($c);while($g=strpos($a,')',$g)){$f=$a;$e=0;for($j=$g;$j;--$j){switch($a[$j]){case')':++$e;break;case'(':--$e;if(!$e)break 2;}}$f[$g++]=$f[$j]=' ';if(eval("return $f;")==eval("return $a;"))$c[str_replace(' ', '', $f)]=1;}if(count($c)>$d){foreach($c as$k=>$v){a($k);}}return$c;}$t=a($argv[1]);krsort($t);echo key($t); ``` Not an impressive length, that's what I get for taking a less than optimal approach (and using a less than optimal language). Strips a pair of brackets out, then evals the resulting expression. If the result is the same as the original it adds it to a map of valid expressions and recurses until no new expressions can be found. Then prints the shortest valid expression. Breaks when the result of the expression gets large and casts to double / exponent notation show up. [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), ~~122~~ 118 bytes ``` T+S:-term_string(T,S). I/O:-X+I,X-Y,Y+O. E-O:-E=A+(B+C),A+B+C-O;E=A*(B*C),A*B*C-O;E=..[P,A,B],A-X,B-Y,O=..[P,X,Y];E=O. ``` [Try it online!](https://tio.run/##bY9Pa4NAEMXP8VOIp92dXZNd/7SxtEWLh5wsTQ5KkBCKDYFEw2qwJ7@6HRMIFN3LLL/35vHmoqtTdRB1e@z7DawD0RT6vKsbfSwPZMPX1DZW8yQQKax4KjKeQWIbsUASv4ZAIvigPAQcInlBwkjEBsJw3Ihtbz95yKOchyLlESYkd5byLEc9sXt9LXff@7og8e9FUzMQxmz4zb@K@npquDH7qfR53xCra03xZnZtV3alxbeDid9NOdY03oX5iLKIy6SiIKWF0n9FgqLMGXGH4Y5Hx358nnIovqksOaaSEcWIAy7FPOZP6uCM9xYM8xaTDRQsFTxjb9dnT@hTLvPxPLJ0QXmUgk@n74RbDdT6Pw "Prolog (SWI) – Try It Online") Defines a predicate `//2` which removes parentheses from its first argument's string value and outputs a string through its second argument. If input could be in Prolog terms, this would only be ~~81~~ 77 bytes defining `+/2` without having to deal with the verbose `term_string/2`, but a lot of unnecessary parentheses would simply not have existed to begin with that way so it would be pretty close to cheating, since all that `+/2` does is handle associativity. I tried to use `=../2` for all of it, but it came out far longer, because a three-byte operator that works with lists isn't exactly terse: # [Prolog (SWI)](http://www.swi-prolog.org), 124 bytes ``` T+S:-term_string(T,S). I/O:-X+I,X-Y,Y+O. X-Y:-X=..[O,A,B],(B=..[O,C,D],E=..[O,A,C],F=..[O,E,D],F-Y;A-C,B-D,Y=..[O,C,D]);X=Y. ``` [Try it online!](https://tio.run/##bU9Na4NQEDzHXyGe3sc@E58fbQxpicZATkKTgxIkhGJDINGgBnvyr9u10paie5qdmR1m70V@zc@irC9tu@c7V1RpcTuWVXHJzmQPO6or22noiohvIRIxxDzUFQTILHX9EMIKvASI1y8@rBMIfgQ/gU2Pg47fiHixEj54Yg3xn58uomWst8UjO76fypQEn/eCqq5QJh2avqXl41qBMvnIi9upIlpTq@JFbeomazINDp0JelOCZZVXof5GacRihqTcMDSU/isGl5SZA95keGPToR/HlibFGcsyhqzBiGTE5BbFPOaM6twc3s0Y5s1GG0g@l/wZe1sOe0KftJiD75G5xaVNKXfo@J/8uwZq7Rc "Prolog (SWI) – Try It Online") ]
[Question] [ Successful code golf submissions are, by nature, filled with crazy symbols all over the place. To make their submission easier to understand, many code-golfers choose to include an explanation of their code. In their explanation, the line of code is turned into a vertically exploded diagram. For example, if this were my code: ``` 1_'[3:~2@+]` ``` One of the many possible diagrams I could create would look like this: ``` 1 _' [ ] [3: ] [ ~ ] [ 2@ ] [ +] ` ``` --- **The Goal** In this challenge, you will write an explanation auto-formatting tool which takes a line of code and creates a diagram to which explanatory text can be easily added. In order to make this a more *useful* challenge, the user will be able to specify the contents of each line, by providing a formatting string. The formatting string will be a second line, containing only letters `A-Za-z`, that is the same length as the program. The letters show the order in which the characters of the program should be printed in the explanation. Here is an example of I/O *without any bracket-like formatting*: ``` 123423 AabcBC 1 2 3 2 3 4 ``` **Brackets** If more than one character in the program has the same priority level, then that set of characters acts as a single block of code (if they form a group) or a set of brackets (if they contain other characters in-between). The general rules are simple: 1. Characters do not appear in a line of the diagram until all other characters of greater priority have already appeared on the lines above it in the diagram. 2. Characters of equal priority are always printed on the same lines. If a certain character appears on a line, all other characters of equal priority appear on the line. 3. A set of characters of equal priority continue to appear on each line until all other characters enclosed by it have appeared at least once. This allows for "bracket-like" constructions. If `bceab` are the priorities, then the `b` characters will appear on the second line (they are second-highest priority) and will continue to appear until all of the `cea` characters have appeared. If the priority string is `abcadeafga`, then all of `bcdefg` are considered contained within it, an all 4 `a`s will continue to appear until the `g` has appeared. **More formatting requirements** All lines of output should be the same length (the length of the input lines), padded with spaces as necessary. The input program line may contain spaces, although those spaces will also be given a priority letter. Trailing newlines on output/input are optional. **Scoring** This is code golf, fewest bytes wins. --- **Examples** Here is a commented example of a piece of code with more complex formatting. ``` 1_'[3:~2@+]` abbcddeffgch 1 #highest priority is denoted by the lowercase letter a _' #priority b [ ] #all characters with priority c [3: ] #priority d, but priority c still printed because it encloses more [ ~ ] #priority e [ 2@ ] #priority f [ +] #priority g, last line of c because all enclosed characters have appeared ` #priority h ``` An example in Perl: ``` $_=<>;s/[^aeiou\W]/$&o$&/gi;print aaaaaabbccccccccccbdddddbbbbeeeee $_=<>; s/ / /gi; s/[^aeiou\W]/ /gi; s/ /$&o$&/gi; print ``` Here are a few examples in CJam, courtesy of Martin Büttner: ``` l~2*{_2%{3*)}{2/}?_p_(}g; aabbcdddefffeeggeehhiiccj l~ 2* { }g {_2% }g { { }{ }? }g { {3*)}{ }? }g { { }{2/}? }g { _p }g { _(}g ; q{_eu'[,66>"EIOU"-#)g{'o1$}*}/ abcccddddddeeeeeeefgghiijjhhbb q { }/ {_eu }/ { '[,66> }/ { "EIOU"- }/ { # }/ { )g }/ { { }*}/ { {'o }*}/ { { 1$}*}/ ``` Here is a crazy example just to mess with you: ``` 1_'[3:~2@+]` azTABACBDCAT [ : ] [3: 2 ] [3:~2 +] [ :~ @+] ' ` 1 _ ``` Here is a more explicit example of what happens when brackets overlap like `abab`. (Normally, this is not the way you would choose to format your explanation.) ``` aabbccddaaeebb aabbccddaaeebb aa aa aabb aa bb aabbcc aa bb aabb ddaa bb bb eebb #"aa" no longer appears because all of "bbccdd" have already appeared. ``` [Answer] # Pyth, ~~33~~ 40 bytes ``` JwFHS{Js.e?@zk&gHYsm&gdH}d>_>JxJYx_JYJdJ ``` Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=JwFHS%7BJs.e%3F%40zk%26gHYsm%26gdH%7Dd%3E_%3EJxJYx_JYJdJ&input=aabbccddaaeebb%0Aaabbccddaaeebb&debug=0) ## Explanation: Generated with the string `aabbbbbzccdeeegfffqhjiiikkpnmmllloooohec`: ``` implicit: z = first input line Jw J = second input line FHS{J for H in sorted(set(J)): .e J map each k,Y of enumerate(J) to: .e? J .... if ... else ... .e @zk dJ z[k] if ... else " " condition: .e @zk gHY dJ H >= Y .e @zk& dJ and .e @zk m JdJ map each d of J to: .e @zk m gdH JdJ d >= H .e @zk m& JdJ and .e @zk m }d JdJ d in ... .e @zk m xJY JdJ index of Y in J .e @zk m >J JdJ substring of J (from index to end) .e @zk m _ JdJ reverse substring .e @zk m x_JYJdJ index of Y in reversed J .e @zk m > JdJ substring of reversed (from index to end) .e @zk s dJ sum up the booleans (acts as any) s sum up the chars and print ``` So the first input line is `z`, the second input line is `J`. The loop iterates over all chars of `J` in sorted order and without duplicates. The current char is called `H`. Then for each `Y` of `J` I print the correspondent char of `z` or a whitespace, depending on if both of the following conditions are satisfied: * `Y <= H` (a char first appears in the line `H`) * there is a char `d >= H`, which appears in a block starting and ending with `Y` (brackets). ## Examples This shows how the forth line of the input `abcdaeb`, `abcdaeb` is printed. The fourth line is a good representation, since most of the possible cases happen: ``` code input: "abcdaeb" order input: "abcdaeb" printing the fourth line, H = "d": "a" is printed, because "a" <= "d" and ("d" >= "d" and "d" is in "abcda") "b" is printed, because "b" <= "d" and ("d" >= "d" and "d" is in "bcdaeb") "c" are not printed, because neither "d" nor "e" (chars >= "d") are not in "c" "d" is printed, because "d" <= "d" and ("d" >= "d" and "d" is in "d") "a" is printed, because "a" <= "d" and ("d" >= "d" and "d" is in "abcda") "e" is not printed, because "e" > "d" "b" is printed, because "b" <= "d" and ("d" >= "d" and "d" is in "bcdaeb") therefore the fourth line is: aabb__ddaa__bb ``` And another example based on a test-case, @Optimizer gave me. (which destroyed my 33 solution). ``` code input: "acab" order input: "acab" printing the second line, H = "b": "a" is printed, because "a" <= "b" and ("c" >= "b" and "c" is in "aca") "c" is not printed, because "c" > "b" "a" is printed, because "a" <= "b" and ("c" >= "b" and "c" is in "aca") "b" is printed, because "b" <= "b" and ("b" >= "b" and "b" is in "b") therefore the second line is: a_ab ``` # Old version: ~~58~~ ~~57~~ 52 bytes ``` JwKNFHS{J=K.e?eS>_>[[email protected]](/cdn-cgi/l/email-protection)?@zknYNdK=KXKHN ``` Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=JwKNFHS%7BJ%3DK.e%3FeS%3E_%3EJxJHx_JHqYH%40KkJs.e%3F%40zknYNdK%3DKXKHN&input=aabbccddaaeebb%0Aaabbccddaaeebb&debug=0) This creates a mask, which I'll modify before and after printing each line. For more information see the edit history. [Answer] # CJam, 48 bytes ``` ll:i:T.{___T#TW%@#~T<>+:e>)1$-@*123Se]m>}z_|(;N* ``` ### Explanation ``` l Code. l Priority. :i Convert priority to integer. :T Save to T. .{ } For corresponding items: .{___ } Copy the current priority 3 times. .{ T# } First position with this priority. .{ TW% } Reverse T. .{ @# } First (last) position with this priority. .{ ~T< } Cut T at the end of this priority. .{ > } Cut at the beginning of this priority. .{ + } Insert the current priority to prevent the array being empty. .{ :e> } Array maximum. .{ )1$- } Count of integers between the current priority and the maximum, inclusive. .{ @* } That number of the current character. .{ 123Se] } Fill irrelevant priorities with spaces. .{ m>} Rotate the array to make non-spaces starting at the current priority. Returns a column containing 123 items. z Zip to get the rows from columns. _| Remove duplicate rows, including unused priorities and all-space rows. (; Remove the first row (an all-space row). N* Insert newlines. ``` [Answer] # CJam, 82 bytes Pretty long currently and I think I can shave off a few more bytes. ``` leel:F]z::+F$_&\f{{W=1$=},\;}{]_{0f=_W=),\0=>Lf&Ra#)},F,S*\:+{~;1$L+:L;t}%oNo~}%]; ``` **Algorithm** Basic algorithm is as following: * `leel:F]z::+` : Group the code, the formatting and the index of each character together * `F$_&\f{{W=1$=},\;}` : Group the above triplets into priority of printing using the formatting string. This code also makes sure that the priorities are sorted. * `]_{0f=_W=),\0=>Lf&Ra#)},` : For each priority group of triplets, get the bounding index range and see if any index is not printed yet. If there is an unprinted index, include this priority group into the "to be printed in this step" group. * `F,S*\:+{~;1$L+:L;t}%oNo~}%` : After getting all groups to be printed in this step, fill the code into the correct index of an empty space string and then print that string. Also update the array containing the list of printed indexes. Code explanation to be followed when I am done golfing this. **Example** Here is the code run on the code itself: Input: ``` leel:F]z::+F$_&\f{{W=1$=},\;}{]_{0f=_W=),\0=>Lf&Ra#)},F,S*\:+{~;1$L+:L;t}%oNo~}%]; aaabbbcccccdddddeefgghhiffggejkklmmmnoooopppqrrrssssllttttuuuvwwxxxxxxxyvvzzzzjjjj ``` Output: ``` lee l:F ]z::+ F$_&\ f{ } f{{ }, } f{{W= },\;} f{{W=1$ },\;} f{{W= =},\;} { }%]; {]_ }%]; { { }, }%]; { {0f= }, }%]; { { _ }, }%]; { { W=), }, }%]; { { \0= }, }%]; { { > }, }%]; { { Lf& }, }%]; { { Ra#)}, }%]; { F,S* }%]; { \:+ }%]; { { }% }%]; { {~; }% }%]; { { 1$L+:L; }% }%]; { { t}% }%]; { oNo~}%]; ``` [Try it online here](http://cjam.aditsu.net/#code=leel%3AF%5Dz%3A%3A%2BF%24_%26%5Cf%7B%7BW%3D1%24%3D%7D%2C%5C%3B%7D%7B%5D_%7B0f%3D_W%3D)%2C%5C0%3D%3ELf%26Ra%23)%7D%2CF%2CS*%5C%3A%2B%7B~%3B1%24L%2B%3AL%3Bt%7D%25oNo~%7D%25%5D%3B&input=l~2*%7B_2%25%7B3*)%7D%7B2%2F%7D%3F_p_(%7Dg%3B%0Aaabbcdddefffeeggeehhiiccj) [Answer] # IDL 8.4, ~~316~~ ~~318~~ 304 bytes New version, still too long, but shorter! And, in the true spirit of IDL, completely vectorized, which means (since there's no for loop) that I can now do it as one line, and run it on itself, once I get my version completely upgraded to 8.4. That'll be edited in later. One line version: ``` c=(f='')&read,c,f&l=[0:strlen(f)-1]&c=strmid(c,l,1)&s=strmid(f,l,1)&u=s.uniq()&k=value_locate(u,s)&n=[0:max(k)]&d=hash(n,u.map(lambda(x,y,z:max(z[(r=stregex(y,'('+x+'(.*))?'+x,len=w)):r+w-1])),f,k))&print,n.map(lambda(n,l,c,d,i:i.reduce(lambda(x,i,l,c,d,n:x+(d[l[i]]ge n?c[i]:' ')),l,c,d,n)),k,c,d,l)&end ``` With line breaks (same number of bytes, subbing \n vs &), and commented: ``` c=(f='') ;initialize code and format as strings read,c,f ;read two lines of input from the prompt l=[0:strlen(f)-1] ;index array for the strings c=strmid(c,l,1) ;split the code string into an array, via substrings of length 1 s=strmid(f,l,1) ;same for the format string, saving f for regex later u=s.uniq() ;get the sorted unique values in the format string (sorts A->a) k=value_locate(u,s) ;assign layer values to the format characters n=[0:max(k)] ;index array for the unique format characters d=hash(n,u.map(lambda(x,y,z:max(z[(r=stregex(y,'('+x+'(.*))?'+x,len=w)):r+w-1])),f,k)) print,n.map(lambda(n,l,c,d,i:i.reduce(lambda(x,i,l,c,d,n:x+(d[l[i]]ge n?c[i]:' ')),l,c,d,n)),k,c,d,l) end ;end the script ``` Here's an algorithmic breakdown for line 9: ``` r=stregex(y,'('+x+'(.*))?'+x,len=w) ; r, w = starting position & length of substring in y {format string} bracketed by x {character} (inclusive) z[(r=...):r+w-1] ; grab a slice of z {layer array} from r to r+w-1 -> layer values for each character in the substring max(z[...]) ; max layer (depth) of any characters in that slice u.map(lambda(x,y,z:max(...)),f,k) ;map an inline function of the above to every element of the unique-formatting-character array d=hash(n,u.map(...)) ; create a hash using the unique indices, the result is a hash of (character:max_substring_depth) ``` ...and 10: ``` x+(d[l[i]]ge n?c[i]:' ')) ; ternary concatenation: if maxdepth for this character >= current depth, add the character, otherwise add ' ' i.reduce(lambda(x,i,c,d,l,n:...)),,l,c,d,n) ;accumulate elements of i {code/format index array} by passing them through the inline ternary concatenation function print,n.map(lambda(n,l,c,d,i:i.reduce(...)),k,c,d,l) ;map the depth index through the reduction, ending up with a string for each depth layer, then print it ``` Lines 9 and 10 do the real work, the rest of it sets up the variables you need for the end. I think this is about as golfed as it's going to get, I can't find anywhere else to do it better. ## Old version (everything below here is out of date): This is nowhere near short enough to win, because this is a terrible golfing language, but no one ever answers in IDL so I'm just gonna go for it. ``` a=(b='') read,a,b c=[0:strlen(b)-1] d=strmid(b,c,1) a=strmid(a,c,1) e=d[uniq(d,sort(d))] f=list(value_locate(e,d),/e) s=hash() for i=0,max(f)do begin g=stregex(b,'('+e[i]+'(.*))?'+e[i],l=l) s[i]=max(f[g:g+l-1]) print,f.reduce(lambda(x,y,z:x+(s.haskey(y)?z[y]:' '),s,a) s=s.filter(lambda(x,y:x[1]gt y),i) endfor end ``` I'm not sure if there's any way I can cut it down more... I could call strmid on both a and b at the same time, but then I spend more bytes indexing d and it works out the same. I'll keep working on it, though! (And tomorrow I'll edit in an explanation of the algorithm.) ]
[Question] [ # Background You are the apprentice of a powerful wizard, and your master is currently developing a spell for creating an inter-dimensional labyrinth to trap his enemies in. He wants you to program his steam-powered computer to analyze the possible layouts. Programming this diabolical machine is highly dangerous, so you'll want to keep the code as short as possible. # Input Your input is a two-dimensional grid of periods `.` and hashes `#`, signifying empty space and walls, given as a newline-delimited string. There will always be at least one `.` and one `#`, and you can decide whether there is a trailing newline or not. This grid is the blueprint of an infinite labyrinth, which is made by aligning infinitely many copies of the grid next to each other. The labyrinth is divided into *cavities*, which are connected components of empty spaces (diagonally adjacent spaces are not connected). For example, the grid ``` ##.#### ...##.. #..#..# ####..# ##...## ``` results in the following labyrinth (continued infinitely in all directions): ``` ##.######.######.#### ...##.....##.....##.. #..#..##..#..##..#..# ####..#####..#####..# ##...####...####...## ##.######.######.#### ...##.....##.....##.. #..#..##..#..##..#..# ####..#####..#####..# ##...####...####...## ##.######.######.#### ...##.....##.....##.. #..#..##..#..##..#..# ####..#####..#####..# ##...####...####...## ``` This particular labyrinth contains a cavity of infinite area. On the other hand, this blueprint results in a labyrinth with only finite cavities: ``` ##.#### ##..### ####... ..####. #..#### ``` # Output Your output shall be a truthy value if the labyrinth contains an infinite cavity, and a falsy value if not. Note that the labyrinth may contain both finite and infinite cavities; in that case, the output shall be truthy. # Rules You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed. # Additional Test Cases Infinite cavities: ``` .# #.# ... #.# #.###.#.###.# #.#...#...#.# #.#.#####.#.# ..#.#...#.#.. ###.#.#.#.### #...#.#.#...# #.###.#.###.# ##.### #..### ..##.. ###..# ##..## ..#..#..#..#..#..# .#..#..#..#..#..#. #..#..#..#..#..#.. #.####.###.###.#### #...#..#...###..### ###.#..#.######..## ....####.#######... ###..###...######## ##########.##....## ..###......##.##... #.........##..##### ###########..###..# #...........####..# #.###########.##..# #.##....##.....#### #.####.###.###.#### ``` Finite cavities: ``` ### #.# ### .# #. #### .#.. #### #.#.# ..#.. ##### ..#.. #.#.# #.#.#.#.#.# ..#...#.#.. ###.###.### ..#.#...... #.#.####### #.#.......# #.#######.# #.#.....#.# #.#.#.#.#.# ##....##### .#..#...##. .##.#..#... ..###.###.. #..##.##### #...##....# #.#.#####.# ###..####.# ....####... ###...##### ###....##.######### ####...##....#...## ..####.#######.###. ....##..........##. ###..#####.#..##... ####..#..#....#..## ..###.####.#.#..##. ..###...#....#.#... ..####..##.###...## #.####.##..#####.## ####...##.#####..## ########### ........#.. #########.# ..........# .########## .#......... ##.######## ...#....... ``` [Answer] # C# - ~~423~~ 375 bytes Complete C# program, accepts input via STDIN, outputs "True" or "False" to STDOUT as appropriate. I could not bare to leave that Linq in there... thankfully its removal paid off! It now keeps track of seen and visited cells in an array (given it only ever looks at a finite number of them anyway). I also re-wrote the directional code, removing the need for a Lambda, and generally making the code more impossible to understand (but with substantial byte savings). ``` using C=System.Console;struct P{int x,y;static void Main(){int w=0,W,k=0,o,i,j;P t;string D="",L;for(;(L=C.ReadLine())!=null;D+=L)w=L.Length;for(i=W=D.Length;i-->0&k<W;){k=1;P[]F=new P[W];for(F[j=0].x=i%w+W*W,F[0].y=i/w+W*W;D[i]>35&j<k;)for(t=F[j++],o=1;o<5&k<W;t.y+=(o++&2)-1){t.x+=o&2;if(D[--t.x%w+t.y%(W/w)*w]>35&System.Array.IndexOf(F,t)<0)F[k++]=t;}}C.WriteLine(k>=W);}} ``` It is a breadth-first (not that this matters) search which just carries on until it either gets stuck in a finite cavern, or it decides the cavern is big enough that it must be infinitely large (when it has as many cells as the original rectangle, this means there must be a path from one cell to itself somewhere else, which we can continue to follow forever). Untrimmed code: ``` using C=System.Console; struct P { int x,y; static void Main() { int w=0, // w is the width W, // W is the length of the whole thing k=0, // k is visited count o, // o is offset, or something (gives -1,0 0,-1 +1,0 0,+1 t offset pattern) i, // i is the start cell we are checking currently j; // j is the F index of the cell we are looking at P t; // t is the cell at offset from the cell we are looking at string D="", // D is the map L; for(;(L=C.ReadLine())!=null; // read a line, while we can D+=L) // add the line to the map w=L.Length; // record the width for(i=W=D.Length;i-->0&k<W;) // for each cell { k=1; P[]F=new P[W]; // F is the list of visited cells, for(F[j=0].x=i%w+W*W,F[0].y=i/w+W*W; // there are reasons (broken modulo) D[i]>35&j<k;) // for each cell we've visited, until we've run out for(t=F[j++], // get the current cell o=1; // o is just a counter which we use to kick t about o<5& // 4 counts k<W; // make sure we havn't filled F t.y+=(o++&2)-1) // kick and nudge y, inc o { t.x+=o&2; // kick x if(D[--t.x%w+t.y%(W/w)*w]>35 // nudge x, it's a dot &System.Array.IndexOf(F,t)<0) // and we've not seen it before F[k++]=t; // then add it } } C.WriteLine(k>=W); // result is whether we visited lots of cells } } ``` [Answer] # Python 2 - ~~258~~ ~~210~~ 244 bytes Recursively check paths, if stack overflow return 1 (truthy) else return None (falsey). ``` import sys def k(s): a=len(s);m=[[c=='.'for c in b]*999for b in s.split('\n')]*999;sys.setrecursionlimit(a) for x in range(a*a): try:p(m,x/a,x%a) except:return 1 def p(m,x,y): if m[x][y]:m[x][y]=0;map(p,[m]*4,[x,x,x+1,x-1],[y+1,y-1,y,y]) ``` [Answer] # Python 2 - 297 286 275 bytes Picks an arbitrary "open" cell to begin a flood fill from. Labyrinth is infinite if during the fill we re-visit a cell we've already visited, but it has a different coordinate to the previous visit. If the flood fill fills the entire region without finding such a cell, try a different region. If such a region can't be found, the labyrinth is finite. Takes file to process on command line, returns exit code `1` for infinite, and `0` for finite. Returns correct results for all test cases. ``` import sys e=enumerate C=dict([((i,j),1)for i,l in e(open(sys.argv[1]))for j,k in e(l)if'.'==k]) while C: d={} def f(r,c): n=(r%(i+1),c%j) if n in d:return(r,c)!=d[n] if C.pop(n,0):d[n]=(r,c);return any(map(f,[r-1,r,r+1,r],[c,c+1,c,c-1])) if f(*C.keys()[0]):exit(1) ``` [Answer] # JavaScript (ES6), 235 ~~253~~ Same method used by @mac. For each free cell, I try a recursive fill, marking used cells with the coordinate I am using (that can be outside the orginal template). If during the fill I arrive to a cell already marked having a different coordinate, I am in an infinite path. The [quirky way](https://stackoverflow.com/questions/4467539/javascript-modulo-not-behaving) of handling the modulo in JS it's quite annoying. ``` L=g=>( g=g.split('\n').map(r=>[...r]), w=g[0].length,h=g.length, F=(x,y,t=((x%w)+w)%w,u=((y%h)+h)%h,v=g[u][t],k=0+[x,y])=> v<'.'?0:v>'.'?v!=k :[0,2,-3,5].some(n=>F(x+(n&3)-1,y+(n>>2)),g[u][t]=k), g.some((r,y)=>r.some((c,x)=>c=='.'&&F(x,y))) ) ``` **Test** In Firefox / FireBug console *Infinite* ``` ['##.###\n#..###\n..##..\n###..#\n##..##' ,'#.#\n...\n#.#' ,'#.###.#.###.#\n#.#...#...#.#\n#.#.#####.#.#\n..#.#...#.#..\n###.#.#.#.###\n#...#.#.#...#\n#.###.#.###.#' ,'##.###\n#..###\n..##..\n###..#\n##..##' ,'#.####.###.###.####\n#...#..#...###..###\n###.#..#.######..##\n....####.#######...\n###..###...########\n##########.##....##\n..###......##.##...\n#.........##..#####\n###########..###..#\n#...........####..#\n#.###########.##..#\n#.##....##.....####\n#.####.###.###.####' ].forEach(g=>console.log(g,L(g))) ``` *Output* ``` "##.### #..### ..##.. ###..# ##..##" true "#.# ... #.#" true "#.###.#.###.# #.#...#...#.# #.#.#####.#.# ..#.#...#.#.. ###.#.#.#.### #...#.#.#...# #.###.#.###.#" true "##.### #..### ..##.. ###..# ##..##" true "#.####.###.###.#### #...#..#...###..### ###.#..#.######..## ....####.#######... ###..###...######## ##########.##....## ..###......##.##... #.........##..##### ###########..###..# #...........####..# #.###########.##..# #.##....##.....#### #.####.###.###.####" true ``` *Finite* ``` ['###\n#.#\n###', '.#\n#.', '####\n.#..\n####' ,'#.#.#\n..#..\n#####\n..#..\n#.#.#' ,'#.#.#.#.#.#\n..#...#.#..\n###.###.###\n..#.#......\n#.#.#######\n#.#.......#\n#.#######.#\n#.#.....#.#\n#.#.#.#.#.#' ,'##....#####\n.#..#...##.\n.##.#..#...\n..###.###..\n#..##.#####\n#...##....#\n#.#.#####.#\n###..####.#\n....####...\n###...#####' ,'###....##.#########\n####...##....#...##\n..####.#######.###.\n....##..........##.\n###..#####.#..##...\n####..#..#....#..##\n..###.####.#.#..##.\n..###...#....#.#...\n..####..##.###...##\n#.####.##..#####.##\n####...##.#####..##' ].forEach(g=>console.log(g,L(g))) ``` *Output* ``` "### #.# ###" false ".# #." false "#### .#.. ####" false "#.#.# ..#.. ##### ..#.. #.#.#" false "#.#.#.#.#.# ..#...#.#.. ###.###.### ..#.#...... #.#.####### #.#.......# #.#######.# #.#.....#.# #.#.#.#.#.#" false "##....##### .#..#...##. .##.#..#... ..###.###.. #..##.##### #...##....# #.#.#####.# ###..####.# ....####... ###...#####" false "###....##.######### ####...##....#...## ..####.#######.###. ....##..........##. ###..#####.#..##... ####..#..#....#..## ..###.####.#.#..##. ..###...#....#.#... ..####..##.###...## #.####.##..#####.## ####...##.#####..##" false ``` ]
[Question] [ Over at our friends at [Puzzling.SE](http://puzzling.stackexchange.com), the following puzzle was posted: [Is this chromatic puzzle always solvable?](https://puzzling.stackexchange.com/questions/36479/is-this-chromatic-puzzle-always-solvable) by Edgar G. You can play it [here](http://www.puzzlopia.com/puzzles/pixelea/play). ## Puzzle explanation Given a `m x n` grid with tiles of three different colours, you may select **any two adjacent tiles**, if their colours are **different**. These two tiles are then converted to the third colour, i.e., the one colour not represented by these two tiles. The puzzle is solved if **all tiles have the same colour**. Apparently, one can [prove](https://puzzling.stackexchange.com/a/36491/10180) that this puzzle is always solvable, if neither `m` nor `n` are divisible by 3. [![8x8 three colour puzzle](https://i.stack.imgur.com/W7Jv2.jpg)](https://i.stack.imgur.com/W7Jv2.jpg) Of course, this begs for a solving algorithm. You will write a function or program that solves this puzzle. Note that functions with 'side effects' (i.e., the output is on `stdout` rather than in some awkward data type return value) are explicitly allowed. ## Input & Output The input will be an `m x n` matrix consisting of the integers `1`, `2` and `3` (or `0`, `1`, `2` if convenient). You may take this input in any sane format. Both `m` and `n` are `>1` and not divisible by 3. You may assume the puzzle is not solved You will then solve the puzzle. This will involve a repeated selection of two adjacent tiles to be 'converted' (see above). You will output the two coordinates of these tiles for each step your solving algorithm took. This may also be in any sane output format. You are free to choose between 0-based and 1-based indexing of your coordinates, and whether rows or columns are indexed first. Please mention this in your answer, however. Your algorithm should run within reasonable time on the original 8x8 case. Brute-forcing it completely is explicitly disallowed, i.e. your algorithm should run under `O(k^[m*(n-1)+(m-1)*n])` with `k` the number of steps needed for the solution. The solution however is **not** required to be optimal. The proof given in the linked question may give you an idea as to how to do this (e.g., first do all columns using only vertically adjacent tiles, and then do all rows) ## Test cases In these test cases, the coordinates are 1-based and rows are indexed first (like MATLAB/Octave and probably many others). ``` Input: [1 2] Output: (result: all 3's) [1 1],[1,2] Input: [ 1 2 3 1 ] Output: (result: all 1's) [1 1],[2 1] (turn left column into 2's) [2 1],[2 2] (turn right column into 3's) [1 1],[1 2] (turn top row into 1's) [2 1],[2 2] (turn bottom row into 1's) Input: [1 2 3 2 3 2 1 1] Output: (result: all 3's) [1 1],[1 2] [1 3],[1 4] [1 2],[1 3] [1 1],[1 2] [1 2],[1 3] [1 1],[1 2] [1 3],[1 4] [2 1],[2 2] [1 1],[2 1] [1 2],[2 2] [1 3],[2 3] [1 4],[2 4] ``` If desired, I may post a pastebin of larger test cases, but I think this should be sufficient. [Answer] ## Octave, ~~334~~ 313 bytes Since the challenge may seem a bit daunting, I present my own solution. I did not formally prove that this method works (I guess that will come down to proving that the algorithm will never get stuck in a loop), but so far it works perfectly, doing 100x100 testcases within 15 seconds. Note that I chose to use a function with side effects rather than one that returns all the coordinates since that saved me a few bytes. Coordinates are row-major, 1-based, and formatted as `row1 col1 row2 col2`. Input colours are `0,1,2` since this works better with `mod`, at the cost of having to use `numel` rather than `nnz`. Golfed version: *Edit: saved another few bytes by using a technique from Kevin Lau's answer.* ``` function P(p) k=0;[m,n]=size(p);t=@(v)mod(sum(v)*numel(v),3);for c=1:n p(:,c)=V(p(:,c));end k=1;for r=1:m p(r,:)=V(p(r,:));end function a=V(a) while any(a-(g=t(a))) isempty(q=find(diff(a)&a(1:end-1)-g,1))&&(q=find(diff(a),1)); a([q q+1])=t(a([q q+1]));if k disp([r q r q+1]) else disp([q c q+1 c]) end;end;end;end ``` Example GIF of the solving algorithm: [![enter image description here](https://i.stack.imgur.com/njo6G.gif)](https://i.stack.imgur.com/njo6G.gif) Ungolfed version: ``` function solveChromaticPuzzle(p) [m,n]=size(p); % Get size t=@(v)mod(sum(v)*numel(v),3); % Target colour function for c=1:n % Loop over columns p(:,c)=solveVec(p(:,c)); % Solve vector end for r=1:m % Loop over rows p(r,:)=solveVec(p(r,:)); end function a=solveVec(a) % Nested function to get globals g=t(a); % Determine target colour while(any(a~=g)) % While any is diff from target... % Do the finding magic. Working left-to-right, we find the % first pair that can be flipped (nonzero diff) that does not % have the left colour different from our goal colour q=min(intersect(find(diff(a)),find(a~=g))); if(isempty(q)) % In case we get stuck... q=find(diff(a),1); % ... just flip the first possible end; a([q q+1])=t(a([q q+1])); % Do the actual flipping. if(exist('r')) % If we're working per row disp([r q r q+1]) % Print the pair, using global row else disp([q c q+1 c]) % Print the pari, using global col end end end end ``` [Answer] ## Lua, ~~594~~ ~~575~~ 559 Bytes **Warning** There's still lots of work before I'm done with this golfing! I should be able to take that under 500 Bytes, at the very least. For the moment, it's the first solution that worked, and I'm still working on it. I will provide a full explanation once I'm done. ``` function f(t)s=#t a=","for i=1,s do p=t[i]for i=1,s do p.Q=p.Q and p.Q+p[i]or p[i]end p.Q=(p.Q*#p)%3 for i=1,s do for j=1,#p-1 do x=p[j]y=p[j+1]u=x~=y and(p.S and p.R==p.S or x~=p.Q)v=(x+y)*2p[j]=u and v%3or x p[j+1]=u and v%3or y print(i..a..j,i..a..j+1)end p.R=p.S p.S=table.concat(p)end end for i=1,s do Q=Q and Q+t[i][1]or t[i][1]end Q=(Q*s)%3 for i=1,s do for j=1,s-1 do p=t[j]q=t[j+1]x=p[1]y=q[1]u=x~=y and(S and R==S or x~=Q)v=(x+y)*2 for k=1,#p do p[k]=u and v%3or x q[k]=u and v%3or y print(j..a..k,j+1..a..k)end Y=Y and Y..x or x end R=S S=Y end end ``` [Answer] # Ruby, 266 bytes More-or-less just a port of the Octave solution, except it solves rows first instead of columns. Input is an array of arrays, with the inner arrays being the rows. Output moves are `[row, column, row, column]`. [Test suite](https://repl.it/C9jd) ``` ->m{t=->v{v.size*v.inject(:+)%3} s=->a,x,r{g=t[a] (q=(r=0..a.size-2).find{|i|a[i]!=a[i+1]&&g!=a[i]}||r.find{|i|a[i]!=a[i+1]} a[q,2]=[t[a[q,2]]]*2 p r ?[x,q,x,q+1]:[q,x,q+1,x])while[]!=a-[g]} m.size.times{|i|s[m[i],i,1]} m=m.shift.zip *m m.size.times{|i|s[m[i],i,p]}} ``` ### Ungolfed with explanation ``` ->m{ # Start lambda function, argument `m` t=->v{v.size*v.inject(:+)%3} # Target color function s=->a,x,r{ # Function to determine proper moves # a = row array, x = row index, r = horizontal g=t[a] # Obtain target color ( q=(r=0..a.size-2).find{|i| # Find the first index `i` from 0 to a.size-2 where... a[i]!=a[i+1] # ...that element at `i` is different from the next... &&g!=a[i] # ...and it is not the same as the target color } || r.find{|i|a[i]!=a[i+1]} # If none found just find for different colors a[q,2]=[t[a[q,2]]]*2 # Do the color flipping operation p r ?[x,q,x,q+1]:[q,x,q+1,x] # Print the next move based on if `r` is truthy ) while[]!=a-[g]} # While row is not all the same target color, repeat m.size.times{|i| # For each index `i` within the matrix's rows... s[m[i],i,1] # ...run the solving function on that row # (`r` is truthy so the moves printed are for rows) } m=m.shift.zip *m # Dark magic to transpose the matrix m.size.times{|i|s[m[i],i,p]}} # Run the solving function on all the columns now # (`r` is falsy so the moves printed are for columns) ``` [Answer] # Rust, ~~496~~ 495 bytes Sadly I can't beat OP, but for a Rust answer I am quite satisfied with the bytecount. ``` let s=|mut v:Vec<_>,c|{ let p=|v:&mut[_],f,t|{ let x=|v:&mut[_],i|{ let n=v[i]^v[i+1];v[i]=n;v[i+1]=n; for k in f..t+1{print!("{:?}",if f==t{(k,i,k,i+1)}else{(i,k,i+1,k)});}}; let l=v.len();let t=(1..4).find(|x|l*x)%3==v.iter().fold(0,|a,b|a+b)%3).unwrap(); let mut i=0;while i<l{let c=v[i];if c==t{i+=1;}else if c==v[i+1]{ let j=if let Some(x)=(i+1..l).find(|j|v[j+1]!=c){x}else{i-=1;i};x(v,j);}else{x(v,i);}}t}; p(&mut (0..).zip(v.chunks_mut(c)).map(|(i,x)|{p(x,i,i)}).collect::<Vec<_>>(),0,c-1usize)}; ``` **Input:** a vector of numbers as well as the number of columns. E.g. ``` s(vec!{1,2,1,3},2); ``` outputs ``` (row1,col1,row2,col2) ``` to the command line. I first solve every row and then solve the resulting column only once ,but print the steps for all columns. So it is actually quite efficient :-P. **With formating:** ``` let s=|mut v:Vec<_>,c|{ let p=|v:&mut[_],f,t|{ // solves a single row/column let x=|v:&mut[_],i|{ // makes a move and prints it let n=v[i]^v[i+1]; // use xor to calculate the new color v[i]=n; v[i+1]=n; for k in f..t{ print!("{:?}",if f==t{(k,i,k,i+1)}else{(i,k,i+1,k)}); } }; let l=v.len(); // find target color // oh man i am so looking forward to sum() being stabilized let t=(1..4).find(|x|(l*x)%3==v.iter().fold(0,|a,b|a+b)%3).unwrap(); let mut i=0; while i<l{ let c=v[i]; if c==t{ // if the color is target color move on i+=1; }else if c==v[i+1]{ // if the next color is the same // find the next possible move let j=if let Some(x)=(i+1..l).find(|j|v[j+1]!=c){x}else{i-=1;i}; x(v,j); }else{ // colors are different so we can make a move x(v,i); } } t }; // first solve all rows and than sovle the resulting column c times p(&mut (0..).zip(v.chunks_mut(c)).map(|(i,x)|p(x,i,i)).collect::<Vec<_>>(),0,c-1usize) }; ``` **Edit:** now returns the color of the solution which saves me a semicolon^^ [Answer] # [Befunge](https://fr.wikipedia.org/wiki/Befunge), ~~197~~ ~~368~~ ~~696~~ 754 Bytes --- (yes, I'm doing some reverse code golf, the more bytes the better) I was thinking it could be a challenge to write this algorithm in Befunge and that it could be fun ~~I would like it to be a community program, so if anyone wants to work on it, please, do so.~~ In the end, I made everything alone so far, so I'll finish on my own (it's almost done) --- What's done yet: a troll-shaped code ``` &:19p&:09p:v:p94g92g90 < v94+1:g94&_$59g1+59p1-:| >p59gp1-: ^ vp95g93$< v94\-1<v:g< > v >g:1+v^_$v^90p94g92< v5p94< 3>1+59p ^ >9gg+\:^ %g v93:g95< v3_2 v v1pg95g94<^95<>g-v>$v^ v ^-%3*2\gg9< >9g39g+59g-1-|v-1_^ #^pg95+g92g90<1_09g:29g+5^ ; > > 09g:29g+59gg\3%-# !^v < ^p95< ^ < v p96-1+g90g92< v p95_@ >59g1+:39g-19g-^ v >p 79g:59gg\1+59gp$$$$$29g49pv > p59g^ |<<<<<<<<<<<<<<<<<<!-g96g94< >:79^>29g49p>69g1+59gg49g:59gg\1+49p- v ^\-\6+gg95+1\g< v !-g96:<-1g94_^ >"]",52*,::59g^v_::1+59gg\59gg-v^ < ^ .-g93g95,.-g<>:69g- v v-g96:_1+^ >+" [,]",,,\29^ >#v_$:49g2-v ^1:.-g93g95,.-g92\,"[ ":< < ``` (yes, it's a troll, believe me) Basically, it reads an array and computes the move to do to solve the rows, given an input as ``` (number of rows) (number of columns) 1 2 3 1 1 3 2 1 2 .... ``` (the whole array is passed as a list [row1, row2, row3,…]) output is ``` [col row],[col',row'] [col2 row2],[col2',row2'] ... ``` rows and cols both start at 0. Now that rows are solved, it's almost done ! Hooray ! --- Explanation: (will be updated later on) ![image](https://i.stack.imgur.com/CxCxS.png) So there are 5 main parts : * The first one, in green, reads the input line and writes one row of the array * The second one, in orange, passes to the next row of the array * The third, in the blue, sums a row * The fourth one, in hot pink, takes the modulus 3 of the sum, saves it at the right of the concerned row, and go to the next row * Finally, in the red, the part that computes the target color from the previously computed number. This part is really dumb and should probably be rewritten, but I didn't figure out how I could do that in a nice way (passed from 197 bytes to 368 with just that part) Grey parts are initialisations --- Here is a a deeper explanation of the module that finds the to boxes to combine (which is coded here, by the way) ``` B @ v | !-g96g94< ENTRY>29g49p>69g1+59gg49g:59gg\1+49p- v v !-g96:<-1g94_^ v_::1+59gg\59gg-v^ < >:69g- v v-g96:_1+^ >#v_$:49g2-v CALL< < ``` The CALL part is when the instruction pointer is going to another module, to combine to boxes. It comes back to this module through the 'B' entry Here is some pseudo code: (currentx is related to the array reading) For: ``` 69g1+59gg // read target color 49g:59gg\1+49p // read current color and THEN shift the currentx to the next box if ( top != top ){ // if the current color is bad 49g1- // put the current place (or currentx - 1) in the stack While: if ( :top != 69g ){ // if you didn't reach the end of the list ::1+ // copy twice, add 1 if ( 59gg == \59gg ){ // if the next color is the same than current 1+ // iterate break While; } } : // copies j (the previous raw iterator) if ( top == 69g ){ // if you reached the end of the row (which mean you can't swap with the color after that point) $: // discard j's copy and copy target 49g2- // put the place just before the color change on the stack combine_with_next; } else { combine_with_next; } 29g49p // back to the beginning of the row (there was some changes int the row) } if ( 49g != 69g ) // if you didn't reach the end of the list break For: ``` --- Note that if you want to test it, you will have to put some trailing space and trailing new lines so that there is enough space to store the array, if you wish to use [the interpret](http://www.quirkster.com/iano/js/befunge.html) I linked. 22 + the number of rows in input as trailing lines, and 34 + the number of columns as trailing spaces on one line should be ok. [Answer] # C, 404 bytes My first code golf, I'm pretty happy with how it turned out. Took way too long, though. It's not fully standard C, just whatever will compile under gcc with no special flags (and ignoring warnings). So there's a nested function in there. The function `f` takes the dimensions `m` and `n` as its first arguments, and as it's third argument takes takes an (int pointer) to an array of size `m`×`n` (indexed by rows first). The other arguments are dummy arguments, you don't need to pass them in, they're just there to save bytes on declaring variables. It writes each changed pair to STDOUT in the format `row1,col1:row1,col1;`, with the semicolon separating the pairs. Uses 0-based indexing. ``` #define A a[i*o+p #define B A*c f(m,n,a,i,j,o,p,b,c,d)int*a;{ int t(x){printf("%d,%d:%d,%d;",b?i:c+x,b?c+x:i,b?i:c+1+x,b?c+1+x:i);} o=n;p=b=1;for(;~b;b--){ for(i=0;i<m;i++){c=j=0; for(;j<n;)c+=A*j++];d=c*n%3; for(j=0;j<n-1;j++) while(A*j]^d|A*j+p]^d){ for(c=j;B]==B+p];c++); if(c<n-2&B]==d&2*(B+p]+A*(c+2)])%3==d) B+p]=A*(c+2)]=d,t(1);else B]=B+p]=2*(B]+B+p])%3, t(0);}}o=m;p=m=n;n=o;o=1;}} ``` I used a slightly different algorithm than OP for solving individual rows/columns. It goes something like this(pseudocode): ``` for j in range [0, rowlength): while row[j] != targetCol or row[j+1] != targetCol: e=j while row[e] == row[e+1]: e++ //e will never go out of bounds if e<=rowLength-3 and row[e] == targetCol and (row[e+1] != row[e+2] != targetCol): row.changeColor(e+1, e+2) else: row.changeColor(e, e+1) ``` The `for(;~b;b--)` loop executes exactly twice, on the second pass it solves columns instead of rows. This is done by swapping `n` and `m`, and changing the values of `o` and `p` which are used in pointer arithmetic to address the array. Here's a version that's ungolfed, with a test main, and prints the whole array after every move (press enter to step 1 turn): ``` #define s(x,y)b?x:y,b?y:x #define A a[i*o+p #define B A*e f(m,n,a,i,j,o,p,b,c,d,e)int*a;{ int t(x){ printf("%d,%d:%d,%d;\n",s(i,e+x),s(i,e+1+x)); getchar(); printf("\n"); for(int i2=0;i2<(b?m:n);i2++){ for(int j2=0;j2<(b?n:m);j2++){ printf("%d ",a[i2*(b?n:m)+j2]); } printf("\n"); } printf("\n"); } printf("\n"); b=1; for(int i2=0;i2<(b?m:n);i2++){ for(int j2=0;j2<(b?n:m);j2++){ printf("%d ",a[i2*(b?n:m)+j2]); } printf("\n"); } printf("\n"); o=n;p=1; for(b=1;~b;b--){ for(i=0;i<m;i++){ c=0; for(j=0;j<n;j++) c+= a[i*o+p*j]; d=0; d = (c*n)%3; for(j=0;j<n-1;j++) { while(a[i*o+p*j]!=d||a[i*o+p*j+p]!=d){ for(e=j;a[i*o+p*e]==a[i*o+p*e+p];e++); if(e<=n-3 && a[i*o+p*e]==d && 2*(a[i*o+p*e+p]+a[i*o+p*(e+2)])%3==d){ a[i*o+p*e+p]=a[i*o+p*(e+2)]=d; t(1); }else{ a[i*o+p*e]=a[i*o+p*e+p] = 2*(a[i*o+p*e]+a[i*o+p*e+p])%3; t(0); } } } } o=m;p=m=n;n=o;o=1; } } main(){ int g[11][11] = { {0,2,1,2,2,1,0,1,1,0,2}, {2,1,1,0,1,1,2,0,2,1,0}, {1,0,2,1,0,1,0,2,1,2,0}, {0,0,2,1,2,0,1,2,0,0,1}, {0,2,1,2,2,1,0,0,0,2,1}, {2,1,1,0,1,1,2,1,0,0,2}, {1,0,2,1,0,1,0,2,2,1,2}, {0,0,2,1,2,0,1,0,1,2,0}, {1,2,0,1,2,0,0,2,1,2,0}, {2,1,1,0,1,1,2,1,0,0,2}, {0,2,1,0,1,0,2,1,0,0,2}, }; #define M 4 #define N 7 int grid[M][N]; for(int i=0;i<M;i++) { for(int j=0;j<N;j++) { grid[i][j] = g[i][j]; } } f(M,N,grid[0],0,0,0,0,0,0,0,0); }; ``` ]
[Question] [ Consider a prime number *p*, written in base 10. The **memory** of *p* is defined as the number of distinct primes strictly less than *p* that are contained as substrings of *p*. ## Challenge Given a non-negative integer *n* as input, find the smallest prime *p* such that *p* has memory *n*. That is, find the smallest prime with exactly *n* distinct strictly lesser primes as substrings. ## Input Input can be taken through any standard format. You must support input up to the largest *n* such that the output does not overflow. For reference, 4294967291 is the largest prime in 32 bits. ## Output Output may be written to STDOUT or returned from a function. ## Examples The number 2 has memory 0 since it contains no strictly lesser primes as substrings. The number 113 is the smallest prime with memory 3. The numbers 3, 13, and 11 are the only prime substrings and no prime smaller than 113 contains exactly 3 primes as substrings. The first 10 terms of the sequence, beginning with *n* = 0, are ``` 2, 13, 23, 113, 137, 1237, 1733, 1373, 12373, 11317 ``` ## Note This is [A079397](https://oeis.org/A079397) in OEIS. ## Leaderboard ``` var QUESTION_ID=55406,OVERRIDE_USER=20469;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] # Pyth, 22 bytes ``` f&}TPTqQlf}YPY{sMP.:`T ``` [Demonstration](https://pyth.herokuapp.com/?code=f%26%7DTPTqQlf%7DYPY%7BsMP.%3A%60T&input=7&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10&debug=0), [Test Harness](https://pyth.herokuapp.com/?code=f%26%7DTPTqQlf%7DYPY%7BsMP.%3A%60T&input=7&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6&debug=0) Explanation: ``` f&}TPTqQlf}YPY{sMP.:`T Implicit: Q = eval(input()) f Starting at T=1 and counting up, return the first T where `T repr(T) .: all substrings P except T itself sM converted to integers { unique examples only f filter on }YPY Y is in the prime factorization of Y, e.g. Y is prime. qQl Q == len of the above, that is, T has memory Q, &}TPT and T is prime, (is in its prime factorization.) ``` [Answer] # CJam, ~~33~~ ~~31~~ 30 bytes ``` 1{)__mp*{_mp2$s@s#)*},,easi^}g ``` This is a full program that reads the input as a command-line argument. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=r%3AE%3B%7B%7D%3AA%3B%20e%23%20Emulate%20%60ea'.%0A%0A1%7B)__mp*%7B_mp2%24s%40s%23)*%7D%2C%2CEAsi%5E%7Dg&input=5). ### Test run ``` $ time cjam <(echo '1{)__mp*,{_mp2$s@s#)*},,easi^}g') 9 11317 real 0m3.562s user 0m4.065s sys 0m0.177s ``` ### How it works ``` 1 e# Push I := 1 on the stack. { e# Do: )__ e# Increment I and push two copies. mp* e# Check the last copy for primality and multiply with the first copy. e# This pushes R := I if I is prime and R := 0 if it is composite. { e# Filter; for each J in [0 ... R-1]: _mp e# Push a copy of J and check for primality. 2$s e# Push a copy of I and cast to string. @s e# Rotate the original J on top of the stack and cast to string. # e# Find the index (-1 if not found) of the latter in the former. )* e# Increment the index and multiply it with the result from `mp'. e# This yields 0 iff J is composite or not a subtring of I. }, e# Keep J if the product is non-zero. , e# Push the length of the filtered range. easi e# Cast the array of command-line arguments to string, then to integer. ^ e# XOR it with the length of the filtered range. }g e# Repeat while theresult is non-zero. ``` [Answer] # CJam, 40 bytes ``` li2sa{_)\{1$\#)},,3$-}{i{)_mp!}gsa+}w]W= ``` [Try it online](http://cjam.aditsu.net/#code=li2sa%7B_)%5C%7B1%24%5C%23)%7D%2C%2C3%24-%7D%7Bi%7B)_mp!%7Dgsa%2B%7Dw%5DW%3D&input=6) I'm sure this comes as a big shocker, but it is in fact longer than the solution Dennis posted. Well, not really, since I didn't even have very high hopes myself. But I wanted to give it a shot anyway. And since it's working, looks pretty reasonable to me, and I believe it is sufficiently different to at least be of some interest, I thought I'd post it anyway. The basic idea here is that I build a list of prime numbers in a loop, adding the next larger prime number to the list in each step. To check for termination, I count how many elements other than the last element in the list are a substring of the last element. If this count is equal to the input `n`, we're done. Explanation: ``` li Get input and convert to integer. 2sa Seed list of primes with ["2"]. The primes are stored as strings to make the later substring search more streamlined. { Start of while loop condition. _ Copy list of primes. ) Pop off last prime from list. \ Swap remaining list to top. { Start of filter block for substring matches with all smaller primes. 1$ Copy test prime to top. \ Swap the smaller prime to top to get correct order for substring search. # Search. ) Increment to get truthy value (Search returns -1 if not found). }, End of filter. We have a list of smaller primes that are substrings now. , Count list entries. 3$ Copy input n to top. - Subtract the two for comparison. If they are different, continue loop. } End of while loop condition. { Start of while loop body. We need to generate the next prime. i The largest prime so far is still on the stack, but as string. Convert it to integer. { Start of loop for prime candidates. ) Increment current candidate value. _mp Check if it is prime. ! Negate, loop needs to continue if it is not a prime. }g End loop for prime candidates. On exit, next prime is found. sa+ Convert it to string, and add it to list of primes. }w End of while loop body. ]W= Solution is at top of stack. Discard other stack entries. ``` [Answer] # Pyth - 25 bytes Nested filter, inner to calculate memory, outer to find first that has required memory. ``` f&!tPTqlf&!tPY}`Y`TtStTQ2 ``` [Test Suite](http://pyth.herokuapp.com/?code=f%26!tPTqlf%26!tPY%7D%60Y%60TtStTQ2&input=4&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4&debug=0). [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (2), 12 bytes, language postdates challenge ``` ~{ṗ≜{sṗ}ᵘkl} ``` [Try it online!](https://tio.run/nexus/brachylog2#@19X/XDn9Eedc6qLgXTtw20LUrJzav//N/sfBQA "Brachylog – TIO Nexus") This was previously 13 bytes, using `ᶠd`, but that's now been given an abbreviation `ᵘ`, cutting it down to 12. As the language postdates the challenge anyway, and the feature is one that wasn't added for this challenge in particular, I may as well use it. As is usual in Brachylog, this is a function, not a full program. ## Explanation ``` ~{ṗ≜{sṗ}ᵘkl} ~{ } Find a value for which the following is true: ṗ The value is prime; ≜ (evaluation strategy hint; avoids an infinite loop) { }ᵘ The set of unique sṗ substrings which are prime l has a length equal to {the input} k when one element is removed. ``` This gives us the smallest prime with the property we want, because `≜` checks values near 0 first. [Answer] ## Octave / Matlab, 126 bytes ``` function p=f(n) p=1;t=1;while t p=p+1;t=~isprime(p)|sum(arrayfun(@(x)any(strfind(num2str(p),num2str(x))),primes(p)))~=n+1;end ``` [Try it online](http://ideone.com/bGBHXu) [Answer] # JavaScript ES6, 106 bytes ``` n=>{for(a=[],i=2;a.filter(c=>(''+i).search(c)+1).length-n-1;a.push(i))while(!a.every(c=>i%c))i++;return i} ``` Here is an ungolfed version with explanation: ``` n=>{ /** * a = list of primes * i = current integer * Iterate until number of members in a that are substring of i == n-1 * After each iteration push the current value of i onto a */ for(a=[],i=2; a.filter(c=>(''+i).search(c)+1).length-n-1; a.push(i)) { // Iterate until no member of a exactly divides i and increment i per iteration while(!a.every(c=>i%c)) i++; } return i; } ``` Of course this gets horrendously slow rather quickly. However the OP has stated there is no limit on time. [Answer] # Python 2, ~~163~~ 154 Bytes I'm too tired to be golfing.. Hopefully when I wake up tomorrow I can improve this. ``` p=lambda n:all(n%x for x in range(2,n)) g=input() s=2 while not(p(s)and len([l for l in[str(x)for x in range(2,s)if p(x)]if l in str(s)])==g):s+=1 print s ``` [Answer] # Julia, 86 bytes ``` n->for i=1:~0>>>1 isprime(i)&&sum(j->contains("$i","$j"),primes(i-1))==n&&return i;end ``` It's practically self-explanatory. Loop over all positive integers, and each time a prime is found, sum a boolean array indicating whether the set of primes less than the current one are substrings of the current one. If it finds one with the necessary number of matches, return that value. Running time becomes sluggish for n=11, and likely for most values higher than 11 - specifically, on my laptop, n=11 takes about 33 seconds. [Answer] # [Husk](https://github.com/barbuz/Husk), 14 bytes ``` ḟ(=⁰#ṗumdQd)İp ``` [Try it online!](https://tio.run/##AR8A4P9odXNr///huJ8oPeKBsCPhuZd1bWRRZCnEsHD///8y "Husk – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 14 bytes ``` λSǎ⌊Uæ∑?=næ∧;ṅ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLOu1PHjuKMilXDpuKIkT89bsOm4oinO+G5hSIsIiIsIjMiXQ==) Takes input 1-indexed. ``` λ ;ṅ # First positive integer where... næ # Number is prime ∧ # And... Sǎ⌊U # Unique substrings of number, as numbers æ∑ # Have a count of primes ?= # Equal to the input? ``` [Answer] ## Haskell, ~~149~~ ~~147~~ 144 bytes (127 bytes not counting the `import` declaration). ``` import Data.List i x=x`elem`nubBy(((>1).).gcd)[2..x] f n=[p|p<-[2..],i p,n==length(nub[x|x<-[read b|a<-tails$show p,b<-tail$inits a],i x])-1]!!0 ``` > > Prelude Data.List> map f [0..20] > > [2,13,23,113,137,1237,1733,1373,12373,11317,23719,Interrupted. > > > The above output was produced with the longer definition ``` i x=and$[x>1]++[rem x n>0|n<-[2..x-1]] ``` The new, 3 chars shorter, definition is much slower, I could only get 5 first numbers in the sequence before loosing patience and aborting. [Answer] # [Haskell](https://www.haskell.org/), ~~119~~ 118 bytes ``` p x=all((>0).mod x)[2..x-1] f n=[y|y<-[2..],p y,n==sum[1|x<-[2..y-1],p x,elem(show x)$words=<<(mapM(:" ")$show y)]]!!0 ``` [Try it online!](https://tio.run/nexus/haskell#JYxLCsMgFAD3PcVLcKFgxJSuivYGPYG4EJLQgD9iShRyd2vb7cwwNUKWxlqMH5wwFybIRF0Zy8OoLwt4qcpZxPBFmkYo1EuZ3k6NZ/7T0sImMp3t7HB6haMd0BG2KUkhsDPxie899AT9XCFadx2vzqweJMRt9TsgaBksoDhjN10/ "Haskell – TIO Nexus") Usage: `f 3` yields `113`. [Answer] # PHP, 124 bytes ``` for($p=1;;){for($i=$c=0;$i-1;)for($i=++$p;$p%--$i;);$m[]=$p;foreach($m as$q)$c+=!!strstr($p,"$q");$c-1-$argv[1]?:die("$p");} ``` takes input from command line argument; run with `-r`. **breakdown** ``` for($p=1;;) { for($i=$c=0;$i-1;)for($i=++$p;$p%--$i;); // find prime $p $m[]=$p; // remember that prime foreach($m as$q)$c+=!!strstr($p,"$q"); // count memory primes $c-1-$argv[1]?:die("$p"); // if memory==N, exit } ``` [Answer] # [Python 2](https://docs.python.org/2/), 108 bytes ``` f=lambda n,x=2:n-sum(all(j%k for j in(i,x)for k in range(2,j))for i in range(2,x)if`i`in`x`)and f(n,x+1)or x ``` [Try it online!](https://tio.run/##TYxBDsIgFET3PQUbE36lJsWVJr0LaIv@Fj4EaEJPj@jKxSzey8yEI789yVrNZLV7zJqRKJO805B2x7W1fD1tzPjIVobEURT4wtaARU2vhUuxws/hvyuARqFCUkWBppkZ3o7PI7RiqeiCj5mlI3Utl7TkuDz3mNCTRYeZy76/jsMIXYhIuY2Rwp45QL19AA "Python 2 – Try It Online") ]
[Question] [ ## Problem You're stuck in a cabin in the middle of the woods, with only an old scrabble set to entertain yourselves. Upon inspection you see that the scrabble letters are so worn, that only the points for each letter are visible. Nonetheless you decide to play a game. You pull seven letters from the bag and place them on your tray, your challenge is to determine what those letters could be. So generally, given a list of points convert it into any possible string or list of letters. --- ## Scrabble Tiles and Distributions * 2 blank tiles (scoring 0 points) * 1 point: E ×12, A ×9, I ×9, O ×8, N ×6, R ×6, T ×6, L ×4, S ×4, U ×4 * 2 points: D ×4, G ×3 * 3 points: B ×2, C ×2, M ×2, P ×2 * 4 points: F ×2, H ×2, V ×2, W ×2, Y ×2 * 5 points: K ×1 * 8 points: J ×1, X ×1 * 10 points: Q ×1, Z ×1 So if you have a list of points `[10,10,8,5,1,1,1]` then `"QZJKEEE"` would be valid but `"QQJKEEE"` would not be valid (since there is only 1 Q tile in the bag) --- ## Problem Specific Rules * You may assume all inputs are valid and that there will always be 7 tiles (i.e it wont be a list of seven 10 point tiles and won't be 9 tiles) * You can assume no tiles have been previously pulled from the bag (so the distribution is the standard distribution of english tiles as defined above) * You do not have to generate a valid word, only a valid string of letters. * The order of your string is irrelevant as long as for each tile there is a corresponding letter. * Points are based on the standard english scrabble tile points as defined above. * You may output in upper or lower case, for a blank tile you may output either a space character or an underscore '\_' * Your answer may output as any reasonable representation of the tiles such as a List, String, Array or Sequence --- ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. --- ## Test Cases Obviously since you can output any possible value it's difficult to define strict test cases. Some cases with a *possible valid* return value: ``` [10,0,10,5,8,8,0] -> "Q ZKJX " [1,1,1,1,1,1,1] -> "EEEEEEE" [1,2,3,4,5,8,0] -> "NDBHKJ " [2,2,2,2,2,2,2] -> "DGDGDGD" ``` Some cases with an *invalid* return value: ``` [10,0,10,5,8,8,0] -> "Q QKJX " - Too many Qs [1,1,1,1,1,1,1] -> "EEEEEE " - Space is 0 points not 1 [1,2,3,4,5,8,0] -> "NDBH" - Too short [1,2,3,4,5,8,0] -> "NDBHKJ I" - Too long [1,2,3,4,5,8,0] -> "ÉDBHKJ1" - Contains none scrabble characters [2,2,2,2,2,2,2] -> "GDGDGDG" - Contains too many Gs (case for invalid cycling) ``` [Answer] # JavaScript (ES6), 72 bytes *A shorter variant suggested by [@supercat](https://codegolf.stackexchange.com/users/3748/supercat)* ``` a=>a.map(o=n=>'?ED?BWQ?_EG?CFZ?_EDJMH?K?EGXPV'[n*9.4+(o[n]=7-~o[n])&31]) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RLzexQCPfNs/WTt3e1cXeKTzQPt7V3d7ZLQpIu3j5eth727u6RwSEqUfnaVnqmWhr5Efnxdqa69aBaE01Y8NYzf/J@XnF@Tmpejn56RppGtGGBjoKBjog0lRHwQKMDGI1NbnQlCkY6mAgHMqMdBSMdRRMYAZiNc1IBwMBlf0HAA "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), ~~137 ... 84 78 77~~ 76 bytes *Saved 10 bytes by using [Neil's cycling method](https://codegolf.stackexchange.com/a/182959/58563)* Returns a list of tiles. Uses `_` for blank tiles. ``` a=>a.map(o=n=>"____FHVWGDGD_K__BCMPEEEE_ZQ__XJ"[n*20%44%32+(o[n]=-~o[n])%4]) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RLzexQCPfNs/WTikeCNw8wsLdXdxd4r3j452cfQNcgSA@KjA@PsJLKTpPy8hA1cRE1dhIWyM/Oi/WVrcORGmqmsRq/k/OzyvOz0nVy8lP10jTiDY00FEw0AGRpjoKFmBkEKupyYWmTMFQBwPhUGako2Cso2ACMxCraUY6GAio7D8A "JavaScript (Node.js) – Try It Online") ### How? For each number of points, we cycle through a group of exactly 4 tiles, starting with the *second* tile of each group (this is important for `G` vs `D`): ``` points | group | max. sequence --------+-------+--------------- 0 | ____ | __ 1 | EEEE | EEEEEEE 2 | GDGD | DGDGDGD 3 | BCMP | CMPBCMP 4 | FHVW | HVWFHVW 5 | _K__ | K \ 8 | _XJ_ | XJ }--- these letters may only appear once each 10 | _ZQ_ | ZQ / ``` All these groups are stored as a single string of 31 characters: ``` ____FHVWGDGD_K__BCMPEEEE_ZQ__XJ ^ ^ ^ ^ ^ ^ ^ ^ 0 4 8 12 16 20 24 28 ``` *NB*: We don't need to store the final `"_"` in `"_XJ_"`, as it will never be accessed anyway. The number of points \$n\$ is converted to the correct index \$i\_n\$ into this string with: $$i\_n=((20\times n)\bmod 44)\bmod 32$$ ``` n | *20 | mod 44 | mod 32 | group ----+-----+--------+--------+------- 0 | 0 | 0 | 0 | ____ 1 | 20 | 20 | 20 | EEEE 2 | 40 | 40 | 8 | GDGD 3 | 60 | 16 | 16 | BCMP 4 | 80 | 36 | 4 | FHVW 5 | 100 | 12 | 12 | _K__ 8 | 160 | 28 | 28 | _XJ_ 10 | 200 | 24 | 24 | _ZQ_ ``` The current position in each group is stored in the object \$o\$. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes ``` ⭆觧⪪”&↖“Vh_z↶∕¡⌈∨₂χ¹‖◨⌊″”¶ι№…θκι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaBTqKDiWeOalpFZowOjggpzMEg0lhZg815g8F/eYPCdn34CYPDePsPCYPO@YPBD0igCRgVFKOgpKMXlKmjoKmUDsnF8KNNw3PycFZG42WBQIrP//j4420lFAR7Gx/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input array ⭆ Map over elements and join ”...” Literal string " \nE\nDG\nBCMP\nFHVW\nK\n\n\nJX\n\nQZ" ⪪ ¶ Split on newlines § ι Indexed by current element § Cyclically indexed by №…θκι Number of times current element has already appeared Implcitly print ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~31 30 27~~ 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “ñẒẎYñ(“Nut¦hß’ṃØA;€⁶ɓṢĖœị ``` A monadic Link accepting a list of integers which yields a list of characters. - a mishmash of my previous, below, and my improvement of [Nick Kennedy's](https://codegolf.stackexchange.com/a/182987/53748) **[Try it online!](https://tio.run/##AU8AsP9qZWxsef//4oCcw7HhupLhuo5Zw7Eo4oCcTnV0wqZow5/igJnhuYPDmEE74oKs4oG2yZPhuaLElsWT4buL////MTAsMSwwLDMsMiwxLDEw "Jelly – Try It Online")** The output is not given in the same order as the input (this is allowed). Using 2 of my own additions to the language in an answer does not happen often! (`ṃ` and `ɓ` here). ### How? ``` “...“...’ṃØA;€⁶ɓṢĖœị - Link: list of integers, V e.g. [10,1,0,3,2,1,10] “...“...’ - list of base 250 integers [28089224382041, 77611203526272] ØA - 'ABC...XYZ' ṃ - base decompress (vectorises) ["EDMFKZZJZQ", "NGPYKZZXZZ"] ;€ - for €ach: concatenate: ⁶ - a space ["EDMFKZZJZQ ", "NGPYKZZXZZ "] ɓ - start a new dyadic chain with swapped arguments - i.e. f(V,that) Ṣ - sort [0,1,1,2,3,10,10] Ė - enumerate [[1,0],[2,1],[3,1],[4,2],[5,3],[6,10],[7,10]] œị - multi-dimensional index into " NEGMZQ" (1-based and modular) ``` --- previous @ 30 ``` “²rṛʂṂø5=Ɓṇ^N¥Y»⁾tky;⁶s2ɓṢĖUœị ``` A monadic Link accepting a list of integers which yields a list of characters. [Try it online!](https://tio.run/##AVIArf9qZWxsef//4oCcwrJy4bmbyoLhuYLDuDU9xoHhuYdeTsKlWcK74oG@dGt5O@KBtnMyyZPhuaLEllXFk@G7i////1sxMCwwLDEwLDUsOCw4LDBd "Jelly – Try It Online") This one's output is also mixed-case (this is allowed). ### How? ``` “...»⁾tky;⁶s2ɓṢĖUœị - Link: list of integers, V e.g. [10,1,0,3,2,1,10] “...» - compression of dictionary entries: - "end", "GMP", "fyttes", "adj", and "xci" and the string "qz" - "endGMPfyttesadjxciqz" y - translate with: ⁾tk - ['t', 'k'] "endGMPfykkesadjxciqz" ;⁶s2ɓṢĖUœị - ... - ...then like the above method (except U reverses each pair of indices) " neGMzq" ``` [Answer] # Pyth - ~~92~~ ~~86~~ ~~83~~ ~~81~~ ~~80~~ ~~75~~ ~~60~~ ~~52~~ ~~49~~ ~~42~~ 36 bytes Loops through input, popping off the available letters. I just have one of each letter that together give 7 for that point category. Now using packed string encoding. ``` K[M*L7c."B_êº çÑOÒ 7âCkÑ"\Lm.)@K K Assign to K [M Map list(for popping). Uses a quirk of M to splat each first *L7 Map repeating each string by 7 c \L Split on occurrences of 'L' ."..." Packed string encoding of the needed letters m (Q) Map on input (input is taken implicitly) .) Pop. This returns the first element after removing it @K Index into K (d) The loop variable is given implicitly ``` Btw, this is the original letter string before encoding: `"_ E DG BCMP FHVW K JX QZ"`. [Try it online](http://pyth.herokuapp.com/?code=K%5BM%2aL7c.%22B_%15%C3%AA%15%C2%BA%C2%8D+%C3%A7%C3%91O%C3%92%0A7%C3%A2Ck%C3%91%C2%92%22%5CLm.%29%40K&test_suite=1&test_suite_input=%5B10%2C10%2C8%2C5%2C1%2C1%2C1%5D%0A%5B1%2C1%2C1%2C1%2C1%2C1%2C1%5D%0A%5B1%2C2%2C3%2C4%2C5%2C8%2C0%5D&debug=0). [Answer] # [Perl 5](https://www.perl.org/), 71 bytes ``` @a=(__,'E'x7,DDDDGGG,BBCCMMP,FFHHVVW,K,1,1,JX,1,QZ);say chop$a[$_]for<> ``` [Try it online!](https://tio.run/##K0gtyjH9/98h0VYjPl5H3VW9wlzHBQjc3d11nJycnX19A3Tc3Dw8wsLCdbx1DIHQKwJIBEZpWhcnViokZ@QXqCRGq8THpuUX2dj9/2/IZcRlzGXCZcplwWXwL7@gJDM/r/i/rq@pnoGhAQA "Perl 5 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~70~~ ~~52~~ ~~39~~ ~~38~~ ~~29~~ ~~26~~ 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` {ε.•3Oû}α›ηö‡.ÝŽ{•2ôÁyèNè? ``` -18 bytes thanks to *@ExpiredData*. -13 bytes by using the same extend to size 7 from [*@Maltysen*'s Pyth answer](https://codegolf.stackexchange.com/a/182956/52210). -9 bytes by creating a port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/182984/52210), so make sure to upvote him! Results in a list of characters, and uses lowercase letters and a space for blanks. [Try it online](https://tio.run/##yy9OTMpM/f@/@txWvUcNi4z9D@@uPbfxUcOuc9sPb3vUsFDv8Nyje6uBMkaHtxxurDy8wu/wiv//ow0NdAx1DHSMdYyAtKFBLAA) or [verify some more test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/6nNb9R41LDL2P7y79tzGRw27zm0/vO1Rw0K9w3OP7q0Gyhgd3nK4sfLwCr/DK/7X6vyPjjY00DHQARKmOhZAaBCrE22ogwTBfCMdYx0TsAqQvJEOEoyNBQA). **Explanation:** ``` { # Sort the (implicit) input-list ε # Map each character `y` in this list to: .•3Oû}α›ηö‡.ÝŽ{• # Push compressed string "endgmpfykkzzzzjxzzqz " 2ô # Split into parts of size 2 Á # Rotate it once towards the left so the space is leading yè # Use integer `y` to index into the string-pairs Nè # Then get the `N`'th character of the string-pair (with automatic # wraparound), where `N` is the index of the loop ``` [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 `.•3Oû}α›ηö‡.ÝŽ{•` is `"endgmpfykkzzzzjxzzqz "`. --- **Previous 38 bytes answer:** ``` .•Mñ&Àû«ì{₆v*Å+µ-•#ðšε7∍}IvDyèн©?ε®õ.; ``` [Try it online](https://tio.run/##yy9OTMpM/f9f71HDIt/DG9UONxzefWj14TXVj5rayrQOt2of2qoLlFI@vOHownNbzR919NZ6lrlUHl5xYe@hlfbnth5ad3irnvX//9FGOkgwFgA) or [verify some more test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSvbqS/X@9Rw2LfA9vVDvccHj3odWH11Q/amor0zrcqn1oqy5QSvnwhqMLz201f9TRW1tZ5lJ5eMWFvYdW2p/bemjd4a161v9ra4GGHNpm/z862tBAx0AHSJjqWAChQaxOtKEOEgTzjXSMdUzAKkDyRjpIMDYWAA). **Explanation:** ``` .•Mñ&Àû«ì{₆v*Å+µ-• # Push compressed string "e dg bcmp fhvw k jx qz" # # Split on spaces: ["e","dg","bcmp","fhvw","k","","","jx","","qz"] ðš # Prepend a space to this list ε7∍} # Extend each string to size 7: # [" ","eeeeeee","dgdgdgd","bcmpbcm","fhvwfhv","kkkkkkk","","","jxjxjxj","","qzqzqzq"] Iv # Loop `y` over the input-list: Dyè # Get the `y`'th string from a copy of the list н # Get it's first character ©? # Store it in the register, and print it without trailing newline ε # Then map each string in the list to: ®õ.; # Remove the first occurrence of the character from the register ``` [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 `.•Mñ&Àû«ì{₆v*Å+µ-•` is `"e dg bcmp fhvw k jx qz"`. [Answer] # [C (gcc)](https://gcc.gnu.org/), 110 bytes ``` _[]={0,7,14,21,0,0,22,0,24};f(char*s){for(;*s+1;s++)*s=*s?*s-1?"DDDDGGGBBCCMMPFFHHVVWKJXQZ"[_[*s-2]++]:69:32;} ``` [Try it online!](https://tio.run/##dU5dS8MwFH3fr7gUhHwVmjinLpbBJuuYDObLFGsYodKZBztpii@lvz0msfrmuSEc7jn33Fulp6py7liqvM/YNeNTJjjLfAkRvukga1S965ZY3NfnFkliKZeWUkxsTuyC2JQvknuPoiiWy9Vqt9uv15vN4fD0sH1@fEnKY@k9QlGq5rPb@aWQgzNNBx/aNCgQ3Z4qBmEHEM@/SoWhn4BHUI2MNMpvutNlsCs5iV1/ECADOXAJBu5ilARKDY5yQJwxKVfepbuzQXGFUXiM@Mv8saT8NxoF5R9XNrY/W39ijZIL@9okDMaJwTke68rdOJ759w0 "C (gcc) – Try It Online") Uses the `_` array as an index into the static string `"DDDDGGGBBCCMMPFFHHVVWKJXQZ"` dynamically with exceptions for 0 and 1. Argument is a `-1`-terminated array of scores which is transformed in-place into a `-1`-terminated string. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~104~~ 90 bytes ``` a=>a.OrderBy(x=>x).Select((x,i)=>(x="_ E DG BCMP FHVW K JX QZ".Split()[x])[i%x.Length]) ``` [Try it online!](https://tio.run/##Vc5PCwFBGIDxu0/xtqXmrTEH17VzwPqzCClk27TG4K01NDsyks@@nETP7Xd6VNlQJVW9m1GtMZWutX@Y/ExK8mFsbmdt812hvyjhEFV5JHMxtXtt2w/mI@lRLHShlWPMc8JIfjDYQgzdPrQ7kxn0BssVjAAgWQPMN4FYXAtyDFOfYUp1L8baHN0pwyqsrSw5zUpnyRxFciHDAh7wAzP6Dn9/DJ9N/tMLEcPqDQ "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~34~~ 32 bytes ``` “¿RÇĊƈ⁸⁾%ỵṆþœsṀṂ’ṃØAṣ”A;⁶ẋ€7⁸ịḢ€ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5xD@4MOtx/pOtbxqHHHo8Z9qg93b324s@3wvqOTix/ubHi4s@lRw8yHO5sPz3B8uHPxo4a5jtaPGrc93NX9qGmNOVDLw93dD3csAnL@H530cOcMHaCJCrp2CkpAlTqH20FcEJPrcDtQSeR/JVcFF3cFJ2ffAAU3j7BwBW8FBQWvCAWFwCil/9Fc0YYGOgY6QMJUxwIIDWJ1gEI6SBAiYKRjrGMCVgNWYaSDBGO5YgE "Jelly – Try It Online") I hadn’t seen there was a shorter Jelly answer when I wrote this, and this uses a different approach so I thought was worth posting as well. Thanks to @JonathanAllan for saving 2 bytes! [Answer] # [Python 3](https://docs.python.org/3/), ~~178~~ ~~142~~ ~~135~~ ~~127~~ ~~112~~ 117 bytes ``` def f(l): d=list(map(list," _EEEEEEE_DDDDGGG_BBCCMMP_FFHHVVW_K___JX__QZ".split('_'))) return[d[i].pop()for i in l] ``` [Try it online!](https://tio.run/##JcZBC4IwFADgu7/i0cUNhlQWRNBFS6UQ6mKRyCPQ0WBtj7kO/flW0Xf66OXv1qQh9IMEyTRfR9BvtBo9e9yI/SImALj7w@1XWZaYZXle10csiqpqmjMeEHF/QTxdJ8lIWnkWY8w5j8AN/ulM27eqS8gS49I6UKAM6C6QU8YzydqZmItULMRSrMS04zy8LXllzRg@ "Python 3 – Try It Online") *-1 byte thanks to cdlane* *correct thanks to mathmandan* [Answer] # [Python 2](https://docs.python.org/2/), 102 bytes (or maybe 95?) (Also fine for Python 3.) ``` lambda a:''.join([r*7for r in'_ E DG BCMP FHVW K * * JX * QZ'.split()][x][:a.count(x)]for x in set(a)) ``` [Try it online!](https://tio.run/##TY3LCsIwFET3fsXdJSmhtFVRCm58owi6UTEGiS@M1KSkkdavj7GCOAdmMQwz@cvetEpc2du7TDyOZwEiRSi8a6kwM0Hnqg0YkAodYATDCfQHiyWMp@sNzCHwzLbeVjsUFnkmLSacVZylIjzpp7K4IvwzUPkBKC4WC0LcL2AsjmhEvbVp1xNxCiymf3yDhDZpq@7UjYT@wXnaAK/cSGWh9IfuDQ "Python 2 – Try It Online") I don't think the following would be acceptable: ``` lambda a:[[r*7for r in'_ E DG BCMP FHVW K * * JX * QZ'.split()][x][:a.count(x)]for x in set(a)] ``` This second version would give output like `['__', 'JX', 'QZ', 'K']`. So the letters would be correct, but they would be collected by point value. (If this were acceptable, it would save 7 bytes.) [Answer] # [PHP](https://php.net/), 101 bytes ``` $b=[_,E,DG,BCMP,FHVW,K,8=>JX,0,QZ];foreach($argv as$t){echo$c=($d=$b[$t])[0];$b[$t]=substr($d,1).$c;} ``` As a standalone program, input via command line: ``` $ php s.php 10 0 10 5 8 8 0 "Q_ZKJX_" ``` [Try it online!](https://tio.run/##JYnLCsIwEAB/pZQ9NLBIehAKMS34RhH0omIppY2x8WLCNnoRvz1WZGAYGGdciCeFMy7SRJZq0s6Svz@6hDMRoJVljQucr3A62@1xuT6ecIuZzDdn5Hi4VOJmSTfKJNBQ94qaHjx7a2UsKJnAVUJbgq9YySvxT9k/297T8DBlI1DiE4o8DiHlgf80DtkA/wI "PHP – Try It Online") ### Or 112 bytes as a function ``` function($a){$b=[_,E,DG,BCMP,FHVW,K,8=>JX,0,QZ];foreach($a as$t)$b[$t]=substr($d=$b[$t],1).$c[]=$d[0];return$c;} ``` [Try it online!](https://tio.run/##TZDRaoMwFIav51McJBcKZ6t1GxRcOuh0ldpt7c1WakWsTadjM5LEq9Jnd5ntqPkhCTkfHyenLur24bEuamBCcJEKVnOhyurTcmwPiHRpu2@qXJW8skhmH8iWxikG6E9x8vSywOfw/QMjHNHxbIUOLteJt@eCZXmhccgkUTbZxkQlVDZbqYRFdvT0gEP7huRxQskudhJPMNWIiuTesfUMgygmlQQKsQEQDx2t1ts9jnScBK8GA7geg7mEdTRbgdlB2MsFCU7rjLh4i3edp2d59SdhNDtZXOzlgvjTLqaR6OaM/x/Cuc1M6hvYcNAGlhccviSvUlblfMesroRgbtRGmdivlD/199@pp2zpOdmaWoSLNHibe8ax/QU "PHP – Try It Online") **Output** ``` [10,0,10,5,8,8,0] "Q_ZKJX_" [1,1,1,1,1,1,1] "EEEEEEE" [1,2,3,4,5,8,0] "EDBFKJ_" [2,2,2,2,2,2,2] "DGDGDGD" ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~77~~ 76 bytes ``` ->a{r=%w{_ E DG BCMP FHVW K . . JX . QZ};a.map{|i|(r[i]<<r[i][0]).slice! 0}} ``` [Try it online!](https://tio.run/##TYpNC4JAGAbv/oonQSh4WzYrCFIPfVMEdaloWcJESSgQTSPU376ZFMjAHIaJ0@tbBbbqOm4e28Yrv2CO2RKT6XaHxepwxAasYn2qtD@XY5c93CgvwqIdi1Ba1teCyw5L7qHnt8DLUgkNED1OnCoNaVTBJdWRGvyTSX0a1N/vMqmB1CTzXe@GvMgKROkzgW4ksB0YiQ4DIiMEIpOyVB8 "Ruby – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 63 bytes ``` *>>.&{(<_ E DG BCMP FHVW K _ _ JX _ QZ>[$_]x 7).comb[%.{$_}++]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1uplmb7X8vOTk@tWsMmXsFVwcVdwcnZN0DBzSMsXMFbIR4IvSKARGCUXbRKfGyFgrmmXnJ@blK0ql61SnyttnZs7f/ixEoFtTSNaCMdJBirac0FkzA00AEiCyA01THRMUGR0kGCQIn/AA "Perl 6 – Try It Online") ``` <_ E DG BCMP FHVW K _ _ JX _ QZ> # array indexed on tile value (<...>[$_] x 7) # pull letters for this value, repeat 7 times to catch E % # anonymous stateful hash .{$_} # element for this tile value ++ # post increment value to move position .comb[...] # characters to array, pull this incrementing index ``` So essentially it keeps a lookup of offsets for each tile value and increments them as needed, using the offset to pull a character from the available set. ]
[Question] [ ## Challenge Write a program P, taking no input, such that the proposition “the execution of P eventually terminates” is [independent](https://en.wikipedia.org/wiki/Independence_(mathematical_logic)) of [Peano arithmetic](https://en.wikipedia.org/wiki/Peano_axioms). ## Formal rules (In case you are a mathematical logician who thinks the above description is too informal.) One can, in principle, [convert](https://www.cs.virginia.edu/~robins/Turing_Paper_1936.pdf) some [Universal Turing machine](https://en.wikipedia.org/wiki/Universal_Turing_machine) *U* (e.g. your favorite programming language) into a [Peano arithmetic](https://en.wikipedia.org/wiki/Peano_axioms) formula HALT over the variable *p*, where HALT(*p*) encodes the proposition “*U* terminates on the program ([Gödel-encoded](http://mathworld.wolfram.com/GoedelNumber.html) by) *p*”. The challenge is to find *p* such that neither HALT(*p*) nor ¬HALT(*p*) can be proven in Peano arithmetic. You may assume your program runs on an ideal machine with unlimited memory and integers/pointers big enough to access it. ## Example To see that such programs exist, one example is a program that exhaustively searches for a Peano arithmetic proof of 0 = 1. Peano arithmetic proves that this program halts if and only if Peano arithmetic is inconsistent. Since Peano arithmetic [is consistent](https://en.wikipedia.org/wiki/Gentzen%27s_consistency_proof) but [cannot prove its own consistency](https://en.wikipedia.org/wiki/G%C3%B6del%27s_incompleteness_theorems#Second_incompleteness_theorem), it cannot decide whether this program halts. However, there are many other propositions independent of Peano arithmetic on which you could base your program. ## Motivation This challenge was inspired by a new [paper by Yedidia and Aaronson (2016)](http://www.scottaaronson.com/blog/?p=2725) exhibiting a 7,918-state Turing machine whose nontermination is independent of [ZFC](https://en.wikipedia.org/wiki/Zermelo%E2%80%93Fraenkel_set_theory), a much stronger system than Peano arithmetic. You may be interested in its citation [22]. For this challenge, of course, you may use your programming language of choice in place of actual Turing machines. [Answer] # Haskell, 838 bytes “If you want something done, …” ``` import Control.Monad.State data T=V Int|T:$T|A(T->T) g=guard r=runStateT s!a@(V i)=maybe a id$lookup i s s!(a:$b)=(s!a):$(s!b) s@((i,_):_)!A f=A(\a->((i+1,a):s)!f(V$i+1)) c l=do(m,k)<-(`divMod`sum(1<$l)).pred<$>get;g$m>=0;put m;l!!fromEnum k i&a=V i:$a i%t=(:$).(i&)<$>t<*>t x i=c$[4%x i,5%x i,(6&)<$>x i]++map(pure.V)[7..i-1] y i=c[A<$>z i,1%y i,(2&)<$>y i,3%x i] z i=(\a e->[(i,e)]!a)<$>y(i+1) (i?h)p=c[g$any(p#i)h,do q<-y i;i?h$q;i?h$1&q:$p,do f<-z i;a<-x i;g$p#i$f a;c[i?h$A f,do b<-x i;i?h$3&b:$a;i?h$f b],case p of A f->c[(i+1)?h$f$V i,do i?h$f$V 7;(i+1)?(f(V i):h)$f$6&V i];V 1:$q:$r->c[i?(q:h)$r,i?(2&r:h)$V 2:$q];_->mzero] (V a#i)(V b)=a==b ((a:$b)#i)(c:$d)=(a#i)c&&(b#i)d (A f#i)(A g)=f(V i)#(i+1)$g$V i (_#_)_=0<0 main=print$(r(8?map fst(r(y 8)=<<[497,8269,56106533,12033,123263749,10049,661072709])$3&V 7:$(6&V 7))=<<[0..])!!0 ``` ## Explanation This program directly searches for a Peano arithmetic proof of 0 = 1. Since PA is consistent, this program never terminates; but since PA cannot prove its own consistency, the nontermination of this program is independent of PA. `T` is the type of expressions and propositions: * `A P` represents the proposition ∀*x* [*P*(*x*)]. * `(V 1 :$ P) :$ Q` represents the proposition *P* → *Q*. * `V 2 :$ P` represents the proposition ¬*P*. * `(V 3 :$ x) :$ y` represents the proposition *x* = *y*. * `(V 4 :$ x) :$ y` represents the natural *x* + *y*. * `(V 5 :$ x) :$ y` represents the natural *x* ⋅ *y*. * `V 6 :$ x` represents the natural S(*x*) = *x* + 1. * `V 7` reprents the natural 0. In an environment with *i* free variables, we encode expressions, propositions, and proofs as 2×2 integer matrices [1, 0; *a*, *b*], as follows: * M(*i*, ∀*x* [*P*(*x*)]) = [1, 0; 1, 4] ⋅ M(*i*, λ*x* [P(x)]) * M(*i*, λ*x* [*F*(*x*)]) = M(*i* + 1, *F*(*x*)) where M(*j*, *x*) = [1, 0; 5 + *i*, 4 + *j*] for all *j* > *i* * M(*i*, *P* → *Q*) = [1, 0; 2, 4] ⋅ M(*i*, *P*) ⋅ M(*i*, *Q*) * M(*i*, ¬*P*) = [1, 0; 3, 4] ⋅ M(*i*, *P*) * M(*i*, *x* = *y*) = [1, 0; 4, 4] ⋅ M(*i*, *x*) ⋅ M(*i*, *y*) * M(*i*, *x* + *y*) = [1, 0; 1, 4 + *i*] ⋅ M(*i*, *x*) ⋅ M(*i*, *y*) * M(*i*, *x* ⋅ *y*) = [1, 0; 2, 4 + *i*] ⋅ M(*i*, *x*) ⋅ M(*i*, *y*) * M(*i*, S *x*) = [1, 0; 3, 4 + *i*] ⋅ M(*i*, *x*) * M(*i*, 0) = [1, 0; 4, 4 + *i*] * M(*i*, (*Γ*, *P*) ⊢ *P*) = [1, 0; 1, 4] * M(*i*, *Γ* ⊢ *P*) = [1, 0; 2, 4] ⋅ M(*i*, *Q*) ⋅ M(*i*, *Γ* ⊢ *Q*) ⋅ M(*i*, *Γ* ⊢ *Q* → *P*) * M(*i*, *Γ* ⊢ *P*(*x*)) = [1, 0; 3, 4] ⋅ M(*i*, λ*x* [P(x)]) ⋅ M(*i*, *x*) ⋅ [1, 0; 1, 2] ⋅ M(*i*, *Γ* ⊢ ∀*x* P(x)) * M(*i*, *Γ* ⊢ *P*(*x*)) = [1, 0; 3, 4] ⋅ M(*i*, λ*x* [P(x)]) ⋅ M(*i*, *x*) ⋅ [1, 0; 2, 2] ⋅ M(*i*, *y*) ⋅ M(*i*, *Γ* ⊢ *y* = *x*) ⋅ M(*i*, *Γ* ⊢ *P*(*y*)) * M(*i*, *Γ* ⊢ ∀*x*, *P*(*x*)) = [1, 0; 8, 8] ⋅ M(*i*, λ*x* [*Γ* ⊢ *P*(*x*)]) * M(*i*, *Γ* ⊢ ∀*x*, *P*(*x*)) = [1, 0; 12, 8] ⋅ M(*i*, *Γ* ⊢ *P*(0)) ⋅ M(*i*, λ*x* [(*Γ*, *P*(*x*)) ⊢ *P*(S(*x*))]) * M(*i*, *Γ* ⊢ *P* → *Q*) = [1, 0; 8, 8] ⋅ M(*i*, (*Γ*, *P*) ⊢ *Q*) * M(*i*, *Γ* ⊢ *P* → *Q*) = [1, 0; 12, 8] ⋅ M(*i*, (*Γ*, ¬*Q*) ⊢ ¬*P*) The remaining axioms are encoded numerically and included in the initial environment *Γ*: * M(0, ∀*x* [*x* = *x*]) = [1, 0; 497, 400] * M(0, ∀*x* [¬(S(*x*) = 0)]) = [1, 0; 8269, 8000] * M(0, ∀*x* ∀*y* [S(*x*) = S(*y*) → *x* = *y*]) = [1, 0; 56106533, 47775744] * M(0, ∀*x* [*x* + 0 = *x*]) = [1, 0; 12033, 10000] * M(0, ∀*y* [*x* + S(*y*) = S(*x* + *y*)]) = [1, 0; 123263749, 107495424] * M(0, ∀*x* [*x* ⋅ 0 = 0]) = [1, 0; 10049, 10000] * M(0, ∀*x* ∀*y* [*x* ⋅ S(*y*) = *x* ⋅ *y* + *x*]) = [1, 0; 661072709, 644972544] A proof with matrix [1, 0; *a*, *b*] can be checked given only the lower-left corner *a* (or any other value congruent to *a* modulo *b*); the other values are there to enable composition of proofs. For example, here is a proof that addition is commutative. * M(0, *Γ* ⊢ ∀*x* ∀*y* [*x* + *y* = *y* + *x*]) = [1, 0; 6651439985424903472274778830412211286042729801174124932726010503641310445578492460637276210966154277204244776748283051731165114392766752978964153601068040044362776324924904132311711526476930755026298356469866717434090029353415862307981531900946916847172554628759434336793920402956876846292776619877110678804972343426850350512203833644, 14010499234317302152403198529613715336094817740448888109376168978138227692104106788277363562889534501599380268163213618740021570705080096139804941973102814335632180523847407060058534443254569282138051511292576687428837652027900127452656255880653718107444964680660904752950049505280000000000000000000000000000000000000000000000000000000] You can verify it with the program as follows: ``` *Main> let p = A $ \x -> A $ \y -> V 3 :$ (V 4 :$ x :$ y) :$ (V 4 :$ y :$ x) *Main> let a = 6651439985424903472274778830412211286042729801174124932726010503641310445578492460637276210966154277204244776748283051731165114392766752978964153601068040044362776324924904132311711526476930755026298356469866717434090029353415862307981531900946916847172554628759434336793920402956876846292776619877110678804972343426850350512203833644 *Main> r(8?map fst(r(y 8)=<<[497,8269,56106533,12033,123263749,10049,661072709])$p)a :: [((),Integer)] [((),0)] ``` If the proof were invalid you would get the empty list instead. ]
[Question] [ The first *Predecessor-completed Ascii Cube (PAC 1)* is a simple cube with side length 1 and looks like this: ``` /////\ ///// \ \\\\\ / \\\\\/ ``` The *PAC 2* is a geometric shape such that combining it with its predecessor (the *PAC 1*) completes a side length 2 cube: ``` front back /////////\ /////////\ ///////// \ ///////// \ /////\\\\\ \ ///////// \ ///// \\\\\ \ ///////// \ \\\\\ ///// / \\\\\\\\\ / \\\\\///// / \\\\\\\\\ / \\\\\\\\\ / \\\\\\\\\ / \\\\\\\\\/ \\\\\\\\\/ ``` Because the *back*-view is kind of boring, we are only interested in the *front*-view. The same goes for the *PAC 3*: With some visual thinking the *PAC 2* can be turned around and plugged into the *PAC 3* to form a solid side length 3 cube: ``` /////////////\ ///////////// \ /////\\\\\\\\\ \ ///// \\\\\\\\\ \ ///// /////\\\\\ \ ///// ///// \\\\\ \ \\\\\ \\\\\ ///// / \\\\\ \\\\\///// / \\\\\ ///////// / \\\\\///////// / \\\\\\\\\\\\\ / \\\\\\\\\\\\\/ ``` And so on with *PAC 4*: ``` /////////////////\ ///////////////// \ /////\\\\\\\\\\\\\ \ ///// \\\\\\\\\\\\\ \ ///// /////////\\\\\ \ ///// ///////// \\\\\ \ ///// /////\\\\\ \\\\\ \ ///// ///// \\\\\ \\\\\ \ \\\\\ \\\\\ ///// ///// / \\\\\ \\\\\///// ///// / \\\\\ \\\\\\\\\ ///// / \\\\\ \\\\\\\\\///// / \\\\\ ///////////// / \\\\\///////////// / \\\\\\\\\\\\\\\\\ / \\\\\\\\\\\\\\\\\/ ``` ### Task: Write a full program or function which takes a positive integer n as input and returns or prints the corresponding front-view of *PAC n* exactly as shown above. Additional trailing white space is acceptable. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so try to use as few bytes as possible in the language of your choice. [Answer] ## JavaScript (ES6), 229 bytes ``` f= (n,l=n*4+1,r=1,i=n*2,g=a=>` / \\ / `.replace(/./g,c=>c.repeat(a.pop())))=>n?g([r,,l,--i])+g([r,2,l,--i])+f(n-1,l-1?1:r-4,r-1?1:l-4).replace(/(\S).*(.)/g,r-1?`$1 $&$2$2$2$2`:`$1$1$1$1$& $2`)+g([r,2,l,,,i])+g([r,,l,,,i+1]):`` ``` ``` <input type=number min=0 oninput=o.textContent=f(+this.value)><pre id=o> ``` [Answer] ## Batch, ~~559~~ ~~432~~ 400 bytes ``` @echo off set m= for /l %%i in (1,1,%1)do call set m= %%m%% call:c "%m:~2%" %m: =//%/\ exit/b :c setlocal set m=%~1%2%~3 echo %m% echo %m:/\=/ \% set s=%~1 if "%s:~,1%"=="/" goto g set t=%2 set t=%t:~3,-3% if %t:~,1%==/ (call:c "%s:~2%////" /\%t:/=\% " \%~3")else call:c "%s:~2%/ " %t:\=/%/\ "\\\\%~3" :g set m=%m:/=-% set m=%m:\=/% set m=%m:-=\% echo %m:\/=\ /% echo %m% ``` Explanation: The bottom half of the cube is drawn by reflecting the top half. The halves are further split into ~~seven~~ ~~six~~ three ~~strips~~ parts, as per this diagram showing the top half: ``` 1 12/////////////////\233 1 12///////////////// \233 1 ////12/\\\\\\\\\\\\\23 \3 1 ////12/ \\\\\\\\\\\\\23 \3 1 ///// 12/////////\23\\\\ \3 1 ///// 12///////// \23\\\\ \3 1 ///// ////12/\\\\\23 \\\\\ \3 1///// ////12/ \\\\\23 \\\\\ \3 ``` 1. The indentation (which decreases every row) and the left triangle, which increases every other row 2. The middle shrinking zigzag triangle, with the small triangle on alternate sides every other row 3. The right triangle, which increases in sync with the left Edit: Saved over 20% by improving the code that reflected the top to the bottom half. Saved almost 10% by merging the left two and middle three strips. [Answer] # [Canvas](https://github.com/dzaima/Canvas), 36 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ;Xø;{1x/╋ ø╶{«5⁸2²4×⁸²«1╋²«\+;↔53╋}═ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjFCJXVGRjM4JUY4JXVGRjFCJXVGRjVCJXVGRjExJXVGRjU4JXVGRjBGJXUyNTRCJTBBJUY4JXUyNTc2JXVGRjVCJUFCJXVGRjE1JXUyMDc4JXVGRjEyJUIyJXVGRjE0JUQ3JXUyMDc4JUIyJUFCJXVGRjExJXUyNTRCJUIyJUFCJXVGRjNDJXVGRjBCJXVGRjFCJXUyMTk0JXVGRjE1JXVGRjEzJXUyNTRCJXVGRjVEJXUyNTUw,i=NA__,v=1) [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 32 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ø.∫4*I└*2∙f«5└*∙+¼F«╝┼;↔±53╬5}╬± ``` [Try it here!](https://dzaima.github.io/SOGLOnline/?code=JUY4LiV1MjIyQjQqSSV1MjUxNCoyJXUyMjE5ZiVBQjUldTI1MTQqJXUyMjE5KyVCQ0YlQUIldTI1NUQldTI1M0MlM0IldTIxOTQlQjE1MyV1MjU2QzUlN0QldTI1NkMlQjE_,inputs=NA__,v=0.12) Simple explanation: 1. iterate for each of 1..x 2. make a `⌐` shape with the width of `i*4+1` and height = `(0-indexed)i // 2` 3. pad it so it looks like `⦧` 4. append a "\" shape to that horizontally 5. insert the previous step inside that reversed 6. after everything, mirror vertically full program: ``` ø push an empty string - starting stage .∫ } iterate over 1..input 4* multiply the 1-indexed counter by 4 I and add 1 └* repeat "/" that many times 2∙ and repeat vertically twice. Top 2 lines are done f« push the 0-indexed counter floor divided by 2 5└* push "/" repeated 5 times ∙ and repeat that vertically by the result of the "f«" + add vertically, creating a "⌐" shape ¼ prepend each next line with one less space than the above F« push 1-indexed counter floor divided by 2 ╝ create a "\" diagonal that long ┼ and append it horizontally. Shell is done of this hexagon ;↔± get the previous item on the stack and reverse it horizontally 53╬5 and at [5;3] insert the previous result in this ╬± once everything's done, mirror vertically to finish the hexagon ``` [Answer] # [Haskell](https://www.haskell.org/), ~~232~~ ~~227~~ ~~224~~ ~~187~~ ~~183~~ ~~180~~ 175 bytes ``` m '/'='\\' m '\\'='/' m c=c r=reverse k=map n?s=('/'<$[1..4*n])++s f 0=[] f n=n?"/\\":n?"/ \\":[1?k m(r s)++" \\"|s<-f$n-1] s="":k(' ':)s ((++).r<*>k(k m)).zipWith(++)s.r.f ``` The anonymous function in the last line takes an integer argument and yields the lines to be printed for a cube of that size. The idea is to use recursion to draw larger cubes from smaller ones. Lets look at the upper half of a cube of size 1. Then we get the upper half of a cube of size 2 by mirroring the former half and add a fixed pattern of slashes and spaces around it: ``` /////////\ ///////// \ /////\ ==> /\\\\\ ==> ////**/\\\\\** \ ///// \ / \\\\\ ////**/ \\\\\** \ ``` So the algorithm to draw a cube of size *n* is 1. Get the lines for the upper cube half of size *n-1*. 2. Mirror each line (by flipping `/`s and `\`s), and pad `////` and `\` around. 3. Prepend two lines with the pattern `////`*n* plus `/\` and `/ \`. 4. Mirror the resulting lines to get the full cube. 5. Pad lines with appropriate number of spaces. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~174 167 169~~ 167 bytes ``` ->n{a=(1..m=n*4).map{' '*m} (-n..0).map{|i|(-2*i).times{|k|a[y=k+2*j=n+i][m+~k+i*2,2+k*2-s=4*i]=?/*(1-~j%2*s)+' '*k+?\\*(1-j%2*s) a[~y]=a[y].tr('/\\','\\\\/')}} a*$/} ``` [Try it online!](https://tio.run/##Jcy7DoMgGEDh3adwaAP8CLTUlfogwECTmiCBGC@DUXx1a@MZv@EM82c5WnWwd1qdwk/Oo0pQEx5dv6ISQcwFZonzx0Wb3zCT4AmffPyO6xY2pxcVqIROJeqtjnQP1IOsJA0g2ahq8FY1AvCT7d1dwkgoKs9zoI0xf72wcHpfrDpvlk8DRsIYVCFzJhDJuXBwE/no52ksW/2yxw8 "Ruby – Try It Online") creates an array of `n*4` strings filled with spaces, then overwrites it with successively smaller cubes. **Commented code** ``` ->n{a=(1..m=n*4).map{' '*m} #make an array of n*4 strings of n*4 spaces (up to centreline of final output) (-n..0).map{|i| #iterate through cube sizes from n down to 0 (i is negative -n to 0) (-2*i).times{|k| #iterate through the number of lines in the top half of the cube a[y=k+2*j=n+i][m+~k+i*2,2+k*2-s=4*i]= #overwrite the correct part of the correct line ?/*(1-~j%2*s)+' '*k+?\\*(1-j%2*s) #with the correct string of the form "/spaces\" with an additional -4*i symbols on one side a[~y]=a[y].tr('/\\','\\\\/') #copy the current line from top half into bottom half, subsituting / for \ and vice versa } } a*$/} #return the elements of the array a, concatenated with newlines $/ ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~254~~ ~~234~~ ~~226~~ ~~203~~ ~~201~~ 199 bytes Finally sub 200! ``` P=[];n=0 M=lambda r:(u''+r).translate({47:92,92:47}) exec r"n+=1;q='/'*4;P=[q*n+'/\\',q*n+'/ \\']+[q+'%s \\'%M(r[::-1])for r in P];"*input() print'\n'.join(l.center(8*n)for l in(P+map(M,P[::-1]))) ``` **Tricks:** This function is used to swap all `\` with `/` and vice versa A bit long in Python2 - works only with unicode Check out [this](https://codegolf.stackexchange.com/a/48994/66855) for how it works ``` M=lambda r:(u''+r).translate({47:92,92:47}) ``` --- Generates new top two rows for each iteration For now I can't find compact way to receive this lines from previous iteration ``` P=[q*n+'/\\',q*n+'/ \\'] ``` --- Reverse all rows of previous iteration and swap slashes ``` [q+'%s \\'%M(r[::-1])for r in P] ``` --- Copy top half, reversed by rows, swap slashes ``` P+map(M,P[::-1]) ``` --- Neat method for center padding strings ``` l.center(8*n) ``` [Try it online!](https://tio.run/##LYzBCoJAFADvfsUSxNt1zUqMcmU/QfCuHjbbyNCnvjYoom83qW4zh5nh6S49RtOU66JKUW@8TLemO54MI8XvAJJE6MjgrTXO8le8V0kUJJGK92/h2YetGS1Q6m06aliDH6fzaPRRwrosIfgRYzNXshglLG/sa8uMU6HUaluJc0@MWIMsr9KF3@Bwd1x4AzXooEQIr32DvA1ri84SP/j4Ldq54LnszMCzIP@vhJim3Qc "Python 2 – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 36 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` äª.$u>↓Z╙╝B↨EXª¡╜?Xáhç∙╩p/♂ù⌠r↨c⌐f/* ``` [Run and debug it](https://staxlang.xyz/#p=84a62e24753e195ad3bc42174558a6adbd3f58a06887f9ca702f0b97f4721763a9662f2a&i=5&a=1) This approach builds up the top half of the output iteratively. It executes the main block the specified number of times. In that block, each row is mirrored and has a prefix and suffix added. The top two new rows are added separately. When all the rows are built, they're centered, and then the bottom is mirrored vertically. Here's the program unpacked, ungolfed, and commented. ``` { begin block to repeat iHYH^H'\* make a string of '\' characters and set the Y register pseudo-code: push(((y = (i * 2)) * 2 + 1) * 2 * '\') given the 0-based iteration index `i`, let y = 2 * i and push a string consisting of (i*8 + 2) backslashes 2M split the string into to equal size (i*4 + 1) substrings ~+ push array to input stack and concatenate on the first iteration, this is a no-op subsequently, it prepends the array to the result so far { begin a block to use for mapping 4'\*+ append 4 backslashes to this element :R "brace-wise" reverse this reverses the string AND the slashes in it |YH3+92& write 92 to index (++y * 2 + 3) in the array this puts the trailing backslash at the correct position this will be an out of bounds index, so the string will grow 92 is the character code for backslash m execute map using block }* repeat block specified number of times |C vertically center all rows { begin block for output mapping Q output this line without popping :Rr "brace-wise" reverse, and then actually reverse net effect is to swap forward and backward slashes m execute map using block rm reverse array, and output all rows ``` [Run this one](https://staxlang.xyz/#c=%7B+++++++++++%09begin+block+to+repeat%0A++iHYH%5EH%27%5C*+%09make+a+string+of+%27%5C%27+characters+and+set+the+Y+register%0A++++++++++++%09++pseudo-code%3A+push%28%28%28y+%3D+%28i+*+2%29%29+*+2+%2B+1%29+*+2+*+%27%5C%27%29%0A++++++++++++%09++given+the+0-based+iteration+index+%60i%60,+let+y+%3D+2+*+i%0A++++++++++++%09++and+push+a+string+consisting+of+%28i*8+%2B+2%29+backslashes%0A++2M++++++++%09split+the+string+into+to+equal+size+%28i*4+%2B+1%29+substrings%0A++%7E%2B++++++++%09push+array+to+input+stack+and+concatenate%0A++++++++++++%09++on+the+first+iteration,+this+is+a+no-op%0A++++++++++++%09++subsequently,+it+prepends+the+array+to+the+result+so+far%0A++%7B+++++++++%09begin+a+block+to+use+for+mapping%0A++++4%27%5C*%2B+++%09append+4+backslashes+to+this+element%0A++++%3AR++++++%09%22brace-wise%22+reverse%0A++++++++++++%09++this+reverses+the+string+AND+the+slashes+in+it%0A++++%7CYH3%2B92%26%09write+92+to+index+%28%2B%2By+*+2+%2B+3%29+in+the+array%0A++++++++++++%09++this+puts+the+trailing+backslash+at+the+correct+position%0A++++++++++++%09++this+will+be+an+out+of+bounds+index,+so+the+string+will+grow%0A++++++++++++%09++92+is+the+character+code+for+backslash+%0A++m+++++++++%09execute+map+using+block%0A%7D*++++++++++%09repeat+block+specified+number+of+times%0A%7CC++++++++++%09vertically+center+all+rows%0A%7B+++++++++++%09begin+block+for+output+mapping%0A++Q+++++++++%09output+this+line+without+popping%0A++%3ARr+++++++%09%22brace-wise%22+reverse,+and+then+actually+reverse%0A++++++++++++%09++net+effect+is+to+swap+forward+and+backward+slashes%0Am+++++++++++%09execute+map+using+block%0Arm++++++++++%09reverse+array,+and+output+all+rows&i=5&a=1) [Answer] # Haskell, 193 bytes Longer than the winner, but the approach may be interesting -- uses even `cos` and `pi` :) Code: ``` i s e f|max e f>s=""|max e f<s=" "|e==s="\\"|1<2="/" w n y x=head$do{d<-[1..n];o<-[-2*d..2*d];z<-[(cos(pi*(n-d)))*o+x];i(2*d)(abs$z-y)(abs$z+y-1)}++" " n!h=h<$>[1-2*n..2*n] f n=((2*n)!)<$>n!w n ``` Run it like this: ``` mapM_ putStrLn (f 4) ``` This program basically 'draws' many diamonds like this one: ``` ------------------------ ------------------------ -----------/\----------- ----------/ \---------- ---------/ \--------- --------/ \-------- --------\ /-------- ---------\ /--------- ----------\ /---------- -----------\/----------- ------------------------ ------------------------ ``` Function `i s e f` 'draws' one diamond of size `s`, where `e, f` are `(abs$z-y)(abs$z+y-1)`. Function `w` moves the diamonds drawn by `i` to correct places. `head` used in its definition is responsible for looking at the topmost layer only. [Try it here](https://tio.run/##RY7NToUwEIXX8hRDw6KFFlP82UB5Al25hC6q5QbiZUrkGuGKz45zjcbNzHfmZM5M7@bX7njc9wFm6OCwjW659Ho2jP2JigSwrTOGoG3ZpqvCsGsWfQDCCovpO@cTHz59pRqd52jLQKSK1Oc5FVueSfKXMPNpSDkqL4RIQ7bYcuDkC@6e5@Ss1l/IVqXFV5bR0Qjj3vRVUjea4vAShzY6ABpOmyhiQR7G9Mg@ugGND9HV6KZH4C2CquGHp/fT0@ntAYHTooC6/p8wJqDRspA38lbeyXu7fwM) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes ``` FN«↗×⊗⊕ι/↓↘G↖²→⊕×⁴⊕ι↘²\G←⁴↘⊕⊗ι→⁴\M⁴→‖T»‖M↓ ``` [Try it online!](https://tio.run/##VZCxDoIwEIZneYqmU5tgTAwuuLqYqCEENxashzYpLTkKxhifvRaQKFv73/X77iruBQpTKOdKg4Ttdd3aU1tdABnn5BUsEpTasvhcp/J2tyHJZAUN25n2ouDq@wVCBdr6s@Q8JHRFOd8Gi6PpgMU789Dz20Dpo8So583onnyA0oPXIYm/jn/q6IvmoVd51w84vKZ5TmfkkRvNG/8x0xbD5JM8@pGGsaOp1CcplAqEzbDQjf@wivnwHXzTo0Q0OG3t3MYtO/UB "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FN« ``` Draw the cubes from the smallest to the largest. (Drawing from the largest to the smallest meant that I ended up with a mirror image for odd numbers which cost too many bytes to fix.) ``` ↗×⊗⊕ι/ ``` Print a line of `/`s. (This will become the `\`s on the right, but the drawing is done mirrored because it's golfier to mirror at the end of the loop.) ``` ↓↘G↖²→⊕×⁴⊕ι↘²\ ``` Print the top two rows of `\`s. (Drawing all the `\`s in one polygon meant that the cursor ended up in an awkward position which cost too many bytes to fix.) ``` G←⁴↘⊕⊗ι→⁴\ ``` Print the left four rows of `\`s. (The fifth row comes from the previous cube.) ``` M⁴→ ``` Move to the start of the next cube. ``` ‖T» ``` Reflect horizontally ready for the next cube. ``` ‖M↓ ``` Mirror everything vertically to complete the cube. ]
[Question] [ ## Background ASCII art is the practice of creating images by using ASCII text to form shapes. Aliasing is the effect created by the large "pixels" of ASCII art, which are the size of characters. The image becomes blocky and hard to see. Anti-aliasing removes this effect by creating a gradient and by softening the hard edges of the ASCII art. # The Challenge Your challenge is to write the shortest program possible that will take a piece of ASCII art and will output a version that has been anti-aliased. ## What sort of anti-aliasing? All of the ASCII art will consist of two types of symbols: Spaces and non-whitespace. For each non-whitespace character, your program must determine whether it is in a position where it need to be anti-aliased. If it is, then you need to replace it with the correct character. If it isn't, then the character stays the same. How do you know if a character needs to be anti-aliased? The answer depends on the characters that are immediately above, below, left, and right of the character (**not the diagonals**). Here is a chart of when anti-aliasing is required, where `?` and `x` can stand for any non-whitespace character. ``` x? -> d? ? ? ?x -> ?b ? ? ? ? ?x -> ?F ? ? x? -> Y? x -> ; Note: This character has been changed from _ to ; ? ? ? ? x -> V ?x -> ?> x? -> <? x -> @ ``` ## Input (and example pre-anti-aliasing ASCII art) First, there will be two lines of input (to STDIN), a number H followed by a number W. There will then be H lines of exactly W characters each (excluding the newline). These following lines will be the ASCII art that needs to be anti-aliased. Here is an example input (not beautiful, but a test): ``` 7 9 888888 888888 999 98 7 666666 666666 6666 6 ``` ## Output (and example anti-aliased art) Your program should output to STDOUT the ASCII art (of the same dimensions), which has been anti-aliased. Here is the output for the above input. Notice how the the border characters are treated as bordering whitespace. ``` d8888> d8888F <99 98 @ Y6666b Y6666> Y66F V ``` This might not look that good (due to the space between lines in the code block), it looks better with larger ASCII art, and the quality depends on the exact font used. # Another Example Input ``` 12 18 xx xxx xxx xxxx xxx xxx xxxxxx xxx xxx xxx xxx xxx xxx xxxx xxx xxx xxx xxxxxx xxx xxx xxxx xxx xxx x xx xxx xxx x xx xxx xxx xx xxx xxx xxx xxx xxxx xxx xxx xx xxxxx xxx xxx x ``` Output ``` db <xb <xb dxxb Yxb Yxb dxxxxb Yxb Yxb dxx xxb xxb xxb Yxxb xxF xxF xxF YxxxxF dxF dxF YxxF dxF dxF ; YF dxF dxF ; xb dxF dxF dx xxb <xF <xF <xx xxxb Yxb Yxb Yx Yxxx> Yx> Yx> V ``` # Rules, Restrictions, and Notes Your program should be written in printable ASCII characters only, so that we can make art out of the programs. Other than that, the standard code-golf rules apply. [Answer] ### Ruby, 180 168 characters ``` gets w=1+gets.to_i f=*(readlines*"").chars f.zip(f[1..-1]+s=[" "],s+f,s*w+f,f[w..-1]+s*w){|a,*b|$><<"@;V#{a}>bF#{a}<dY#{a*5}"[a>" "?(b.map{|y|y>" "?1:0}*"").to_i(2):3]} ``` Another Ruby implementation which takes a zip approach. You can see the second example [running online](http://ideone.com/HShcb). *Edit:* Using `readlines` saves 12 characters. [Answer] ### Ruby ~~275~~ ~~265~~ ~~263~~ ~~261~~ ~~258~~ ~~254~~ ~~244~~ ~~243~~ ~~214~~ ~~212~~ 207 ``` H=0...gets.to_i W=0...gets.to_i G=readlines z=->x,y{(H===y&&W===x&&' '!=G[y][x])?1:0} H.map{|j|W.map{|i|l=G[j][i] G[j][i]="@V;#{l}>Fb#{l}<Yd#{l*5}"[z[i+1,j]*8+z[i-1,j]*4+z[i,j+1]*2+z[i,j-1]]if' '!=l}} puts G ``` Sample 1: <http://ideone.com/PfNMA> Sample 2: <http://ideone.com/sWijD> [Answer] ## Python, 259 chars ``` H=input() W=input()+1 I=' '.join(raw_input()for i in' '*H) for i in range(H):print''.join(map(lambda(s,a,b,c,d):(s*5+'dY<'+s+'bF>'+s+';V@'+' '*16)[16*(s==' ')+8*(a==' ')+4*(b==' ')+2*(c==' ')+(d==' ')],zip(I,I[1:]+' ',' '+I,I[W:]+' '*W,' '*W+I))[i*W:i*W+W-1]) ``` The program reads the input into a single string `I` (with spaces separating the lines), zips up a list of 5-tuples containing the character and its four surrounding characters, then looks up the result character using string indexing. [Answer] Javascript, 410 characters: ``` function(t){m={"10110":"b","11100":"d","01101":"Y","00111":"F","10100":";","00101":"V","00110":">","01100":"<","00100":"@"},d="join",l="length",t=t.split('\n').splice(2),t=t.map(function(x)x.split('')),f=function(i,j)t[i]?(t[i][j]||' ')==' '?0:1:0;for(o=t[l];o--;){for(p=t[o][l];p--;){y=[f(o+1,p),f(o,p+1),f(o,p),f(o,p-1),f(o-1,p)],t[o][p]=m[y[d]('')]||t[o][p]}}t=t.map(function(x)x[d](''))[d]('\n');return t;} ``` ungolfed: ``` function(t){ m={ "10110":"b", "11100":"d", "01101":"Y", "00111":"F", "10100":";", "00101":"V", "00110":">", "01100":"<", "00100":"@" }, d="join", l="length", t=t.split('\n').splice(2), t=t.map(function(x) x.split('')), f=function(i,j) t[i]?(t[i][j]||' ')==' '?0:1:0; for(o=t[l];o--;){ for(p=t[o][l];p--;){ y=[f(o+1,p),f(o,p+1),f(o,p),f(o,p-1),f(o-1,p)], t[o][p]=m[y[d]('')]||t[o][p] } } t=t.map(function(x)x[d](''))[d]('\n'); return t; } ``` Original, ~~440 characters~~: ``` function (t){m={"10110":"b","11100":"d","01101":"Y","00111":"F","10100":";","00101":"V","00110":">","01100":"<","00100":"@"},s="split",d="join",l="length",t=t[s]('\n').splice(2),t=t.map(function(x) x[s]('')),f=function(i,j)i<0||i>=t[l]?0:(j<0||j>=t[i][l]?0:t[i][j]==' '?0:1);for(o=t[l];o--;){for(p=t[o][l];p--;){y=[f(o+1,p),f(o,p+1),f(o,p),f(o,p-1),f(o-1,p)],h=m[y[d]('')];if(h){t[o][p]=h}}}t=t.map(function(x) x[d](''))[d]('\n');return t;} ``` N.B. I've assumed that the first two input lines are actually irrelevant and the size of the following lines are a correct. I'm also reckoning I might be able to chop a few more chars off this when I get a chance! [Answer] ## PHP - ~~359~~ ~~330~~ ~~282~~ ~~268~~ 257 characters ``` <?php $i=fgets(STDIN)+0;$w=fgets(STDIN)+1;$s='';$m='@<;d>0b0VY00F000'; for(;$i--;)$s.=fgets(STDIN); for(;++$i<strlen($s);){ $b=trim($s[$i])?0:15; foreach(array($i+1,$i+$w,$i-1,$i-$w)as$k=>$x) $b|=pow(2,$k)*(isset($s[$x])&&trim($s[$x])); echo $m[$b]?$m[$b]:$s[$i];} ``` [Answer] # Python, 246 241 ``` H=input();W=1+input() S=' ' o=W*S F=o+'\n'.join((raw_input()+o)[:W-1]for k in range(H))+o print ''.join((16*x+'@;<d>b'+2*x+'V'+x+'Y'+x+'F'+3*x)[ 16*(x>S)|8*(a>S)|4*(l>S)|2*(r>S)|(b>S)]for x,a,l,r,b in zip(F[W:-W],F,F[W-1:],F[W+1:],F[2*W:])) ``` WC and test on sample 2, diffed with the output of the Ruby solution at the top: ``` t:~$ wc trans.py && python trans.py < lala2 > o && diff -q o ruby_out2_sample 2 11 241 trans.py t:~$ ``` [Answer] ## C# ~~591~~ 563 ``` string A(string t){var s=new StringReader(t);var h=int.Parse(s.ReadLine());var w=int.Parse(s.ReadLine());var lines=s.ReadToEnd().Split(new[]{"\r\n"},StringSplitOptions.None).Select(x=>x.ToCharArray()).ToArray();for(var i=0;i<h;i++)for(var j=0;j<w;j++){var c=lines[i][j];if(c==' ')continue;var n=(i>0?(lines[i-1][j]!=' '?1:0):0)+(i<h-1?(lines[i+1][j]!=' '?2:0):0)+(j>0?(lines[i][j-1]!=' '?4:0):0)+(j<w-1?(lines[i][j+1]!=' '?8:0):0);lines[i][j]=new[]{'@','V',';',c,'>','F','b',c,'<','Y','d',c,c,c,c,c}[n];}return string.Join("\r\n",lines.Select(l=>new string(l)));} ``` ]
[Question] [ Inspired by [this xkcd](http://xkcd.com/851_make_it_better/) [![enter image description here](https://i.stack.imgur.com/AWTyS.png)](https://i.stack.imgur.com/AWTyS.png) You work for [Shazam](https://en.wikipedia.org/wiki/Shazam_(service)) and they have a project for you. Some customers are complaining about their app taking up too much space on their phone, so they want you to code a lite version of the app. Unfortunately, your existing code can only understand the word "na", and you have to ship soon. That's okay, we'll do the best with what we've got. # The Challenge You must write a full program that takes a user input, or takes a command line argument, and print the title and artist of the song. Since we are trying to fix customers complaining about program size, your code must be as short as possible. The input will be a string consisting entirely of na's, with a single space between them. Lowercase/uppercase is arbitrary. This is considered a valid input: `Na Na nA na NA` This is an invalid input: `nah nah NA naNa banana` You must determine what song is playing and print it out in exactly this format: ``` Song: <trackname> Artist: <artist> ``` If the input is *exactly* 8 na's, this matches two separate songs, so you must print both: ``` Song: Batman Theme Artist: Neal Hefti ``` and ``` Song: Na Na Hey Hey Kiss Him Goodbye Artist: Steam ``` If the input is *exactly* 10 na's, you must print: ``` Song: Katamari Damacy Artist: Yuu Miyake ``` If the input is *exactly* 11 na's, you must print: ``` Song: Hey Jude Artist: The Beatles ``` If the input is 12 or more na's, you must print ``` Song: Land Of 1000 Dances Artist: Wilson Pickett ``` Lastly, if the input is invalid, there are less than 8 na's, or any of the words are not "na", your program fails to understand the music. So logically, there is only one other song that it could possibly be. You must print: ``` Song: Africa Artist: Toto ``` As usual, standard loopholes apply, and the shortest answer in bytes wins. [Answer] # [Retina](https://github.com/mbuettner/retina/), 242 [Try it online!](http://retina.tryitonline.net/#code=aUdgXm5hKCBuYSkqJAppTWBuYQptYF44JAo-QmF0bWFuIFRoZW1lLE5lYWwgSGVmdGkkbj5OYSBOYSBIZXkgSGV5IEtpc3MgSGltIEdvb2RieWUsU3RlYW0KbWBeMTAkCj5LYXRhbWFyaSBEYW1hY3ksWXV1IE1peWFrZQptYF4xMSQKPkhleSBKdWRlLFRoZSBCZWF0bGVzClswLTldLisKPkxhbmQgT2YgMTAwMCBEYW5jZXMsV2lsc29uIFBpY2tldHQKbWBeWzAtOV0KPkFmcmljYSxUb3RvCj4KU29uZzogCiwKJG5BcnRpc3Q6IA&input=) ``` iG`^na( na)*$ iM`na m`^8$ >Batman Theme,Neal Hefti$n>Na Na Hey Hey Kiss Him Goodbye,Steam m`^10$ >Katamari Damacy,Yuu Miyake m`^11$ >Hey Jude,The Beatles [0-9].+ >Land Of 1000 Dances,Wilson Pickett m`^[0-9] >Africa,Toto > Song: , $nArtist: ``` # How it works: IgnoreCase flag + Grep mode flag + Regex `^na( na)*$`. If the input is valid, print it as is. If not, print nothing. ``` iG`^na( na)*$ ``` IgnoreCase flag + Match mode flag + Regex `na`. Count the "na"s and print the number. ``` iM`na ``` If the string is exactly "8", replace by the second line. ``` m`^8$ >Batman Theme,Neal Hefti$n>Na Na Hey Hey Kiss Him Goodbye,Steam ``` If the string is exactly "10", replace by the second line. ``` m`^10$ >Katamari Damacy,Yuu Miyake ``` If the string is exactly "11", replace by the second line. ``` m`^11$ >Hey Jude,The Beatles ``` If the string matches `[0-9].+`, replace by the second line. This is neither true for single digit numbers, `10` and `11` as they already have been repaced nor any of the above replacement strings. ``` [0-9].+ >Land Of 1000 Dances,Wilson Pickett ``` If none of the above matched, the string still starts with a number. Default to Toto, Africa. ``` m`^[0-9] >Africa,Toto ``` Replace the placeholders `>` and `,` by `Song:` and `Artist:`. ``` > Song: , $nArtist: ``` [Answer] # JavaScript (ES6), 276 bytes ``` alert(`Song: `+([,`Batman Theme,Neal Hefti Song: Na Na Hey Hey Kiss Him Goodbye,Steam`,,`Katamari Damacy,Yuu Miyake`,`Hey Jude,The Beatles`,`Land Of 1000 Dances,Wilson Pickett`][+prompt(i=0).replace(/na( |$)/gi,_=>++i)&&(i>11?4:i-7)]||`Africa,Toto`).replace(/,/g,` Artist: `)) ``` ## Explanation Input can optionally contain one trailing space. ``` alert( // output the result `Song: `+([ // insert the "Song:" label , // set the first element to undefined in case input is empty // Songs `Batman Theme,Neal Hefti Song: Na Na Hey Hey Kiss Him Goodbye,Steam`, , `Katamari Damacy,Yuu Miyake`, `Hey Jude,The Beatles`, `Land Of 1000 Dances,Wilson Pickett` ][ + // if the input string was made up only of "na"s, the replace would // return a string containing only digits, making this return a // number (true), but if not, this would return NaN (false) prompt( // get the input string i=0 // i = number of "na"s in input string ).replace( // replace each "na" with a number /na( |$)/gi, // find each "na" _=>++i // keep count of the "na"s and replace with a (non-zero) number ) &&(i>11?4:i-7) // select the song based on the number of "na"s ] ||`Africa,Toto` // default to Africa ).replace(/,/g,` Artist: `) // insert the "Artist:" label ) ``` ## Test ``` var prompt = () => input.value; var alert = (text) => result.textContent = text; var solution = () => { alert(`Song: `+([,`Batman Theme,Neal Hefti Song: Na Na Hey Hey Kiss Him Goodbye,Steam`,,`Katamari Damacy,Yuu Miyake`,`Hey Jude,The Beatles`,`Land Of 1000 Dances,Wilson Pickett`][+prompt(i=0).replace(/na( |$)/gi,_=>++i)&&(i>11?4:i-7)]||`Africa,Toto`).replace(/,/g,` Artist: `)) } ``` ``` <input type="text" id="input" value="na na Na na NA na na nA" /> <button onclick="solution()">Go</button> <pre id="result"></pre> ``` [Answer] # PowerShell, 278 bytes * Can handle any amount of whitespace * No regex whatsoever! * Implicit typecasting FTW! ``` @{8='Batman Theme/Neal Hefti','Na Na Hey Hey Kiss Him Goodbye/Steam' 10='Katamari Damacy/Yuu Miyake' 11='Hey Jude/The Beatles' 12='Land Of 1000 Dances/Wilson Pickett'}[[math]::Min($args.Count*!($args|?{$_-ne'na'}),12)]|%{'Song: {0} Artist: {1}'-f($_+'Africa/Toto'*!$_-split'/')} ``` # Ungolfed ``` @{8='Batman Theme/Neal Hefti','Na Na Hey Hey Kiss Him Goodbye/Steam' # array 10='Katamari Damacy/Yuu Miyake' 11='Hey Jude/The Beatles' 12='Land Of 1000 Dances/Wilson Pickett'} # Hashtable of songs [ # Get value by key from hashtable # If key is invalid, silently return null value [math]::Min( # Clamp max value to 12 $args.Count* # Multiply count of argumens # true/false will be cast to 1/0 ! # Negate result of expression # Will cast empty array to 'false' # and non-empty array to 'true' ( # Return non-empty array if input arguments # contain anything other than 'na' $args | Where-Object {$_ -ne 'na'} ), 12 ) ] | ForEach-Object { # Send value from hashtable down the pipeline, # This allows to process arrays in hasthable values 'Song: {0} Artist: {1}' -f ( # Format string $_+ # Add to current pipeline variable 'Africa/Toto'*!$_ # If pipeline variable is empty, # then add default song to it # Example: 'Test'*1 = 'Test' # 'Test'*0 = null -split '/' # Split string to array for Format operator ) } ``` # Usage ``` PS > .\WhatSong.ps1 na na na na na na na na Song: Batman Theme Artist: Neal Hefti Song: Na Na Hey Hey Kiss Him Goodbye Artist: Steam PS > .\WhatSong.ps1 Na na na na na na na na na Na Song: Katamari Damacy Artist: Yuu Miyake PS > .\WhatSong.ps1 Na na na na na na na na na BanaNa Song: Africa Artist: Toto ``` [Answer] # sh + coreutils, 290 Albeit longer than my other submission, this one is straightforward and pretty much ungolfed, so i included it anyway. ``` grep -Ei "^na( na)*$"|wc -w|awk '{s="Song: ";a="\nArtist: ";p=s"Africa"a"Toto"}$1==8{p=s"Batman Theme"a"Neal Hefti\n"s"Na Na Hey Hey Kiss Him Goodbye"a"Steam"}$1>9{p=s"Katamari Damacy"a"Yuu Miyake"}$1>10{p=s"Hey Jude"a"The Beatles"}$1>11{p=s"Land Of 1000 Dances"a"Wilson Pickett"}{print p}' ``` # How it works: If the input is valid, print it as is. If not, print nothing. ``` grep -Ei "^na( na)*$" ``` Count the words. ``` wc -w ``` Simple look up table, `Song:` and `Artist:` are kept in variables. ``` awk ' {s="Song: ";a="\nArtist: ";p=s"Africa"a"Toto"} $1==8{p=s"Batman Theme"a"Neal Hefti\n"s"Na Na Hey Hey Kiss Him Goodbye"a"Steam"} $1>9{p=s"Katamari Damacy"a"Yuu Miyake"} $1>10{p=s"Hey Jude"a"The Beatles"} $1>11{p=s"Land Of 1000 Dances"a"Wilson Pickett"} {print p} ' ``` [Answer] # Python ~~453~~ ~~440~~ ~~406~~ 380 bytes **EDIT:** Thanks to Cyoce for reducing 13 bytes! **EDIT:** Thanks again to Cyoce! **EDIT:** Thanks to RainerP. for helping me imrpove the algorithm on certain invalid cases. This is a rough draft of a Python program. I believe it can be definitely golfed, maybe to 300-400 bytes. But will work on that soon. ``` f=0 S='Song:' A='\nArtist:' l="Batman Theme,Neal Hefti,Na Na Hey Kiss Him Goodbye,Steam,Katamari Damacy,Yuu Miyake,Hey Jude,Beatles,Land of the 1000 Dances,Wilson Pickett,Africa,Toto".split(',') s=raw_input().lower()+" " n=s.count("na ") n*=n*3==len(s) if n>11:f=8 if n==10:f=4 if n==11:f=6 if n<8or n==9:f=10 if f:print S+l[f]+A+l[f+1] else:print S+l[0]+A+l[1]+"\n"+S+l[2]+A+l[3] ``` [Try here!](http://ideone.com/tinWZu) [Answer] # Julia, 325 bytes Probably could be golfed further. ``` p(s,a)=println("Song: $s\nArtist: $a");ismatch(r"^(na )*na$",ARGS[1])&&(c=length(split(ARGS[1],"na"))-1)==8?(p("Batman Theme","Neal Hefti"),p("Na Na Hey Hey Kiss Him Goodbye","Steam")):c==10?p("Katamari Damacy","Yuu Miyake"):c==11?p("Hey Jude","The Beatles"):c>=12?p("Land Of 1000 Dances","Wilson Pickett"):p("Africa","Toto") ``` [Answer] # Rust, ~~501~~ 477 bytes ``` fn main(){let(mut i,mut n)=(String::new(),0);let(s,a);std::io::stdin().read_line(&mut i);i=i.trim().to_lowercase();let o=i.split(" ");for w in o{if w!="na"{n=0;break}else{n+=1}}match n{8=>{println!("Song: Batman Theme\nArtist: Neal Hefti");s="Na Na Hey Hey Kiss Him Goodbye";a="Steam"}10=>{s="Katamari Damacy";a="Yuu Miyake"}11=>{s="Hey Jude";a="The Beatles"}_=>{if n>=12{s="Land Of 1000 Dances";a="Wilson Pickett"}else{s="Africa";a="Toto"}}}print!("Song: {}\nArtist: {}",s,a)} ``` Ungolfed ``` fn main() { let (mut input_string, mut na_counter) = (String::new(), 0); let (song_name, artist_name); std::io::stdin().read_line(&mut input_string); input_string = input_string.trim().to_lowercase(); let output = input_string.split(" "); for word in output { if word != "na" { na_counter = 0; break; } else { na_counter += 1; } } match na_counter { 8 => { println!("Song: Batman Theme\nArtist: Neal Hefti"); song_name = "Na Na Hey Hey Kiss Him Goodbye"; artist_name = "Steam"; } 10 => { song_name = "Katamari Damacy"; artist_name = "Yuu Miyake"; } 11 => { song_name = "Hey Jude"; artist_name = "The Beatles"; } _ => { if na_counter >= 12 { song_name = "Land Of 1000 Dances"; artist_name = "Wilson Pickett"; } else { song_name = "Africa"; artist_name = "Toto"; } } } print!("Song: {}\nArtist: {}", song_name, artist_name); } ``` Edit: removed an unnecessary to\_string and type annotations [Answer] # [Perl 5](https://www.perl.org/) `-pa`, 248 bytes ``` $_=/^(na ?)+$/&&(@F==8?",Batman Theme;Neal Hefti,Na Na Hey Hey Kiss Him Goodbye;Steam":@F==10?"Katamari Damacy;Yuu Miyake":@F==11?",Hey Jude;The Beatles":@F>11?",Land Of 1000 Dances;Wilson Pickett":0)||",Africa;Toto";s/;/ Artist: /gm;s/,/ Song: /gm ``` [Try it online!](https://tio.run/##bY9BS8NAEIXv/RXDUkqLkd0cBMkSY4tosFqFFsSLMiaTujS7G7KbQ6C/3bgJHoU3DDNv@B7TUFtfDcP8M@UfS4OQrS7mfLFY3t6n6XXGog16jQYO36RJ7ghryKnyKtohBOXUT7VVzkGuNDxYW371JPeeULNkpMQiY1v0qLFVcBda0cv3roNn1eOJ/m7iEDWCHruSZAiDDaGvyY32zeQ@oSnhpYJYCBEwpiAn31TtrIFXVZzIe5aI1fnMonXVqgLlwXrLpOOSz9atV84nwI86LCI@21tznMZhCD//px/beGWNGy4b/AU "Perl 5 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), ~~312~~ 292 bytes ``` $_=lc<>;$n="(na ?)";/^(na ){7}na$|(na ){9,}na/ or$_="%Africa&Toto";s/$n{12,}/%Land Of 1000 Dances&Wilson Pickett/;s/$n{11}/%Hey Jude&The Beatles/;s/$n{10}/%Katamari Damacy&Yuu Miyake/;s/$n{8}/%Batman Theme&Neal Hefti\n%Na Na Hey Hey Kiss Him Goodbye&Steam/;s/&/\nArtist: /g;s/%/Song: /g;print ``` [Try it online!](https://tio.run/##NVB/S8NADP0qobSHg8G1gvijTukQLE47YQMRhhLbdB5rc6N3/aPMffZ6rRMSeC/v5QWyp6a66Hv/c1blt3exzzPvjBHuJ14sPwY0OVweGf2fP3w9dUSCbtyCFyRlo3IUa221Fxvp8yE6nx5l8IxcwLKEKAxDeEDOyYg3VRnN8KryHVkrT/bIuVPq4KktSKy/CeaEtiLzr4dOX6DFGhvlkmrMO/HetvCiOtzRyXXlTHO0NTK4iJpERlhBSqVVGw4yBFfDkaEXyhhIVQ2PWhdfHYmVJayHICE3nDRWGXsDcusGgVxp3o5k3yi2fe9ewGPaABLIkhHgLw "Perl 5 – Try It Online") Ungolfed: ``` $_ = lc <STDIN>; $_ =~ /^(na ){7}na$|(na ){9,}na/ or $_ = "%Africa&Toto"; $_ =~ s/(na ?){12,}/%Land Of 1000 Dances&Wilson Pickett/; $_ =~ s/(na ?){11}/%Hey Jude&The Beatles/; $_ =~ s/(na ?){10}/%Katamari Damacy&Yuu Miyake/; $_ =~ s/(na ?){8}/%Batman Theme&Neal Hefti\n%Na Na Hey Hey Kiss Him Goodbye&Steam/; $_ =~ s/&/\nArtist: /g; $_ =~ s/%/Song: /g; print $_ ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~403~~ ~~395~~ ~~370~~ ~~365~~ ~~364~~ 362 bytes -8 -5 -1 = -14 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) Pretty much as straight-forward as can be. ``` f(char*s){int*a[]={"Neal Hefti","Steam","Yuu Miyake","The Beatles","Wilson Pickett","Toto","Batman Theme","Na Na Hey Hey Kiss Him Goodbye","Katamari Damacy","Hey Jude","Land Of 1000 Dances","Africa"},i,l=0,j=1;for(;*s;s+=3-!s[2])i=(*s|32)^'n'|(s[1]|32)^97|s[2]>32,l++;for(i=i?5:l^8?l^10?l^11?l>11?4:5:3:2:j++;j--;)printf("Song: %s\nArtist: %s\n",a[6+i--],a[i]);} ``` [Try it online!](https://tio.run/##lZB9a9swEMb/bj7FzTBqJza17HXLbNyQMljoSzroYIzEgasjt5fIcrGUQkjy2VPZKaQNK3TmrNPpfs9zQpl3n2XbbW5nD1i1lbMiqds4SpOVNeQoYMBzTZZr3WqOhcl/Fwu4piXOuSl@P3A456gFV6b6Q0KVEn5RNuda1@1Slyadoy5QgoGLWjREMDHgy@a/JKVgQAX8LMvp3bIGLlFjgRXBD5OypTmpwYvFtG5eoZzCTQ7M930DyKwZ3c8rytDauOSKxHdnCYvzsrLjtopVJwm9T2oUpA4ldlutw8CZHMvjta1GLG2q79/Wdf8sDFzR6TRKSqh3GolJtycmzK8X1hNnZvkSnUZhFEQzA848L3YeK/NiuW3dlvI@gs9qLPuVJqV3e8vF0dcOeV5qNpQ68WZrcCiQpO20Vq2jx4VWttUFm@QTCpo6Y@mZz3Li1pFxnZfVk0R4Jxpq5zCW4XseEu9Q4gEdHDI7Ozg5gWBPMf8f2GEM97ep5czf67sfkMs@vCi7rwazjyjfvEQzm72yCP/P4q1R2NpsnwE "C (gcc) – Try It Online") [Answer] # UNIX Shell, 394 bytes ``` uudecode -p<<<'begin-base64 0 - /Td6WFoAAATm1rRGAgAhARwAAAAQz1jM4AE9AIRdACmbycaLOYv90Azj3HBohRZGa6a5FikeJU+8JbGlB4f9wmi2aQ+mn81aypMRM4nEKPxW439Z2C4WfGeyrREjk427H1GrCRUMHdth+9lVBDiPfCaD8WpStyS0MtJenHKB+tou8rD9INq0yw9IPXuQe7zLM3p14ZDFO8UoJp66scd4bKQAAACSwUb7ERvesgABoAG+AgAARAEAGbHEZ/sCAAAAAARZWg== ===='|unxz|sed -n $#s/,/\\n/gp|grep .||echo $'Song: Land Of 1000 Dances\nArtist: Wilson Pickett' ``` Test: ``` ; sh $THE_FILE na na na na na na na Song: Batman Theme Artist: Neil Hefti Song: Na Na Hey Kiss Him Goodbye Artist: Steam ``` Probably could be optimized, but I just liked this idea TBH :) [Answer] # Java 8, 353 bytes ``` s->{int n=s.split(" ").length,b=s.matches("(na ?)+")?1:0;s="Africa";return"Song: "+(b>0?n<8?s:n<9?"Batman Theme\nArtist: Neal Hefti\nSong: Na Na Hey Hey Kiss Him Goodbye":n>11?"Land of 1000 Dances":n>10?"Hey Jude":n>9?"Katamari Damacy":"":s)+"\nArtist: "+(b>0?n<8?"Toto":n<9?"Steam":n>11?"Wilson Pickett":n>10?"The Beatles":n>9?"Yuu Miyake":"":"Toto");} ``` **Explanation:** [Try it online.](https://tio.run/##lVNRa9tADH7frxD3ZJPVOG@b3cSkDBbW1QxSGGPtg3y@JNfYuuCTC6bkt2eK7a4ttGwFCe4kff50@uQ7vMcztzd0V@6OukLv4QotPXwAsMSmWaM2kJ@uACtuLG1AB@PBh6nED@JinpGthhwIZnD0Z/MHwQPNfOT3leVAgQqjytCGtx8LidbIemt8oAJCyMKJCrNpEqd@phbrxmpUaWO4bUitHG0SUJOgmMcZnX/KfELnnzN1gVwjwfXW1OaGFg1bzwnkBitYmjXbGxqQOZ5sabreL628cGlr@OpcWXRGJTSfTjP1HakEt4ZpHMfwBUkb36fiTJ1g39qyLxXeS2SssbFSVaPuVKJU4qX/px6e9aquHTs1NLxig/Uj309beUfww@qdYX6kksfAhUGuBnYB/WpbuLId7kxPNHwvTA/HdBj7vi0qGfs4/XtnS6hFv1Gi37cYDtqx8aKBjPo1U72Q/yh6d@m7q98EvIwWFcLoLxMiMy0gXwiih23/l16Ni/y0xv0ge9jfXR//gc6zqSPXcrSXBFcU@InoMjK9kqZIBz58Oz9yH45/AA) ``` s->{ // Method with String as both parameter and return-type int n=s.split(" ").length, // The amount of words when split by spaces b=s.matches("(na ?)+")?1:0;// Whether the input matches the regex "^(na ?)+$" s="Africa"; // Set the input we no longer need to "Africa" return"Song: " // Return "Song: " +(b>0? // +If the input matched the regex: n<8? // If there are less than 8 "na"'s: s // Append "Africa" :n<9? // Else-if there are exactly 8 "na"'s: "Batman Theme\nArtist: Neal Hefti\nSong: Na Na Hey Hey Kiss Him Goodbye" // Append the String above :n>11? // Else-if there are 12 or more "na"'s: "Land of 1000 Dances" // Append "Land of 1000 Dances" :n>10? // Else-if there are exactly 11 "na"'s: "Hey Jude" // Append "Hey Jude" :n>9? // Else-if there are exactly 10 "na"'s: "Katamari Damacy" // Append "Katamari Damacy" : // Else (there are exactly 9 "na"'s): "" // Append nothing : // Else: s) // Append "Africa" +"\nArtist: " // +Append a new-line and "Artist: " +(b>0? // +If the input matched the regex: n<8? // If there are less than 8 "na"'s: "Toto" // Append "Toto" :n<9? // Else-if there are exactly 8 "na"'s: "Steam" // Append "Steam" :n>11? // Else-if there are 12 or more "na"'s: "Wilson Pickett" // Append "Wilson Pickett" :n>10? // Else-if there are exactly 11 "na"'s: "The Beatles" // Append "The Beatles" :n>9? // Else-if there are exactly 10 "na"'s: "Yuu Miyake" // Append "Yuu Miyake" : // Else (there are exactly 9 "na"'s): "" // Append nothing : // Else: "Toto");} // Append "Toto" ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 148 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` l#„naQW*O5Ý8+@OI5£“‹…0Toto ߃›Ì0Neal Hefti0ÿ¤·¤··—„š‚¿bye0ÁÜ KatamariÊÖacy0Yuu Miyake ¤· Jude0€€ÊÄ ˆÑ€‚ 2–›s0¦‹šèett“¶¡0δ¡2₄:¬2ǝ„ŽŸŒá#ÞrèðδÛø„: ý»™ ``` [Try it online](https://tio.run/##NU6xSgNBEO33KxbSabMcBCSV6dRgQkAQy42ucBjvINkrrlvDYSE2RrGISWRVQooUFiGJSgjMcFoI@Yj5kcueILyBebyZ917Ylg1fZVmzQGYYyPrxVq2Ig53t3dp@EV7J9Ml8kBmJo1CHDJ@/u2Q@8VZUlWzyPXWufYEreIP538zJPDib1JLpwaoRK4FX2GesIrW8lC0fb/BRnsbiJIr4oR/LC8XyP34QnSlBnYmDO0nY7zXe5dT0uEfm3kW2BYxck9TiWGntasEMrFhPwXrUSUow8X4GefIyXaRdtAUctnCM7@spPuHCCSWOS/ii5CXLqpI7BGUeuKXM/@kG) or [verify some more test cases](https://tio.run/##jU5NS0JBFN3Prxh0Vy4GQQg35q4PUoIgWo410SMbQ@cFD1pMIi2iTRYtTI1XIS5ctBC1QoS5vFoE/oj5I68Z3dhCC86Fc@85955bKNGcw8Lzs8g6P3VFEkdSXgxFsq6YdjEvzEe1bHK6vbuUTUBjZXk16yXUs5Z1Ld@0bJGdgiggePysavkO1yTDaB6vsUPhEBipF9WfVF/LO3Mm8LWsqVHOYwQuoI7QJhX0hBYduIJ7uu@RPdfFW45Hjxmye3jDPWBElzsGxlJB35dwY1tZw3Etb01kiaiW@STwoc2EMG@pnvLJuKv8uC5XkqoT/2rY5GEwCKrgR6FZhDa8jrvwAAMjJDEM1YeuPIUx1UuFnKIMxQY8jbkhacTpEbaVsQMj5Cin1jXVJ8YZPm@O569M@WLV8D8Ni9J/83/aLJ/BDw). **Explanation:** ``` l # Convert the (implicit) input-string to lowercase # # Split it on spaces (if there are any) „naQ # Check for each word if it's equal to "na" (1 if truthy; 0 if falsey) W # Push its minimum, without popping the list itself * # Multiply that to all integers # (if any word wasn't "na", the entire list now only contains 0s) O # Sum this list to get the amount of "na"s 5Ý # Push the list [0,1,2,3,4,5] 8+ # Add 8 to each: [8,9,10,11,12,13] @ # Check for each if the sum is larger than or equal to this value # (1 if sum>=n, 0 if sum<n) O # Sum to get the amount of truthy values I # Push the input-string 5£ # Pop and only leave its first 5characters (if it's a valid string, # this will be "na na" - with variable casing) “‹…0Toto ߃›Ì0Neal Hefti0ÿ¤·¤··—„š‚¿bye0ÁÜ KatamariÊÖacy0Yuu Miyake ¤· Jude0€€ÊÄ ˆÑ€‚ 2–›s0¦‹šèett“ # Push dictionary string "africa0 Toto\nbatman theme0Neal Hefti0ÿ hey hey kiss him goodbye0 steam\n\nKatamari damarcy0Yuu Miyake\nhey Jude0 the beatles\nland of 2 dances0 wilson pickett", # where the `ÿ` is automatically replaced with the 5-char string ¶¡ # Split this string on newlines 0δ¡ # And then split each inner string on 0s # [["africa"," Toto"], # ["batman theme","Neal Hefti","na na hey hey kiss him goodbye"," steam"], # [], # ["Katamari damarcy","Yuu Miyake"], # ["hey Jude"," the beatles"], # ["land of 2 dances"," wilson pickett"]] 2₄: # Replace the 2 with 1000 ¬ # Get the first pair (without popping): ["africa"," Toto"] 2ǝ # Insert it at (0-based) index 2, replacing the empty list „ŽŸŒá # Push dictionary string "song artist" # # Split it on spaces: ["song","artist"] Þ # Cycle this list infinitely: ["song","artist","song","artist",...] r # Reverse the values on the stack è # Modulair 0-based index the sum of truthy values into the list of lists of # artist(s)/song(s), so 6 will wrap back to the first item δ # Map over each string inside each inner list: ð Û # And trim all leading spaces ø # Create pairs with the infinitely cycled list, where it will only create # as many pairs as the smallest list (so either 2 or 4 in this case) „: ý # Join each inner pair with ": " delimiter » # Then join everything by newlines ™ # And finally titlecase each word in the string # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `“‹…0Toto ߃›Ì0Neal Hefti0ÿ¤·¤··—„š‚¿bye0ÁÜ\n\nKatamariÊÖacy0Yuu Miyake\n¤· Jude0€€ÊÄ\nˆÑ€‚ 2–›s0¦‹šèett“` is `"africa0 Toto\nbatman theme0Neal Hefti0ÿ hey hey kiss him goodbye0 steam\n\nKatamari damarcy0Yuu Miyake\nhey Jude0 the beatles\nland of 2 dances0 wilson pickett"` and `„ŽŸŒá` is `"song artist"`. ]
[Question] [ You are an explorer, mapping an unknown world. Your ship is carried on the wind. Where it goes, who knows? Each day, in your spyglass, you see features to the north, south, east and west. You always see four such features, corresponding to the cardinal directions. Your spyglass reports ASCII symbols like this: `~~.*`, `~~~~`, `~.^^`, `~#~#` The symbols are in the order (north, south, east, west). These are the symbols: `~` = sea, `.` = coast, `^` = mountain, `*` = tree, `#` = invalid (no observation, this occurs whenever you see the edge of the world, or the landscape is obscured by fog). Your spyglass sees exactly one unit in every direction. Each night, you look up at the stars to see how far you've travelled. Looking at the stars reports an ascii symbol like this: `n`, `s`, `e`, `w` corresponding to North, South, East and West, respectively. You always move exactly one unit to the north, south, east or west every night. So you, as explorer will be receiving an endless stream of symbols: `~~.*n~~~~s~~.*s~.**` Your task is to output a 2D map of the world (where `?` are unknown parts of the map, north is up, east is right): ``` ?~~~?????? ?~~~?????? ?~~~.^^.?? ?~~.***.~~ ~~.*^^*.~~ ~~~..~~~~~ ~~~~~~~~~~ ~~~~~~~~~~ ``` For the sake of simplicity let's assume you start in the bottom left corner of the map. Assume all maps are 8x8. Here is a simple 3x3 example. Assume the map looks like this: ``` ~.~ ~^~ ~.~ ``` With the following input: `~#.#n~~^#s` You will get this output: ``` ~?? ~^? ~.? ``` More example inputs and outputs: input `~#~#n~~~#n~~~#n~~~#n~~~#n~~.#n~~.#n#~~#e#.~~e#.~~e#.~~e#.~~e#~~~e#~~~e#~#~s~~#~s~~#~s~~#~s~~#.s~~#~s~~#~s~##~w~#~~w.#~~w^#~~w.#~~` output ``` ~~~~~~~~ ~....~~~ ~.????~~ ~~????~~ ~~????.~ ~~????~~ ~~?.^.~~ ~~~~~~~~ ``` Input: `~#~#e~#~~e~#~~e.#~~e^#~~n.~..n~^~.n~.~~n.~~.n.~~*n~.~.n#.~~w#.~~w#.~~s~*..s..*.s*~.~s.~~~s` Output: ``` ?~~~~~?? ?....~?? ?.**.~?? ?~..~~?? ?~~~~~?? ?~~..~?? ~~~.^.?? ~~~~~~?? ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~68~~ ~~59~~ 58 bytes ``` '?'7XJQtX"'s'jh5e"@2#1)t35>)-1l8t_4$h9M)b'nsew'=8M*sJ+XJ+( ``` [**Try it online!**](http://matl.tryitonline.net/#code=Jz8nN1hKUXRYIidzJ2poNWUiQDIjMSl0MzU-KS0xbDh0XzQkaDlNKWInbnNldyc9OE0qc0orWEorKA&input=fiN-I2V-I35-ZX4jfn5lLiN-fmVeI35-bi5-Li5ufl5-Lm5-Ln5-bi5-fi5uLn5-Km5-Ln4ubiMufn53Iy5-fncjLn5-c34qLi5zLi4qLnMqfi5-cy5-fn5z) ### Explanation The map is kept in the bottom of the stack and gradually filled. The current position of the explorer is stored in clipboard J. The map uses matrix coordinates, so (1,1) is upper left. In addition, column-major linear indexing is used. This means that the elements of the 8×8 matrix representing the map are accessed with a *single index* as follows: ``` 1 9 17 25 33 41 49 57 2 10 18 26 34 42 50 58 3 11 19 27 35 43 51 59 4 12 20 28 36 44 52 60 5 13 21 29 37 45 53 61 6 14 22 30 38 46 54 62 7 15 23 31 39 47 55 63 8 16 24 32 40 48 56 64 ``` So for example the element (3,2) of the matrix is the element with linear index 11. Movement towards North, South, East and West respectively corresponds to adding -1, 1, 8 or -8 to the linear index. The array [-1 1 8 -8] serves to encode two different things: * The possible displacements of the explorer. * The relative positions of features detected with the spyglass. These positions are relative to the current position of the explorer. The input string is arranged into chunks of `5` characters. Since the first chunk is missing the first character (that which indicates movement), an initial `s` is arbitrarily included to make all chunks the same size. To compensate for this, the explorer starts at position 7, not 8, so the initial displacement to the South (add 1 to the linear index) leaves them at position 8. The chunks of 5 characters are processed in a loop. The first character updates the position, and the remaining 4, if different than `#`, are written into the adequate entries of the matrix that represents the map. ``` '?' % push '?'. The map will initially be filled with this 7XJ % push 7: initial position of the explorer. Copy into clipboard J Qt % add 1. Duplicate X" % 8x8 matrix containing '?' 'n'jh % take input string. Prepend 'n' 5e % reshape into a 5-column matrix " % for each column (chunk) @ % push current chunk 2#1) % split chunk into its first char and an array with the other 4 t35> % duplicate. Logical index of chars different than # ) % apply that index to keep characters different than # -1l8t_4$h % array [-1 1 8 -8] 9M % push logical index again ) % apply that index to keep only relevant relative positions b % bubble up in stack: move first char of chunk to top 'nsew'= % logical index that tells if that char is 'n', 's', 'e' or 'w' 8M % push array [-1 1 8 -8] again * % multiply element-wise. Only one of the four results will be nonzero s % sum of the array. Gives displacement of the explorer J+ % push position of the explorer and add to compute new position XJ % update position in clipboard J + % add updated position of explorer to relative positions of features ( % write those fearttures into the indexed entries of the map % end for each. Implicitly display ``` [Answer] # C, ~~210~~ ~~208~~ 207 bytes This one uses printf and scanf to read input, and a linearized array instead of x,y; so I feel it is sufficiently different from [millibyte](https://codegolf.stackexchange.com/a/76644/41288)'s. Golfed: ``` main(p){char*i,*j,m[80];for(p=73,i=m+p;p--;m[p]=63);for(p=8;scanf("%5s",i)>0;p+=*j=='n'?8:*j=='s'?-8:*j=='e'?1:-1)for(j=i;j-i<4;j++)if(*j^35)m[p+"qajh"[j-i]-'i']=*j;for(p=72;m[p]=0,p-=8;)printf("%s\n",m+p);} ``` Somewhat-ungolfed: ``` main(p){ char*i,*j,m[80]; for(p=73,i=m+p;p--;m[p]=63); // fill with ? for(p=8;scanf("%5s",i)>0; p+=*j=='n'?8:*j=='s'?-8:*j=='e'?1:-1) // read 5-at-a-time for(j=i;j-i<4;j++) if(*j^35)m[p+"qajh"[j-i]-'i']=*j; // update map positions for(p=72;m[p]=0,p-=8;)printf("%s\n",m+p); // output line-by-line } ``` Representation: ``` // board: (vertically reversed when printed) 0 1 2 3 4 5 6 7 8 9 10 ... 16 18 19 ... ... 56 57 58 59 60 61 62 63 // offsets and offset order, or why "qajh": s2 -8 a w4 e3 -1 0+1 h i j n1 +8 q <- offset by +'i' ``` Also, you start at position 8 because this shaves a char or so off the print-loop. [Answer] # Ruby, ~~169~~ 147 bytes Full program. Takes in the input string from STDIN (you probably need to pipe it in from a file to prevent any trailing newlines from messing things up) and outputs the resultant map to STDOUT. Trimmed a ton by putting all the strings into one and then splitting them later. ``` m=??*64 d=0 x=56 gets.each_char{|c|d<4?(w=x+(d>2?-1:d>1?1:d<1?-8:d<2?8:0) m[w]=c if c>?$):x+=c>?v?-1:c<?f?1:c>?q?8:-8 d+=1;d%=5} puts m.scan /.{8}/ ``` Ungolfed: ``` m = ?? * 64 # 64 "?" symbols # y axis counts downwards; 0-7 is top row d = 0 # Keep track of which direction we're looking x = 56 # Position, bottom left corner (0,7) gets.each_char do |c| # For each character from first line of STDIN if d < 4 # Looking in a direction if d > 2 # d == 3; looking west w = x - 1 elsif d > 1 # d == 2; looking east w = x + 1 elsif d < 1 # d == 0; looking north w = x - 8 else # d == 1; looking south w = x + 8 end m[w] = c if c > ?$ # Only '#' gets rejected by this step else # Moving in a direction if c > ?v # c == 'w' x -= 1 elsif c < ?f # c == 'e' x += 1 elsif c > ?q # c == 's' x += 8 else # c == 'n' x -= 8 end end d = (d + 1) % 5 # Look in the next direction end puts m.scan /.{8}/ # Split map into rows of 8 ``` [Answer] # Fortran, 263 251 247 235 234 216 bytes 1D version (similar to the one by Don Muesli): ``` #define R read(*,'(a)',advance='no',eor=1)c #define F(x)R;if(c/='#')a(x+i)=c program t character::a(64)='?',c integer::k(4)=[8,-8,1,-1],i=57 do F(-8) F(8) F(1) F(-1) R i=i+k(index('snew',c)) enddo 1 print'(8a)',a end ``` 2D version: ``` #define R read(*,'(a)',advance='no',eor=1)c #define F(x,y)R;if(c/='#')a(x+m,y+l)=c #define G(x,y)j=index(x,c);if(j==2)j=-1;y=y+j program t character::a(8,8)='?',c l=8;m=1 do F(,-1) F(,1) F(1,) F(-1,) R G('sn',l) G('ew',m) enddo 1 print'(8a)',a end ``` To enable free form and pre-processing, the file needs the extension `.F90`, e.g. `explorer.F90`. The input is read from STDIN: ``` echo "~#~#e~#~~e~#~~e.#~~e^#~~n.~..n~^~.n~.~~n.~~.n.~~*n~.~.n#.~~w#.~~w#.~~s~*..s..*.s*~.~s.~~~s" | ./a.out ?~~~~~?? ?....~?? ?.**.~?? ?~..~~?? ?~~~~~?? ??~..~?? ~~~.^.?? ~~~~~~?? ``` [Answer] # C, ~~265~~ ~~226~~ 224 bytes ``` a[8][8];x;y;i;main(c){for(;c=getchar(),c+1;y+=(c=='n')-(c=='s'),x+=(c=='e')-(c=='w'))for(i=5;--i;c=getchar())i&&c-35&&(a[x+(i==2)-(i==1)][y-(i==3)+(i==4)]=c);for(y=8;y--;putchar(10))for(x=0;x<8;)putchar((i=a[x++][y])?i:63);} ``` The map is 8x8, I didn't notice that before. And here is the 265 bytes solution that works for maps with variable dimensions: ``` a[99][99];c;x;X;y;i;k;p;main(Y){for(;c=getchar(),c+1;y+=(c=='n')-(c=='s'),x+=(c=='e')-(c=='w'))for(i=5;--i;c=getchar())i&&c-35&&(a[k=x+(i==2)-(i==1),X=X<k?k:X,k][p=y-(i==3)+(i==4),Y=Y<p?p:Y,p]=c);for(y=Y+1;y--;putchar(10))for(x=0;x<=X;)putchar((i=a[x++][y])?i:63);} ``` [Answer] # Lua, 354 bytes ([try it online](http://www.lua.org/cgi-bin/demo)) Golfed: ``` n=(...)r={}y=8x=1q="?"for i=1,8 do r[i]={q,q,q,q,q,q,q,q}end for u in n:gsub("#",q):gmatch(".....")do a,b,c,d,e=u:match("(.)(.)(.)(.)(.)")if a~=q then r[y-1][x]=a end if b~=q then r[y+1][x]=b end if c~=q then r[y][x+1]=c end if d~=q then r[y][x-1]=d end y=y+(("n s"):find(e)or 2)-2x=x+(("w e"):find(e)or 2)-2 end for i=1,8 do print(table.concat(r[i]))end ``` Slightly ungolfed: ``` n = "~#~#e~#~~e~#~~e.#~~e^#~~n.~..n~^~.n~.~~n.~~.n.~~*n~.~.n#.~~w#.~~w#.~~s~*..s..*.s*~.~s.~~~s" r={} y=8 x=1 q="?" for i=1,8 do r[i]={q,q,q,q,q,q,q,q} end for u in n:gsub("#",q):gmatch(".....") do a,b,c,d,e=u:match("(.)(.)(.)(.)(.)") if a~=q then r[y-1][x]=a end if b~=q then r[y+1][x]=b end if c~=q then r[y][x+1]=c end if d~=q then r[y][x-1]=d end y=y+(("n s"):find(e)or 2)-2 x=x+(("w e"):find(e)or 2)-2 end for i=1,8 do print(table.concat(r[i])) end ``` [Answer] # Kotlin, 242 bytes ``` {val m=Array(8){Array(8){'?'}} var d=7 var i=0 for(c in it)(mapOf('n' to{d--},'s' to{d++},'w' to{d-=8},'e' to{d+=8},'#' to{i++})[c]?:{m[d%8+listOf(-1,1,0,0)[i%4]][d/8+listOf(0,0,1,-1)[i%4]]=c i++})() m.forEach{for(c in it)print(c);println()}} ``` The newlines can be replaced with semicolons if wished. [Try Here](http://try.kotlinlang.org/#/UserProjects/irseu5kgc1lbaa66a8cq2rts48/rdhqqabn44vbun4l6r1c61bfpd) ]
[Question] [ Let's say I have the following (2D) matrix: ``` [[1, 2, 3, 4 ], [5, 6, 7, 8 ], [9, 10, 11, 12], [13, 14, 15, 16]] ``` Rotate the matrix *counterclockwise* `R` times (not in 90 degree increments, just by 1 number each time), ``` 1 2 3 4 2 3 4 8 3 4 8 12 5 6 7 8 --> 1 7 11 12 --> 2 11 10 16 9 10 11 12 5 6 10 16 1 7 6 15 13 14 15 16 9 13 14 15 5 9 13 14 ``` Completed example: Input: ``` 2 [[1, 2, 3, 4 ], [5, 6, 7, 8 ], [9, 10, 11, 12], [13, 14, 15, 16]] ``` Output: ``` [[3, 4, 8, 12], [2, 11, 10, 16], [1, 7, 6, 15], [5, 9, 13, 14]] ``` (weird spaces are to align the numbers in nice columns) The outer "ring" of the matrix rotates 2 counterclockwise, and the inner right rotates 2 also. In this matrix, there are only two rings. An example with 1 "ring": ``` 2 [[1, 2], [3, 4], [5, 6]] ``` Should output: ``` [[4, 6], [2, 5], [1, 3]] ``` Your challenge is to take in a matrix and an integer `R`, and output the translated version after `R` rotations. Rotation of a 4x5 matrix is represented by the following figure: [![enter image description here](https://i.stack.imgur.com/MeFZw.png)](https://i.stack.imgur.com/MeFZw.png) **Constraints:** * `2 ≤ M, N ≤ 100`, where M and N are the dimensions of the matrix. It is guaranteed that the minimum of M and N will be even. * `1 ≤ R ≤ 80`, where r is number of rotations. * The matrix will only ever contain positive integers. * Values are not always distinct. * The input should always be as a 2D array (if you can't take runtime input as a 2D array, then you just have to find another way to get input). Another test case, with non-distinct values: ``` 1 [[1, 1], [2, 2], [3, 3]] ``` Outputs: ``` [[1, 2], [1, 3], [2, 3]] ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~39~~ ~~38~~ ~~36~~ 35 bytes ``` ḢṚ;Ḣ€;Ṫ;Ṫ€Ṛ$,-ṙ\;"ß¹¡ FJ©ṁ¹Çy®ịFṁµ¡ ``` [Try it online!](https://tio.run/nexus/jelly#@/9wx6KHO2dZA6lHTWusH@5cBcJAJlBQRUf34c6ZMdZKh@cf2nloIZeb16GVD3c2Htp5uL3y0LqHu7vdQLythxb@//8/OtpQR8FIR8FYR8EkVkch2lRHwUxHwVxHwQLEs9RRMDQAYqAaQyOQgCFQnaEJEAPVGZrFxv43AgA "Jelly – TIO Nexus") [Answer] # Octave, 210 bytes ``` function M=F(M,R);f=@(z)[-z/2:-1 !eye(!!mod(z,2)) 1:z/2];t=angle(f([x y]=size(M))'+f(y)*i);B=!!M;B(2:x-1,2:y-1)=0;d=bwdist(B,'ch');[~,I]=sortrows([d(:) t(:)]);for k=0:max(d(:));M(h)=shift(M(h=I(d(I)==k)),R);end ``` [Try it on Octave Online!](http://octave-online.net/#cmd=function%20M%3DF(M%2CR)%3Bf%3D%40(z)%5B-z%2F2%3A-1%20!eye(!!mod(z%2C2))%201%3Az%2F2%5D%3Bt%3Dangle(f(%5Bx%20y%5D%3Dsize(M))%27%2Bf(y)*i)%3BB%3D!!M%3BB(2%3Ax-1%2C2%3Ay-1)%3D0%3Bd%3Dbwdist(B%2C%27ch%27)%3B%5B%7E%2CI%5D%3Dsortrows(%5Bd(%3A)%20t(%3A)%5D)%3Bfor%20k%3D0%3Amax(d(%3A))%3BM(h)%3Dshift(M(h%3DI(d(I)%3D%3Dk))%2CR)%3Bend%3Bend%3BR%3D2%3BM%3Drandi(10%2C4%2C7)%2CF(M%2CR)) Ungolfed version: ``` function M=F(M,R) [x y]=size(M); f=@(z)[-z/2:-1 !eye(!!mod(z,2)) 1:z/2]; t=angle(f(x)'+f(y)*i); B=!!M; B(2:x-1,2:y-1)=0; d=bwdist(B,'chessboard'); [~,I]=sortrows([d(:) t(:)]); for k=0:max(d(:)) M(h)=shift(M(h=I(d(I)==k)),R); end end R=2; M=randi(10,4,7) F(M,R) ``` Explanation: ``` f=@(z)[-z/2:-1 !eye(!!mod(z,2)) 1:z/2]; ``` A function that gets a number and generates a range that is ordered and centered for input 4 (even) generates `-2 -1 1 2` for input 5(odd) generates `-2.5 -1.5 0 1 2` only it should be ordered and centered ``` f(x)'+f(y)*i ``` a complex matrix generated from ranges ``` (-2,-2.5) (-2,-1.5) (-2,0) (-2,1) (-2,2) (-1,-2.5) (-1,-1.5) (-1,0) (-1,1) (-1,2) (1,-2.5) (1,-1.5) (1,0) (1,1) (1,2) (2,-2.5) (2,-1.5) (2,0) (2,1) (2,2) t=angle(f(x)'+f(y)*i); ``` Convert rectangular to polar coordinates and return angles so for each ring angles are sorted counteclockwise ``` -2.25 -2.50 3.14 2.68 2.36 -1.95 -2.16 3.14 2.36 2.03 -1.19 -0.98 0.00 0.79 1.11 -0.90 -0.64 0.00 0.46 0.79 B=!!M; B(2:x-1,2:y-1)=0; ``` The following matrix generated ``` 1 1 1 1 1 1 0 0 0 1 1 0 0 0 1 1 1 1 1 1 d=bwdist(B,'chessboard'); ``` Computes the distance transform of B using chessboard distance to generate ring indices ``` 0 0 0 0 0 0 1 1 1 0 0 1 1 1 0 0 0 0 0 0 ``` for a 6 \* 7 matrix we will have the following matrix ``` 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 1 2 2 2 1 0 0 1 2 2 2 1 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 [~,I]=sortrows([d(:) t(:)]); ``` lexicographic sort first based on ring index and then by order of angle(indices of sorted elements returned) ``` for k=0:max(d(:)) M(h)=shift(M(h=I(d(I)==k)),R); end ``` and finally circular shift each ring. [Answer] # Python 3, ~~292~~ 288 bytes ``` _=eval a=input().split() b,a=int(a[0]),_("".join(a[1:]))[::-1] c=len(a) d=len(a[0]) e=range f="int((i>=j and i+j<c-1)|2*(i>=c/2and i+d>j+c)|3*(i<c/2and i+j<d))" l=[-1,1,0,0],[0,0,1,-1] g=lambda x:[[x[i+l[0][_(f)]][j+l[1][_(f)]]for j in e(d)]for i in e(c)] print(_("g("*b+"a"+")"*b)[::-1]) ``` Takes input with newlines removed, but leaving a space after the number of increments to rotate it by. ## Explanation: Instead of modeling the matrix as a series of concentric rings per the OP's suggestion, one can instead divide it into four regions where the elements travel either up, down, right, or left during a single rotation. This is the purpose of the long eval-ed string `f`: to determine which region each `i,j` combination falls into. Then, the result of that is looked up twice in `l`, giving the element that must rotate into position `i,j` in the next step. The function `g` that does all of this and forms the new matrix after a single step is then called repeatedly by evaling a generated string containing the representation of a nested function call. When I made this originally, I accidentally caused the matrix to rotate clockwise instead of counterclockwise. Rather than doing a proper fix, I added two strategically placed copies of `[::-1]` to reverse the matrix before and after the rotation. These could probably be golfed off to ~~~280~~ 276 bytes, but I'm too lazy to do that. Also, this is a quick untested port from a slightly longer Python 2 program, so forgive me if it doesn't work quite right. Here's the Python 2 code, anyways: ``` _=eval a=raw_input().split() b,a=int(a[0]),_("".join(a[1:]))[::-1] c=len(a) d=len(a[0]) e=xrange f="int((i>=j and i+j<c-1)|2*(i>=c/2and i+d>j+c)|3*(i<c/2and i+j<d))" l=[-1,1,0,0],[0,0,1,-1] g=lambda x:[[x[i+l[0][_(f)]][j+l[1][_(f)]]for j in e(d)]for i in e(c)] print _("g("*b+"a"+")"*b)[::-1] ``` EDIT: Golfed off 4 bytes by replacing `or` with `|` twice. `and` can't be helped, unfortunately. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~78 76 60~~ 64 bytes -16 bytes from using @ngn's [version](https://chat.stackexchange.com/transcript/message/56770838#56770838) +4 because of changes in the language (prototypes) ``` {(,()){(,y),+|x}/|,/{1_{1_y,*x}':x,,*x}'0N 4#-1_*'(*:)(|+1_)\x}/ ``` [Try it online!](https://ngn.codeberg.page/k#eJw9jU0KgzAYRPc5xUAXJppiJvGv+Ra9QS/QSnaewIWi3t1USmGYgceDmeKmrTYm92pstS9Hvdt6Y8pZbbkcRVzste6F5nZnKgtdRqP3isl8sq7U9PaiCY+ARlp06DHIA3QgQS8MYAO2YGfGvy0/+0L8Ioq/cMhIzbHPf3540qk5G0Hm8QRiiSfO) * `{...}/` use the "do" variant of `/` to run the function `x` times, seeded with `y` and returning the last result. (each iteration rotates each ring of the input matrix one position) * `(*:)(|+1_)\x` peel off the first row, rotating the remainder until there's nothing left, accumulating the results into a list * `-1_*'` take the first item of each (i.e. the "top-most" slice of the outer ring). drop the last item, as it's empty * `0N 4#` reshape the flat list into groups of four items; each group represents one "ring" of the input matrix * `{...}'` for each ring... + `x,,*x` append a copy of the first ring slice + `1_{1_y,*x}':` for each slice of the ring, append the first item of the current slice to the previous slice, dropping the first value of the result. (this has the effect of rotating the values in each ring one position) * `(,()){...}/|,/` set up a `/`, seeded with an empty list and run over the flattened and reversed ring slices... + `(,y),+|x` where we prepend each ring slice to the rotated and transposed result so far [Answer] # Perl, ~~330~~ 328 bytes ``` sub f{($r,$m)=@_;$h=@m=@$m;for$s(0..(($w=$#{$m[0]})<--$h?$w:$h)/2-.5){@_=(@{$m[$s]}[@x=$s..($x=$w-$s)],(map$m[$_][$x],@y=1+$s..($y=$h-$s)-1),reverse(@{$m[$y]}[@x]),(map$m[$h-$_][$s],@y));push@_,shift for 1..$r;@{$m[$s]}[@x]=map shift,@x;$m[$_][$x]=shift for@y;@{$m[$y]}[@x]=reverse map shift,@x;$m[$h-$_][$s]=shift for@y}@$m=@m} ``` [Try it on Ideone](http://ideone.com/bDfkmZ). Ungolfed: ``` sub f { my ($r, $m) = @_; my @m = @$m; my $h = $#m; my $w = @{$m[0]} - 1; my $c = (($w < $h ? $w : $h) + 1) / 2 - 1; for my $s (0 .. $c) { my $x = $w - $s; my $y = $h - $s; my @x = $s .. $x; my @y = $s + 1 .. $y - 1; # One circle. @_ = (@{$m[$s]}[@x], (map { $m[$_][$x] } @y), reverse(@{$m[$y]}[@x]), (map { $m[$h - $_][$s] } @y)); # Circular shift. push(@_, shift(@_)) for 1 .. $r; @{$m[$s]}[@x] = map { shift(@_) } @x; $m[$_][$x] = shift(@_) for @y; @{$m[$y]}[@x] = reverse(map { shift(@_) } @x); $m[$h - $_][$s] = shift(@_) for @y; } @$m = @m; } ``` ]
[Question] [ [We already generated Minesweeper fields](https://codegolf.stackexchange.com/q/10635/3396), but someone really has to sweep those generated mines before PCG blows up! Your task is to write a Minesweeper Solver that is compatible with a slightly modified version of [the accepted solution of “Working Minesweeper”](https://codegolf.stackexchange.com/questions/10635/working-minesweeper/10676#10676) (actions are separated by spaces to allow for larger fields). **Input:** A Minesweeper field, fields separated by spaces. The first line denotes the total number of mines. * `x`: Untouched * `!`: Flag * Digit: Number of mines around that field Example: ``` 10 0 0 1 x x x x x 0 0 2 x x x x x 0 0 2 ! x x x x 0 0 1 2 x x x x 0 0 0 1 x x x x 1 1 0 2 x x x x x 1 0 2 x x x x 1 1 0 1 x x x x ``` **Output:** Your next step in the format `action row column` (starting at zero) Valid Actions: * `0`: Open it * `1`: Place a flag Example: ``` 0 1 2 ``` **Rules:** * You write a complete program that takes a single field as input (either STDIN or command line arguments) and outputs a single action (STDOUT). Therefore, you cannot save states, except for `!`. * Your choice must follow the best odds for survival. (i.e. if there is a 100% safe move, take it) * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); the shortest solution (in UTF-8 bytes) wins **Tests:** These tests serve the purpose of testing for common clear situations; your program must work for every test field. In: ``` 4 x x x x 1 2 x x 0 1 2 x 0 0 1 x ``` Out (any of these): ``` 1 1 2 0 0 2 0 1 3 ``` In: ``` 2 x x x 1 ! x 1 1 x ``` Out (any of these): ``` 0 0 0 0 0 1 0 1 2 0 2 2 1 0 2 ``` In: ``` 10 x x x x x x x x 1 3 3 x x x x x 0 1 ! 3 3 4 x x 0 2 3 ! 2 3 x x 0 1 ! 2 2 ! x x ``` Out (any of these): ``` 1 1 5 1 0 2 ``` In: ``` 2 x x x 2 3 1 ! 1 0 ``` Out (any of these): ``` 0 0 1 1 0 0 1 0 2 ``` [Answer] ## Mathematica Still not golfed. Needs some more work on I/O formats. ``` t = {{0, 0, 1, x, x, x, x, x}, {0, 0, 2, x, x, x, x, x}, {0, 0, 2, F, x, x, x, x}, {0, 0, 1, 2, x, x, x, x}, {0, 0, 0, 1, x, x, x, x}, {1, 1, 0, 2, x, x, x, x}, {x, 1, 0, 2, x, x, x, x}, {1, 1, 0, 1, x, x, x, x}}; (*Sqrt[2] is 1.5*) c = Sequence; p = Position; nums = p[t, _?NumberQ]; fx = Nearest[p[t, x]]; flagMinus[flag_] := If[Norm[# - flag] < 1.5, t[[c @@ #]]--] & /@ nums flagMinus /@ p[t, F]; g@x_List := Tr[q[#] & /@ x] eqs = MapIndexed[t[[c @@ (nums[[#2]][[1]])]] == g[#1] &, (fx[#, {8, 1.5}] & /@nums)]; vars = Union@Cases[eqs, _q, 4]; s = Solve[Join[eqs, Thread[0 <= vars < 2]], vars, Integers]; res = (Transpose@s)[[All, All, 2]]; i = 1; plays = Select[{i++, #[[1]], Equal @@ #} & /@ res, #[[3]] &]; Flatten /@ ({#[[2]] /. 1 -> F, List @@ vars[[#[[1]]]] - 1} & /@ plays) (* {{0, 0, 3}, {F, 1, 3}, {F, 2, 4}, {0, 3, 4}, {0, 4, 4}, {F, 5, 4}, {F, 6, 0}, {F, 6, 4}, {0, 7, 4}} *) ``` **Edit: Bonus Track** I made up an interactive playground that calculates bomb probabilities by calculating all possible solutions for a given configuration: ![Mathematica graphics](https://i.stack.imgur.com/u3LyC.png) Instructions for testing it without Mathematica installed: 1. Download <http://pastebin.com/asLC47BW> and save it as \*.CDF 2. Dowload the free CDF environment from Wolfram Research at <https://www.wolfram.com/cdf-player/> (not a small file) The slider changes the board dimensions. This is just a sketchy program, not fully tested, please report any bugs. I haven't implemented a "total number of available bombs on board" feature. It's assumed infinite. ]
[Question] [ Every programmer knows that brackets `[]{}()<>` are really fun. To exacerbate this fun, groups of interwoven brackets can be transformed into cute and fuzzy diagrams. Let's say that you have a string that contains balanced brackets, like `[{][<(]})>(())`. Step one is to rotate the string 45 degrees clockwise. (In Mathematica, this can be almost done with `Rotate[ur_string,-pi/4]`). Here is the result of the first step: ``` [ { ] [ < ( ] } ) > ( ( ) ) ``` Next add a diagonal space between each character. ``` [ { ] [ < ( ] } ) > ( ( ) ) ``` Next, start with the left-most bracket and draw a square between it and its partner in crime. ``` +---+ | | | { | | | +---+ [ < ( ] } ) > ( ( ) ) ``` Repeat this process with each pair of brackets, overwriting previous characters with `+`s if need be. ``` +---+ | | | +-+---------+ | | | | +-+-+ | | | | [ | | | | < | | | | ( | | | | ] | | | +-----------+ ) > ( ( ) ) ``` Continue until you have made everything nice and square. ``` +---+ | | | +-+---------+ | | | | +-+-+ | | | | +-----+ | | | | | | | +---+-+---+ | | | | | | | | | +-+-+-+ | | | | | | | | | | +-+-+-+ | | | | | | | | | +-----+-+---+ | | | | | | | +-----+ | | | +---------+ +-----+ | | | +-+ | | | | | | +-+ | | | +-----+ ``` **Input** Input will be a single line of balanced brackets and no other characters, with each bracket being one of `[]{}()<>`. Each *type* of bracket is balanced individually, though different types may overlap (this is what makes the squares look interesting). A trailing newline is optional. **Output** Output will be the interlocking square pattern generated from the bracket string. Trailing spaces and trailing newline are optional, but there mustn't be leading whitespace. **Goal** This is code-golf, fewest bytes wins. [Answer] # JavaScript (ES6), ~~269 274 278 296~~ 261 bytes **Edit** Saved 4 bytes thx @Neil ``` x=>[...x].map(c=>{g.push([],[]),z='<{[(>}])'.indexOf(c);if(z>3)for(j=a=o[z-4].pop();j<=b;j++)S(j,a,'|'),S(j,b,'|'),S(a),S(b);else o[z].push(b);b+=2},S=(y,x=j,c='-')=>g[y][x]=g[y][x]?'+':c,o=[[],[],[],[]],g=[],b=0)&&g.map(r=>[...r].map(c=>c||' ').join``).join` ` ``` **TEST** ``` F=x=>[...x].map(c=>{g.push([],[]),z='<{[(>}])'.indexOf(c);if(z>3)for(j=a=o[z-4].pop();j<=b;j++)S(j,a,'|'),S(j,b,'|'),S(a),S(b);else o[z].push(b);b+=2},S=(y,x=j,c='-')=>g[y][x]=g[y][x]?'+':c,o=[[],[],[],[]],g=[],b=0)&&g.map(r=>[...r].map(c=>c||' ').join``).join` ` // Less golfed U=x=>( S = (y,x=j,c='-')=>g[y][x]=g[y][x]?'+':c, o = [[],[],[],[]], g = [], b = 0, [...x].map(c=> { g.push([],[]), z='<{[(>}])'.indexOf(c); if(z>3) for(j = a =o[z-4].pop(); j <= b; j++) S(j,a,'|'), S(j,b,'|'), S(a), S(b) else o[z].push(b); b += 2 }), g.map(r=> [...r].map(c=>c||' ').join`` ).join`\n` ) function test() { O.textContent=F(I.value) } test() ``` ``` Input:<input id=I value='[{][<(]})>(())' oninput='test()'> <pre id=O></pre> ``` [Answer] ## Python 3, 226 ``` n,p,*t=0,[],0,[],[],[],[] for b in input(): r=t[ord(b)//30];r+=[n];n+=2 if b in'])}>':p+=[r[-2:]];del r[-2:] R=range(n-1) for y in R:print(''.join(' -|+'[sum((y in q)+2*(x in q)for q in p if x>=q[0]<=y<=q[1]>=x)]for x in R)) ``` [Example](https://ideone.com/r7Z6GS). Explanation: ``` n,p,*t=0,[],0,[],[],[],[] # n -> counter for input # p -> bracket pairs # t -> four stacks [unused, (), <>, [], {}] for b in input(): # for each bracket b of input r=t[ord(b)//30]; # r -> alias for b's stack r+=[n]; # push bracket's index n+=2 # increase counter by 2 (to add diagonal gaps) if b in'])}>': # if b is a closing bracket p+=[r[-2:]]; # pair the top 2 brackets on stack del r[-2:] # pop them from stack R=range(n-1) # n-1 is now the width/height of output for y in R: print(''.join(' -|+'[ sum((y in{a,b})+2*(x in{a,b})for a,b in p if x>=a<=y<=b>=x) ]for x in R)) # three nested loops: # 1) for each line y # 2) for each character x # 3) for each bracket pair (a, b) if x>=a<=y<=b>=x # if x or y isn't in the inclusive range [a, b], we can skip it (y in{a,b}) # if y is a or b, then the character lies on a horizontal edge of that square # so we add 1 to the sum 2*(x in{a,b}) # if x is a or b, then the character lies on a vertical edge of that square # so we add 2 to the sum ' -|+'[sum()] # if it lies on a single edge, the sum will be 1 or 2 -> '-' or '|' # if it lies on two edges, the sum will be 1 + 2 == 3 -> '+' ``` [Answer] # [pb](http://esolangs.org/wiki/pb) - 449 bytes ``` ^w[B!0]{w[B=40]{b[39]}t[B]w[B!0]{w[B=T]{^b[1]}w[B=T+1]{^b[1]}w[B=T+2]{^b[2]}^[Y]^>}<[X]^w[B!1]{>}t[1]b[0]w[T!0]{>w[B=1]{t[T+1]b[0]}w[B=2]{t[T-1]b[0]}}b[3]vw[B!0]{>}^w[B!3]{b[0]<}b[0]vb[1]>[X]vv[X]b[43]t[X]^[Y]^<[X]w[B=0]{>}>[X]vv[X]b[43]w[Y!T-1]{vw[B=45]{b[43]}w[B=0]{b[124]}}vb[43]t[1]>w[B!43]{t[T+1]w[B=124]{b[43]}w[B=0]{b[45]}>}w[T!0]{^t[T-1]w[B=45]{b[43]}w[B=0]{b[124]}}w[B!43]{w[B=124]{b[43]}w[B=0]{b[45]}<}<[X]^[Y]^w[B=0]{>}b[0]>w[B=1]{b[0]>}} ``` I was all excited when I read this because I have a language that prints directly to a position! This challenge about positioning outputs should be easy and short! Then I remembered pb is longwinded anyway. With comments: ``` ^w[B!0]{ w[B=40]{b[39]} # change ( to ' to make closing bracket calculation work t[B] # this used to just find the first matching bracket # but then op clarified we had to use depth # whoops # <fix> w[B!0]{ w[B=T]{^b[1]} # put a 1 above opening brackets of this type w[B=T+1]{^b[1]} # same as before, but ugly hack to make ( work w[B=T+2]{^b[2]} # put a 2 above closing brackets of this type ^[Y]^ # return to input line >} <[X]^w[B!1]{>}t[1]b[0] # set T to 1 above the opening bracket w[T!0]{> # until T (depth) == 0: w[B=1]{t[T+1]b[0]} # add 1 to T if 1 w[B=2]{t[T-1]b[0]} # subtract 1 from T if 2 } b[3] # when T is 0, we've found the right one vw[B!0]{>} # go to the end of the input ^w[B!3]{b[0]<}b[0]v # clean up the row above # </fix> b[1] # replace it with 1 so it's not confusing later >[X]vv[X]b[43]t[X] # put a + at its output position and save coord ^[Y]^<[X]w[B=0]{>}>[X]vv[X]b[43] # put a + at opening bracket's output position w[Y!T-1]{v w[B=45]{b[43]} # replace - with + w[B=0]{b[124]} # otherwise put | } vb[43] # put a + at lower left corner t[1] # count side length + 1 >w[B!43]{ t[T+1] w[B=124]{b[43]} # replace | with + w[B=0]{b[45]} # otherwise put - >} w[T!0]{^ # create right side t[T-1] w[B=45]{b[43]} w[B=0]{b[124]} } w[B!43]{ # create top side w[B=124]{b[43]} # this replacement saves us from putting the last + explicitly # which is why we counted the side length + 1, to get that # extra char to replace w[B=0]{b[45]} <} <[X]^[Y]^w[B=0]{>}b[0]>w[B=1]{b[0]>}# Go to next character (skipping 1s) } ``` [Answer] # CJam, 117 bytes ``` q_,2*:M2#0a*\:iee{1=K/}${~)4%1>{a+aL+:L;}*}/L{2f*__~,>m*5Zb\m*{~W2$#%Mb\}%\2m*Mfb3am*}%e_2/{~2$2$=+3e<t}/" |-+"f=M/N* ``` [Try it here.](http://cjam.aditsu.net/) [Answer] # Ruby, 268 ``` ->z{a=(2..2*t=z.size).map{' '*t} g=->y,x{a[y][x]=(a[y][x-1]+a[y][x+1]).sum>64??+:?|} 2.times{|h|s=z*1 t.times{|i|c=s[i] c>?$&&(j=s.index(c.tr('[]{}()<>','][}{)(><')) (m=i*2).upto(n=j*2){|k|k%n>m ?g[k,m]+g[k,n]:h<1&&a[k][m..n]=?++?-*(n-m-1)+?+} s[i]=s[j]=?!)}} puts a} ``` **ungolfed in test program** ``` f=->z{ a=(2..2*t=z.size).map{' '*t} #make an array of strings of spaces g=->y,x{a[y][x]=(a[y][x-1]+a[y][x+1]).sum>64??+:?|} #function for printing verticals: | if adjacent cells spaces (32+32) otherwise + 2.times{|h| #run through the array twice s=z*1 #make a duplicate of the input (*1 is a dummy operation to avoid passing just pointer) t.times{|i| #for each index in input c=s[i] #take the character c>?$&&( #if ascii value higher than for $ j=s.index(c.tr('[]{}()<>','][}{)(><')) #it must be a braket so find its match (m=i*2).upto(n=j*2){|k| #loop through the relevant rows of array k%n>m ?g[k,m]+g[k,n]: #if k!=n and k!m draw verticals h<1&&a[k][m..n]=?++?-*(n-m-1)+?+ #otherwise draw horizontals (but only on 1st pass) } s[i]=s[j]=?!) #we are done with this set of brackets, replace them with ! so they will be ignored in next call of index } } puts a } z=gets.chop f[z] ``` ]
[Question] [ It's 22022 and the Unicode consortium is having a problem. After the writing system of the ⮧⣝Ⅲⴄ⟢⧩⋓⣠ civilization was assigned the last Unicode block, the consortium members have been scrambling to find a new encoding to replace UTF-8. Finally UTF-∞, a proposal by Bob Rike, was adopted. UTF-∞ is backwards compatible with UTF-8. If you know how UTF-8 works, then TLDR; UTF-∞ is the natural extension of UTF-8. UTF-∞, like UTF-8, encodes an integer to some sequence of bytes like so (each byte shown as 8 bits) `xxxxxxxx 10xxxxxx 10xxxxxx 10xxxxxx ...` If the sequence of bytes has length \$n\$, then the first \$n\$ `x`:s (from left to right), are set to `1` and the \$n+1\$:th `x` is set to 0. The rest of the `x`:s encode a big-endian binary representation of the integer. There is an exception. If the length of the sequence is `1` (meaning the input number is less than 128), then the encoding looks as follows: `0xxxxxxx` Where the `x`:s contain the binary representation of the integer. Also, in order for an encoding to be valid, the minimum amount of bytes has to be used (no overlong encodings). Your task is to take in a non-negative integer and output the UTF-∞ representation of the integer. You can output a list/string of bytes or a list of numbers between 0 and 255 inclusive. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins. # Example Let's take the input 8364 (the euro symbol "€") as an example. We somehow know that we need 3 bytes, so \$n=3\$. Let's take `xxxxxxxx 10xxxxxx 10xxxxxx 10xxxxxx ...` And take the first 3 bytes: `xxxxxxxx 10xxxxxx 10xxxxxx` Next, the first \$n\$ "x"s are set to 1: `111xxxxx 10xxxxxx 10xxxxxx` And then the leftmost "x" is set to 0. (index \$n+1\$ before any "x"s were replaced) `1110xxxx 10xxxxxx 10xxxxxx` Finally, we fill the binary expansion of 8364 (which is 10 0000 1010 1100) into the remaining "x"s `11100010 10000010 10101100` And convert to bytes: `[226, 130, 172]` Now you might wonder how we know what value of \$n\$ to use? One option is trial and error. Start from \$n=1\$ and increment \$n\$ until we find an \$n\$ where the binary expansion of our input fits. If we had the input 70368744177663 (\$n=9\$) we would start like so: `xxxxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx` and then `11111111 1010xxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx` and then fill the binary expansion of 70368744177663 # Test cases ``` 0 -> [0] 69 -> [69] 127 -> [127] 128 -> [194, 128] 1546 -> [216, 138] 2047 -> [223, 191] 2048 -> [224, 160, 128] 34195 -> [232, 150, 147] 65535 -> [239, 191, 191] 65536 -> [240, 144, 128, 128] 798319 -> [243, 130, 185, 175] 2097151 -> [247, 191, 191, 191] 2097152 -> [248, 136, 128, 128, 128] 30606638 -> [249, 180, 176, 148, 174] 67108863 -> [251, 191, 191, 191, 191] 67108864 -> [252, 132, 128, 128, 128, 128] 20566519621 -> [254, 147, 137, 183, 130, 189, 133] 68719476735 -> [254, 191, 191, 191, 191, 191, 191] 68719476736 -> [255, 129, 128, 128, 128, 128, 128, 128] 1731079735717 -> [255, 153, 140, 140, 153, 136, 166, 165] 2199023255551 -> [255, 159, 191, 191, 191, 191, 191, 191] 2199023255552 -> [255, 160, 160, 128, 128, 128, 128, 128, 128] 64040217759022 -> [255, 174, 163, 186, 134, 155, 164, 180, 174] 70368744177663 -> [255, 175, 191, 191, 191, 191, 191, 191, 191] 70368744177664 -> [255, 176, 144, 128, 128, 128, 128, 128, 128, 128] 34369578119952639221217025744100729453590194597032 -> [255, 191, 191, 191, 191, 165, 184, 145, 129, 139, 182, 177, 159, 176, 167, 155, 139, 159, 138, 163, 170, 143, 151, 141, 156, 154, 134, 183, 176, 175, 170, 178, 168] ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 47 bytes ``` Nθ≔÷⁺³L↨貦⁵ηI⎇‹θ¹²⁸θE↨⁺θ⁻X⁶⁴η×⁴X³²η⁶⁴⁺ι×⁶⁴⁺²¬κ ``` [Try it online!](https://tio.run/##NU3LbsIwELz3K3JcS6nkZ4zFqYULEkU58AMutYhFcMB2qPr17jq0K@3u7Ghm9jTYeJrsWMou3OZ8mK@fLsKdrF/eUvLnALuQt/7hvxz045xAtM3ehXMe4N0mB/e24YSQtlHYA7r66EOGjU0Zji4GG39g71KqQsZXKELwYW9P95JYCR8Q9NM3vu5kDWqbo7@6BHg8acErvbzqJI7F6v9l1bQwqDpMGS7kr9alCCk6o/SKMWMU74ThnHGmKVdaSkap5kYqoQxluI2mgpfXx/gL "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input the integer. ``` ≔÷⁺³L↨貦⁵η ``` Calculate the number of bytes the extended representation would take. ``` I⎇‹θ¹²⁸θ ``` If the integer is less than 128 then just output the integer again, otherwise... ``` E↨⁺θ⁻X⁶⁴η×⁴X³²η⁶⁴⁺ι×⁶⁴⁺²¬κ ``` ... calculate `n-2` high-level bits, add that to the integer, convert to base `64`, then add `192` to the first byte and `128` to the remaining bytes. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~104~~ 103 bytes *Saved 1 byte thanks to @emanresuA* Expects a BigInt. Returns a comma-separated string of bytes. ``` n=>n>127?(g=k=>k>63?g(k>>6n)+[,k&63n|128n]:k|192n)(2n**(x=(h=n=>n?-~h(n/2n):3n)(n)/5n)-4n<<x*5n|n):n+'' ``` [Try it online!](https://tio.run/##nZbLbttADEX3@QqtGsnxY57kTBrJq36F4YXhxk6iYFwkRZGF0V93yZlEsoPW9UgLAbLAc8lLDq2n1a/V6/rl8cfPSdh9vz9s6kOom9BIhfNyW7d10zag59uybRoI1c1i3H4BHfZSubC8bffSq1CVKoxG5VtdPtQcPJ/8fijDjF7canoZqpkN1cSEu7u3kQ17@jncXF8fvi6uikKEcZF7zWbFQiwpGHx@NAeD52gqMTucoykuhbth4d6MOTgyrIFcCDOUBGLoyFDC4CCG0sTw8p3hhjG4FhBdQdpIbzNJEaQVMSyDTHQXrNXDQD5W1ZXGIBgCMjGZ1KuuPvROy8ypSzQ2WzPSWbqhTbZ7lFZm4RIN@yKPmsg0NYDG9WnoK@3bKUAA6KzZSEjuguNykblRAU3sB0rhHK2QXKSVn2ruW5yQJh/JQxcn77jwrnolLICVHtTlLUpcE@eY4Xxzfe/ZFq1j0g5pEyBgxpj3cC//eTuFQyach1P5vzly6o1ELQV6yh7lpeunV7DsSDpg4uMxDiDEWzoc0ntBe8HSJfMV/P9dOlZQ2Qpx672vvrNWgRFGKIloSe1CnV4G44Zlg1zc@fyY9E13xOLBQqGp7caQEFx6vI5k7Hm/OtNOZEy2DHxaqmed00aDt@gkNcoq0F4pSUYKZTkBIVB5Q38TXtCwW0@ZqXCk1WU@nU4/nItHMSYRC8ZoHwsCCS6vppvdy7fVmr5eirop1rvwunu@nz7vtuWGPmOq6vAH "JavaScript (Node.js) – Try It Online") ### 92 bytes An alternate version taking a standard JS number. It only works up to 0x3FFFFFF, which somewhat defeats the purpose of using UTF-∞. :-/ ``` n=>n>>7?(g=k=>k>>6?g(k>>6)+[,k&63|128]:k|192)(2**(x=(h=n=>n?-~h(n>>1):3)(n)/5|0)-4<<x*5|n):n ``` [Try it online!](https://tio.run/##XZLLbsIwFET3fEVWlU0N@P2g2Kz6FYgFSnm0QU4FVcUi6q@nvk6aRM0m8py5M9dKPg7fh3t5e//8WsT67diefBt9iCGYLTr7yocqBL09I3jh5x2pnrRoGLf7ddUwxzHi8zl6eHTxMLZd/FxQGmZ4LTCKeKUaihdys3nMVRPxOrYvu1lRUFL0z2pV7Og@SdqRiaQdaIwbMmrp1Il2KjpJQMpESU0Gwlk6MJEJp9JMCBeJONYTOyWQpukQKSRzigxY8EQUYJl30UqJKXY5dwgHrEcs82C379BgnBUs373zwGoCjDYFM6O6JZ1hKuX2HjPWTC4CHj54oAHK/7rGK1FNtRZJ6Iyws4VCA@48Z2Te3jBqrRZ9omL/Wvvq/Wx5qm@vhzJ9@MKHoqzjvb4el9f6jE7pF8C4/QU "JavaScript (Node.js) – Try It Online") ### How? This is essentially the same method as [@Neil's](https://codegolf.stackexchange.com/a/243467/58563). Using the recursive function \$h\$, we compute \$x=\left\lfloor(b+3)/5\right\rfloor\$, where \$b\$ is the number of bits in the input. We compute \$2^x-4\$ (a bit mask consisting of \$x-2\$ ones followed by \$2\$ zeros). We shift it by \$5x\$ positions to the left and OR it with \$n\$. Using the recursive function \$g\$, we convert the result to base \$64\$ in big-endian order. We add \$192\$ to the leading byte and \$128\$ to the other ones. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 171 bytes ``` n=>n<128?n:(F='0bxxxxxxxx '.repeat(c=((d=n.toString(2)).length+3)/5|0)[r='replace'](/ 0bxx/g,' 0b10',i=0))[r](/x/g,_=>i++<c?1:d.padStart(5*c+3,0)[i-c])[r](/0b\d{8}/g,eval) ``` [Try it online!](https://tio.run/##VVDbbtswDH3XV@jNUp04pO5q6/RtP9DHtVhd28k8GLLhaMWAtt@e0UtXoAJEkYeHhxR/NS/NqV2GOW/T1PXnQ31O9T7dogp36Vp8qwt4/vNxeFEt/dw3WbS1EF2dqjzd52VIR6GkrMY@HfPPUsudfQP5fakLYo9N2xePYsdXmd1xU5CDUGyGGiRxKLOiP@r9UJa37R1ed9XcdPe5WbKwV22pNyQ1bNvHCxmeH7rX8E4l/UszynM7pVPmQ5p/Z17zJ2AuMlSebmBojWMKjF9NYNpgtMxZqy/WMR@DxkjZ6NHix6uYBgfO6cCcRwjB6f@OIYp1zmJ0CpkLHqPxzq96n75j6DWCjwR7pNYYIyitLB38EinmDBhQ6L0lUDEPmnSMIYDafw0Nja9dtD4gSVjldFQKqRaUXTkAXkVDX4tAg9hIxeqpOs3jkEXxkAp5ww7TwsXnvvh0uKxN8hWbxr4ap6Mo11TJC77dkyn54R8i5c35Lw "JavaScript (Node.js) – Try It Online") Since `n<128` is an edgecase, just handle it there and then. Next, the code determines the number of bytes using a simple formula: if there are `c` bytes, then there are `5c+1` x's, so we use that. This means subtracting one from the number of bits in the binary representation and dividing that by five. We repeat `xxxxxxxx` that many times. Replace the first two x's of any byte that is not the first with a `10`, then replace the remaining x's with the (padded) binary representation of `n`, then evaluate each byte. Output format: as a number for `n<128`, as a space-separated string (with trailing newline) otherwise. Let me know if this is not allowed. Fails on last testcase due to JavaScript's limitations. *Thanks @Neil for -7 bytes.* [Answer] # [JavaScript (Node.js)](https://nodejs.org), 137 bytes ``` n=>n<128?[n]:eval(`[0b${('1'.repeat((L=(s=n.toString(2)).length+3)/5)+'0'.repeat(~(4.8*~L%6-2))+s).match(/^.{8}|.{6}/g).join`n,0b10`}n]`) ``` [Try it online!](https://tio.run/##hVRNb9pAEL3zK3xo5XUTnP3@aGoqVeqhUm49UipISggRWSOwokiU/HUyM14TN01TDsvuzLw3b2fGezu7n22vNst1M4z1r/nhujrEahQ/Cek/j@Pk4/x@tmLTMb98t2O5yMvNfD2fNYxdVGxbxbKpvzebZVwwWRTlah4Xzc2JKs5McZLzY/Aj06X/8Hjx3g4h7GRblHez5uqGnf0sd37/u9zZ/dmiKG/rZZzGU34p@HQfJ9Pi0GRVNh3wbDjKxnwysIF2NkwGQjrawz8efHsI@jSDA1iMtmSSwoJJgUly3UKkVGAKgkw@mRBoeUIrLYJpHUqCzaBDQyJrjOocgUgSEzpSQk3BrZDE54JXIiQ3JlcY4w0szqCM4IQRye@eeY8y0S@TH0mVfabvNHPLrVXpPhrVecziMJRAToNOJ7j3VrVRRrzI1d2mjdIpCktAdehnTGklN9YaEaxM@o2mWiEEF/98XZSkFLB7B41y1nWlJEgQ/1z6kFRkg7WT4TVNfXXCKcFdgExOuB7SoKq2Ubw7Uk0tLdgTEQKH7hv4iT4y/E9rHyl7SJquNGJvSLaaay6FcwZY@nhHI4pKPY00Hltifew1dNhxBdXSGhjssc/tpL2tPMn/A6/7ePtirt@4hNLKBuO8gFoYaVWQUsCduDTIzLmTQcOXFDh01QRI2b/oa8osOjyN1rHz9AV6nEvnus6QSOu60lAIOZTvqueo7bij8de4GITRGFJZaWiJiopGCEcEcLdpCQ/eHSvK7Xq1bFj@I@b4nq3ZQ1aNsofOPBzlRXE@aMrrevN1Bo9dRPdukGVXddzWq3m5qhfsmn1ZLr7FhkV43@BpzPOsqjJ6c@NYTNBwmv0dBMT74vzwBA "JavaScript (Node.js) – Try It Online") StackExchange code highlight is broken again... Not sure if using string based idea could golf some more bytes or not. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 33 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žy@ibg3+5÷U64Xm32Xm4*-+64вāΘÌ64*+ ``` Port of [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/243467/52210). [Try it online](https://tio.run/##yy9OTMpM/f//6L5Kh8ykdGNt08PbQ81MInKNjSJyTbR0tc1MLmw60nhuxuEeMxMt7f//zQ2MzSzMTUwMzc3NzIwB) or [verify all test cases](https://tio.run/##VU@7SkNhDH6V0rEnQu75M7UvIRTEwYJIh@IgCGfo4OLkIJ18Dhc3l6Or@Ay@yDEHL9BAbl@SL8n1zcVmezne9sv57Ov@MJsv@@FxfH/tV9vNlXQ2vJy6rnfC650uTjrXz@e3u4@n4cF10Y17GM8QPIE4ShuQqQOjxmQaiFIauJn8WIfIJpRVzSCjX88g6OguDTwIW3P5C7RazN0onQm8BaWGx8T3HztQCGFkwUG1mjKRha2EjjIGV1RkirACGQKleFQLqPXHqdb54mnRqCiMXZKZahbZph7E4NR6LbEOsaxhPv8G). **Explanation:** In pseudo-code: For inputs \$<128\$, simply output the input For inputs \$\geq128\$: 1. With \$n\$ as input, first calculate: \$x=\left\lfloor\frac{len(bin(n))+3}{5}\right\rfloor\$ 2. Then calculate \$y=64^x-4\times32^x+n\$ 3. Convert this \$y\$ to a base-64 list 4. Add 128 to each item, and an additional 64 to the very first item, which is the intended output ``` žy@i # If the (implicit) input-integer is >= 128: b # Convert the (implicit) input to a binary string g # Pop and push its length 3+ # Add 3 5÷ # Integer-divide that by 5 U # Pop and store it in variable `X` 64Xm # Push 64 to the power `X` 32Xm # Push 32 to the power `X` 4* # Multiply it by 4 - # Subtract it from each other + # Add the (implicit) input to it 64в # Convert this integer to a base-64 list ā # Push a list in the range [1,length] (without popping) Θ # Convert every non-1 to 0 (with an ==1 check) Ì # Add 2 to each 64* # Multiply each by 64 + # Add the values at the same positions in the lists together # (after which this list is output implicitly as result) # (implicit else:) # (implicitly output the implicit input) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 101 bytes ``` n=>(h=x=>x>>8n?[...h(x>>6n),x%64n+128n]:[x])((g=x=>n>>7n?n>>1n+5n*x?g(++x):64n**x-32n**x:x)(0n)*4n+n) ``` [Try it online!](https://tio.run/##nZbPbhpBDMbveYq9VNoFQsbzx56hYjn1KRAHRAO0ioYqqap9e2rPJLsQtQmzHAZWwr/P/uwx/Nz@2b7snn/8@n0fT98fz/vlOS7b@rjslm3Xtj6u1vP5/FjzZ4zNrPuCNk5B@7hZrLtNU9cH@WZsW4orPiFOXZx0q0M9nXbNgr88mXT3RsvbomtqFZsJA2Jz/rq@qyoVZ1Xp6@GhWqsNB2Moj5ZgDBINmorDJZrjcrgfFx7sTIITw1kshQhDAzLDJIZWlkYxtGFGgFeGH8eQWlD1BRkLwRWSEshoZjgB2eQuOmfGgUKqqi9NQDgGZFMyuVd9fRS8gcKpyzQx2wjSOz7IZdsDgYMiXKbRUORFE4WmR9CkPoNDpUM7FSpEUzQbGSld8FIuCTcpkE39IFDeoylGOnhX89DijLTlSBm6NHmXhffVa@UQHQTUt7coc22aY4HL4Yfeiy3GpKQ98SYgpIIxH@AB/ntcw7EQLsOpw78cufYGyICiwNkT3Lp@BgUnjuQLpt4e0wBiOvLlgBAU7wXHLyhXCJ@7dKmgixXS1ntdfR9ahVZZpYHIsdqNOoMMpQ0rBvm08@Ux69v@iqWLRcpw261lIbz1el3IuI/96k27krHFMvhuqX7onLEGgyMP3Cin0QStgY1U2kkCSpEOln8mguJhd4Ez0/FCq8@c/768OZeuYkoiFUzJPhFEFtzczfen52/b3bGO1bKtdqf4cnp6nD@dDvW@jk3TnP8C "JavaScript (Node.js) – Try It Online") ]
[Question] [ This was inspired by a function I recently added to my language [Add++](https://github.com/SatansSon/AddPlusPlus). Therefore I will submit an short answer in Add++ but I won't accept it if it wins (it wouldn't be fair) Don't you hate it when you can multiply numbers but not strings? So you should correct that, right? You are to write a function or full program that takes two non-empty strings as input and output their multiplied version. How do you multiply strings? I'll tell you! To multiply two strings, you take two strings and compare each character. The character with the highest code point is then added to the output. If they are equal, simply add the character to the output. Strings are not guaranteed to be equal in length. If the lengths are different, the length of the final string is the length of the shortest string. The input will always be lowercase and may contain any character in the printable ASCII range (`0x20 - 0x7E`), excluding uppercase letters. You may output in any reasonable format, such as string, list etc. Be sensible, integers aren't a sensible way to output in this challenge. With inputs of `hello,` and `world!`, this is how it works ``` hello, world! w > h so "w" is added ("w") o > e so "o" is added ("wo") r > l so "r" is added ("wor") l = l so "l" is added ("worl") d < o so "o" is added ("worlo") ! < , so "," is added ("worlo,") ``` So the final output for `hello,` and `world!` would be `worlo,`. # More test cases (without steps) ``` input1 input2 => output programming puzzles & code golf!? not yet graduated, needs a rehaul => prtgyetmirgduuzzlesneedsde rolful king object => oing blended bold => boln lab0ur win. the "super bowl" => the0usuwir. donald j. trumfefe! => trumlefj. ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins! Luok! [Answer] ## Haskell, 11 bytes ``` zipWith max ``` [Try it online!](https://tio.run/##XcxLDgIhEEXRuat4EuPILXRchuOyKT42v0CR2GweGTu/9zhqB4cwp9mGLy8vDpG@M5JP2KDzBUCpPgluMFClZlspRp8sSh8jcMMde9YMm4O5PhVUyoKTBSvUnYT1A4lZNxAqO@pB/aHH0taX3x/eRc0f "Haskell – Try It Online") Nothing much to explain. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` øΣà? ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f//8I5ziw8vsP//v6AoP70oMTc3My9doaC0qiontVhBTSE5PyVVIT0/J03Rnisvv0ShMrVEAagspTSxJDVFRyEvNTWlWCFRoSg1I7E0BwA "05AB1E – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 16 bytes ``` ñl g îUy ®¬ñ oÃq ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=8WwgZyDuVXkgrqzxIG/DcQ==&input=WyJraW5nIiAib2JqZWN0Il0=) Takes input as an array of two strings. Lack of min and max built-ins hurt Japt here, but it still manages to pull off a somewhat decent score... ### Explanation ``` ñl g îUy ® ¬ ñ oà q Uñl g îUy mZ{Zq ñ o} q // Implicit: U = input array ["object", "king"] Uy // Transpose the strings of U. ["ok", "bi", "jn", "eg", "c ", "t "] mZ{ } // Map each string Z to Zq ñ o // the larger of the two chars. (Literally Z.split().sort().pop()) // ["o", "i", "n", "g", "c", "t"] q // Join into a single string. "oingct" Uñl g // Sort the two input strings by length and take the shorter. î // Trim the previous result to this length. // "king"î"oingct" -> "oing" // Implicit: output result of last expression ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` żœ-"« ``` [Try it online!](https://tio.run/##NY09EoIwEIV7TrFSSIM/N/AcDkORsAuCS8KEZBgovYKHsNAjWOl4ES8SzYjdm2@/fa8h5tH71/11XsWPq39eNu/Tbe99FkGW1KpzNklhDnkaYGd0ZUTb1qqCzk0TUw9LKDQSVJrLxS48KG1hJAtfE52whCkoIuxBgKGDcDyXHb8twdeyoeK/IJkUEgYuNeNMWcitMzDUah0u9kAQ964jA1IPHM8WaiUYofk5xrUllbRI8ij/AA "Jelly – Try It Online") ### How it works ``` żœ-"« Main link. Arguemts: s, t (strings) ż Zipwith; form all pairs of corresponding characters from s and t. If one of the strings is longer than the other, its extra characters are appended to the array of pairs. « Dyadic minimum; get all minima of corresponding characters. This yields the characters themselves for unmatched characters. œ-" Zipwith multiset subtraction; remove a single occurrence of the minimum from each character pair/singleton. This yields the maximum for pairs, but an empty string for singletons. ``` ### Example Let **s = blended** and **t = bold**. `ż` yields `["bb", "lo", "el", "nd", 'd', 'e', 'd']`. The last three elements are characters. `«` is the vectorizing, dyadic minimum, so it yields `['b', 'l', 'e', 'd', 'd', 'e', 'd']`. `œ-"` removes exactly one occurrence of the **n**th character in the second array from the **n**th string/character in the first array, yielding `["b", "o", "l", "n", "", "", ""]`. `œ-` is the *multiset subtraction* atom, and the quick `"` makes it vectorize. When printed, this simply reads **boln**. [Answer] # PHP>=7.1, 52 Bytes ``` for(;$t=min(~$argv[1][$i],~$argv[2][$i++]);)echo~$t; ``` [PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/c6373f01fe411441e74865d25e7600b8aef6e259) # PHP>=7.1, 69 Bytes ``` for([,$a,$b]=$argv;(~$c=$a[$i])&&~$d=$b[$i++];)$r.=max($c,$d);;echo$r; ``` [PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/6c981e474956faddb84243a4d5565cfc9dd43b39) # PHP>=7.1, 70 Bytes ``` for([,$a,$b]=$argv;(~$c=$a[$i])&&~$d=$b[$i++];)$r.=$c>$d?$c:$d;echo$r; ``` [PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/458e9e9ea8c8f858dea9b6b8f10c9cfff42e54a3) [Answer] ## [Alice](https://github.com/m-ender/alice), 8 bytes ``` /oI\ @m+ ``` [Try it online!](https://tio.run/##S8zJTE79/18/3zOGyyFX@///pJzUvJTUFK6k/JwUAA "Alice – Try It Online") ### Explanation Alice also has this operator (which I called *superimpose*) but it doesn't limit the output to the shorter string's length (instead, the remaining characters of the longer string are appended). However, it also has an operator to truncate the longer of two strings to the length of the shorter one. ``` / Reflect to SE, switch to Ordinal. The IP bounces diagonally up and down through the code. m Truncate, doesn't really do anything right now. I Read a line of input. The IP bounces off the bottom right corner and turns around. I Read another line of input. m Truncate the longer of the two input lines to the length of the shorter. + Superimpose: compute their elementwise maximum. o Output the result. @ Terminate the program. ``` [Answer] ## JavaScript (ES6), ~~47~~ 45 bytes ``` f= (a,b)=>a.replace(/./g,(c,i)=>c>b[i]?c:[b[i]]) ``` ``` <div oninput=o.textContent=f(a.value,b.value)><input id=a><input id=b><pre id=o> ``` Conveniently `c>b[i]` returns false past the end of `b`. Edit: Saved 2 bytes thanks to @ETHproductions. [Answer] # [Perl 6](http://perl6.org/), 22 bytes ``` {[~] [Zmax] @_».comb} ``` As a bonus, it accepts any number of multiplicands, not just two. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` żḊ€ṁ@» ``` [Try it online!](https://tio.run/##ATQAy/9qZWxsef//xbzhuIrigqzhuYFAwrv///9sYWIwdXIgd2luLv90aGUgInN1cGVyIGJvd2wi "Jelly – Try It Online") [Answer] ## [Retina](https://github.com/m-ender/retina), 28 bytes ``` {O^` G`. ^.+$ M!\*`^. Rm`^. ``` [Try it online!](https://tio.run/##K0otycxL/P@/2j8ugcs9QY8rTk9bhYvLVzFGKyFOjysoF0j@/5@Uk5qXkprClZSfkwIA "Retina – Try It Online") ### Explanation ``` {O^` ``` The `{` tells Retina to run the entire program in a loop until it fails to change the working string. `O` makes this a sorting stage which sorts non-empty lines by default. The `^` option reverses the result. So in effect, we get a reverse sort of the two lines if they're non-empty, putting the line with the larger leading character at the top. ``` G`. ``` Discard empty lines if there are any. ``` ^.*$ ``` If only one line is left, one of the lines was empty, and we remove the other one as well to stop the process. ``` M!\*`^. ``` Lots of configuration going on here. This matches (`M`) the first character in the working string (`^.`), returns it (`!`), prints it without a trailing linefeed (`\`) and then reverts the working string to its previous value (`*`). In other words, we simply print the first character of the working string (which is the maximal leading character) without actually changing the string. ``` Rm`^. ``` Finally, we remove the first character from each line, so that the next iteration processes the next character. [Answer] # C, 58 bytes ``` f(char*s,char*t){putchar(*s>*t?*s:*t);*++s&&*++t&&f(s,t);} ``` [**Try Online**](https://tio.run/##NYxLCsMgGIT3OcVfF0aNvUADzUW6EV8JGA0@KE3I2a0tZBYzwzB88m6lrNUQOYvIEv9HpsdW8q8Slp4sTyw92jiyYUgYN88YG5J4m866@AyrWDyh3dFBkyFo1s4Fjjh6h@jUDdHx4vUv39Px@m0x2CjWdfEWtrLvTifAIIPSYIMzt6khfMjw0RnaURWRteLgtVYJBEQ9i@IavTvrFw) * -8 bytes @Steadybox [Answer] # [Husk](https://github.com/barbuz/Husk), 2 bytes ``` z▲ ``` [Try it online!](https://tio.run/##yygtzv7/v@rRtE3///9XSspJzUtJTVECsvJzUpQA "Husk – Try It Online") ### "Ungolfed"/Explained Makes use of `zip f` that truncates the shorter list such that there are always two arguments for `f`, e.g. `zip f [1,2] [3,4,5] == zip f [1,2] [3,4] == [f 1 3, f 2 4]`: ``` z -- zip the implicit lists A,B with - e.g. "ab" "bcd" (lists of characters) ▲ -- maximum - [max 'a' 'b', max 'b' 'c'] -- implicitly print the result - "bc" ``` [Answer] ## Mathematica, 78 bytes ``` FromCharacterCode[Max/@Thread[#~Take~Min[Length/@x]&/@(x=ToCharacterCode@#)]]& ``` There is another answer in *Mathematica* already. This answer take input as a list of strings, so `/@` can be used on `#` instead of `{##}`. And we can just `Map` the long function name on object instead of assigning it to variables. (in fact, each Mathematica built-in symbol name is used at most once in the function) [Answer] # [Python 2](https://docs.python.org/2/), ~~47~~ ~~44~~ 34 bytes *-3 bytes thanks to musicman523. -10 bytes thanks to Blender.* Takes input as a list of strings. ``` lambda a:''.join(map(max,zip(*a))) ``` [Try it online!](https://tio.run/##TZDRasMwDEXf8xVqH@ZkhDL2WCj7kK4MOZYTZ4plHJus@fksWccygUD43HuFFe6pE/@62Mv7wjhog4BnpU69OF8OGNb@qmcXymesqmpJNKaPBkca4QLXAta6qo6YpVY1qEkim4O61b/E@ZDTBh7D33uI0kYcBudbCHmeec17gkYMQStsD2@bx0uCOyVYlSZjIlODJzIjIETqMPOe97kGbRbRPTX/9mgmb8hsSAubHTDqlxxhcv60wdQRHMccKIKWiY@70IhHNtA/ZDEPliytPyxuRWElggPnYb/K@ccWovMJbOmq5Rs "Python 2 – Try It Online") [Answer] # [V](https://github.com/DJMcMayhem/V), ~~28, 24~~, 21 bytes ``` Í./&ò dd{JdêHPÎúúx Íî ``` [Try it online!](https://tio.run/##K/v//3Cvnr7a4U1cKSnVXimHV3kEHO47vOvwrgquw72H1/3/n5Gak5NfBQRc5flFOSn2AA "V – Try It Online") Hexdump: ``` 00000000: cd2e 2f26 f20a 6464 7b4a 64ea 4850 cefa ../&..dd{Jd.HP.. 00000010: fa78 0acd ee .x... ``` *Three bytes saved thanks to @nmjcman101!* Explanation: ``` Í " Globally substitute: . " Any character / " With: & " That character ò " And a newline dd " Delete this line { " Move to the first empty line J " Delete this line dê " Columnwise delete the second word HP " Move to the first line, and paste the column we just deleted Î " On every line: úú " Sort the line by ASCII value x " And delete the first character Í " Remove all: î " Newlines ``` [Answer] # Javascript (ES2015), 66 63 49 bytes ``` a=>b=>[...a].map((c,i)=>c>b[i]?c:b[i]||'').join`` ``` **Explanation:** ``` a=>b=> // Function with two string parameters [...a] // Split a into array of characters .map((c, i) => // Iterate over array c>b[i] ? c : b[i]||'') // Use the character with the larger unicode value until the end of the larger string .join`` // Join the array into a string ``` **Previous Versions:** ``` //ES2015 a=>b=>[...a].map((c,i)=>c>b[i]?c:b[i]).slice(0,b.length).join`` //63 a=>b=>a.split``.map((c,i)=>c>b[i]?c:b[i]).slice(0,b.length).join`` //66 a=>b=>a.split``.map((c,i)=>c>b[i]?c:b[i]).slice(0,Math.min(a.length,b.length)).join`` //85 a=>b=>{for(i=-1,c='';++i<Math.min(a.length,b.length);)c+=a[i]>b[i]?a[i]:b[i];return c} //86 a=>b=>{for(i=-1,c='';++i<Math.min(a.length,b.length);)c+=a[d='charCodeAt'](i)>b[d](i)?a[i]:b[i];return c} //105 a=>b=>a.split``.map((c,i)=>c[d='charCodeAt']()>b[d](i)?c:b[i]).slice(0,Math.min(a.length,b.length)).join`` //106 //With array comprehensions a=>b=>[for(i of a.split``.map((c,i)=>c>b[i]?c:b[i]))i].slice(0,b.length).join`` //79 a=>b=>[for(i of a.split``.map((c,i)=>c>b[i]?c:b[i]))i].slice(0,Math.min(a.length,b.length)).join`` //98 a=>b=>[for(i of ' '.repeat(Math.min(a.length,b.length)).split``.map((_,i)=>a[i]>b[i]?a[i]:b[i]))i].join`` //105 a=>b=>[for(i of Array.apply(0,Array(Math.min(a.length,b.length))).map((_,i)=>a[i]>b[i]?a[i]:b[i]))i].join`` //107 a=>b=>[for(i of a.split``.map((c,i)=>c[d='charCodeAt']()>b[d](i)?c:b[i]))i].slice(0,Math.min(a.length,b.length)).join`` //119 a=>b=>[for(i of ' '.repeat(Math.min(a.length,b.length)).split``.map((_,i)=>a[d='charCodeAt'](i)>b[d](i)?a[i]:b[i]))i].join`` //124 a=>b=>[for(i of Array.apply(0,Array(Math.min(a.length,b.length))).map((_,i)=>a[d='charCodeAt'](i)>b[d](i)?a[i]:b[i]))i].join`` //127 ``` [Answer] # Java 8, ~~124~~ ~~120~~ ~~117~~ 63 bytes ``` a->b->{for(int i=0;;i++)System.out.print(a[i]>b[i]?a[i]:b[i]);} ``` -4 bytes thanks to *@Khaled.K*. -3 bytes thanks to *@Jakob*. Inputs are two character-arrays, and it stops with an `ArrayIndexOutOfBoundsException`. **Explanation:** [Try it here.](https://tio.run/##bVLBbtswDL3nK1gdVht2jJ6b1cVQbNhlpx52SHKgLDpRKkuCTLVLg3x7JsceNhe7CE96jxQfyQO@4tJ5sgf1cmkM9j38QG1PC4CekXUDh6SoImtTtdE2rJ2tvk3gc7PHsN6W/9M8OdvHjsKkqWto4QEuuKzlsj61LmTaMuiHu9VKF0X@fOyZuspFrnxITIZrva1lOh4HdD@gfHW@rBapMh@lSZVNBb46raBLRWfPnEJ36y1gPhgAYOo5E9/JGFeKEsRPF4y6EfnqH1ZbH3kgRzDjfHC7gF2XsqZP398N9fAJGqcIds60N49DnHUMR2JIShWRSZVgiVQPCIH2GM0850tKNoQ5eaCGYU5KQ1aRGnjpjJqTBuVdDPCmbTUIeE@wEX30FEC6N7MRc7lyFo2CwygOsWuppcn8efF3wNf@XUPG/gGWMCH5p4/hOAKAtkLvzTHDit1TGu2XEPCY5XmFTUOeM/nhfazo3CA3@@zrr0GT1gMoP00jpxDGkRub3YrbAguxEYBWJXOikNdbz857Usk67xMFKcaFexAFpZ24fvBxf1Kyyej58hs) ``` a->b->{ // Method with two char-array parameters and no return-type for(int i=0;;i++) // Loop `i` from 0 up indefinitely (until an error is given) System.out.print( // Print: a[i]>b[i]?a[i]:b[i]);} // The character that has the highest unicode value ``` [Answer] # C#, 81 78 bytes ``` a=>b=>{var s="";try{for(int q=0;;q++)s+=a[q]>b[q]?a[q]:b[q];}catch{}return s;} ``` C# has implicit `char` to `int` conversion (because a `char` is actually an `int` underneath) which is nice, and instead of looking for shortest string just try until failure [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` otX>cwA) ``` Input is a cell array of strings, in the format `{'abcd' 'efg'}` [Try it online!](https://tio.run/##y00syfn/P78kwi653FHz//9q9aSc1LyU1BR1BfWk/JwU9VoA "MATL – Try It Online") As an aside, this also works [for more than two strings](https://tio.run/##y00syfn/P78kwi653FHz//9q9aSc1LyU1BR1BfWk/BwQlZiUXJeSmqZeCwA). ### Explanation Consider input `{'blended' 'bold'}`. The stack is shown upside down, with more recent elements below. ``` o % Implicitly input a cell array of strongs. Convert to numeric % vector of code points. This right-pads with zeros if needed % STACK: [98 108 101 110 100 101 100; 98 111 108 100 0 0 0] tX> % Duplicate. Maximum of each column % STACK: [98 108 101 110 100 101 100; 98 111 108 100 0 0 0], [98 111 108 110 100 101 100] c % Convert to char % STACK: [98 108 101 110 100 101 100; 98 111 108 100 0 0 0], 'bolnded' w % Swap % STACK: 'bolnded' [98 108 101 110 100 101 100; 98 111 108 100 0 0 0] A % All: gives true (shown as 1) for columns containing only nonzeros % STACK: 'bolnded' [1 1 1 1 0 0 0] ) % Use as logical index (mask). Implicitly display % STACK: 'boln' ``` [Answer] ## R, 103 bytes Code: ``` n=min(sapply(y<-strsplit(scan(,"",sep="\n"),""),length));cat(mapply(max,el(y)[1:n],y[[2]][1:n]),sep="") ``` Test cases: ``` > n=min(sapply(y<-strsplit(scan(,"",sep="\n"),""),length));cat(mapply(max,el(y)[1:n],y[[2]][1:n]),sep="") 1: programming puzzles & code golf!? 2: not yet graduated, needs a rehaul 3: Read 2 items prtgretmirgduuzzlesneedsde rolful > x <- scan(,"",sep=NULL) 1: asd asd 3: Read 2 items > n=min(sapply(y<-strsplit(scan(,"",sep="\n"),""),length));cat(mapply(max,el(y)[1:n],y[[2]][1:n]),sep="") 1: king 2: object 3: Read 2 items oing > n=min(sapply(y<-strsplit(scan(,"",sep="\n"),""),length));cat(mapply(max,el(y)[1:n],y[[2]][1:n]),sep="") 1: lab0ur win. 2: the "super bowl" 3: Read 2 items the0usuwir. ``` [Answer] # Kotlin, ~~50~~ ~~41~~ 37 bytes -9 bytes with function reference syntax -4 bytes with extension function ``` fun String.x(o:String)=zip(o,::maxOf) ``` If s, and x are in scope, and not in a function, this method is only 16 bytes ``` s.zip(x,::maxOf) ``` [Demo](https://try.kotlinlang.org/#/UserProjects/nubfa8m87ehb35729vbh64f439/jnj1je8dmgim992ti2c5dtakr4) [Answer] # Excel, 86 bytes ``` =LET(x,SEQUENCE(MIN(LEN(A1),LEN(A2))),d,MID(A1,x,1),e,MID(A2,x,1),CONCAT(IF(d>e,d,e))) ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 12 bytes ``` q~z{1/~e>o}% ``` Input is a list of two strings. The program exits with an error (after producing the right output) if the two strings have different lengths. [**Try it online!**](https://tio.run/##S85KzP3/v7CuqtpQvy7VLr9W9f//aKXszLx0JQWl/KSs1OQSpVgA "CJam – Try It Online") ### Explanation ``` q~ e# Read input and evaluate z e# Zip: list of strings of length 2, or 1 if one string is shorter { }% e# Map this block over list 1/ e# Split the string into array of (1 or 2) chars ~ e# Dump the chars onto the stack e> e# Maximum of two chars. Error if there is only one char o e# Output immediately, in case the program will error ``` [Answer] ## Clojure, 31 bytes ``` #(map(comp last sort list)% %2) ``` Yay for function composition :) Returns a sequence of characters instead of a string, but they mostly work the same way in Clojure except when printing or regex matching. Sadly `max` does not work with characters. [Answer] # JavaScript (ES6), 47 bytes ``` f=([S,...s],[T,...t])=>S&&T?(S>T?S:T)+f(s,t):'' ``` A recursive solution, which walks the string, always outputting the largest character. **Snippet:** ``` f=([S,...s],[T,...t])=>S&&T?(S>T?S:T)+f(s,t):'' console.log(f('programming puzzles & code golf!?','not yet graduated, needs a rehaul')); console.log(f('king','object')); console.log(f('blended','bold')); console.log(f('lab0ur win.','the "super bowl"')); console.log(f('donald j.','trumfefe!')); ``` [Answer] # [Julia 0.5](http://julialang.org/), 33 bytes Pretty much the same concept as Python2, but shorter. ``` a->join(map(maximum,(zip(a...)))) ``` [Try it online!](https://tio.run/##ZZDBasMwDIbveQo1hzWBNOyyY9cHGWMosdw4ky3j2GTLe@@cOSujbBEIBP/3/xIaExt8WvV5xdPzKMZVFn3uD2OTbarF@Arbtq1zrZGm@NbjRBOc4aWAe1XlQMzSlA2UswRWh7Ju/gLG@RQ3/Tb8l32Qa0BrjbuCT8vCeckD9KIIrsL6cNmsTiJ8UoRMqoSRVAOOSE2AEGjAxLvY95y3OaUbqd9v7ZicIrURnbDa6YzdYwowG9duTBwIjlPyFKCTmY87XolDVjDe6JCsJk35F7/Ua1FoCWDAOLh/80f1wbhY6crUdZGPWr@cnHrsB/oG "Julia 0.5 – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina), ~~55~~ 36 bytes ``` ^ ¶ {O`¶.* }`¶.(.*)¶(.) $2¶$1¶ 1!`.* ``` [Try it online!](https://tio.run/##K0otycxL/P8/juvQNq5q/4RD2/S0uGpBlIaeluahbRp6mlwqRoe2qRgC5Q0VE/S0/v/PzsxL58pPykpNLgEA "Retina – Try It Online") Explanation: A line is prefixed to hold the result. While both strings still have characters left the inputs are sorted and the leading character with the highest code point is moved to the result while the other leading character is deleted. Finally the result is printed. [Answer] # J, 25 bytes ``` >./&.(a.&i.)@(<.&#{."1,:) ``` # explanation half the bytes go to solving ensuring both inputs have the shorter inputs length (would love to see an improvement on this portion, if anyone has one): ``` (<.&#{."1,:) ``` `<.&#` is the minimum of the two lengths, and `{."1,:` takes that many characters from both rows of the 2-row table consisting of the left string stacked on top of the right one. ``` >./&.(a.&i.) ``` Use the Under verb `&.` to convert each character to its ascii index, take the maximum of the two numbers, and then convert back to characters. [Try it online!](https://tio.run/##LctBCoMwFATQvaf4REgUytduS1tKD9A7GPPV2JCUaMjCw6dB3Q0zb@aUhgfCExuOVYdcY/2q7sjLDdn1cqsL6icH4qvtKGAA4eRM/Srg80ZwuTx3acgqUjuRzqgD5GRPYDrZBg9RW9zROhGwJfzIZxUNOw65bcMSovZYpPQH "J – Try It Online") [Answer] # [Add++](https://github.com/SatansSon/AddPlusPlus), 8 bytes ``` D,f,@@,^ ``` [Try it online!](https://tio.run/##S0xJKSj4/99FJ03HwUEn7r9Kmo69jj2XO5f///9KHqk5Ofk6Sv@VwvOLclIUlf7lF5Rk5ucV/9fVLUstKgYybQ30TAA "Add++ – Try It Online") In versions 0.4 through 1.11, `^` exponents two numbers or "multiplies" two strings, depending on the type of the arguments. [Answer] # [Python 3](https://docs.python.org/3/), 29 bytes ``` lambda*a:''.join(map(max,*a)) ``` [Try it online!](https://tio.run/##TZDBasMwEETv/opNDrVjTCj0Fgj5kDSUlbWy5a61QpZwk5935abUFQjEvplZNP4ee3Fvizm/L4yj0ljjqSyPg1hXjejz/WpqPByWSFP8aHGiCc5wLSCfa9kTszRlA@UsgfWuvDW/xDqf4gqej7@5D9IFHEfrOvDp8eCc9wKtaIJO2Owuq8dJhDtFyEqdMJJuwBHpCRAC9Zh4y/vMQatF1EDtvz2KyWnSK1LCegOM6jUFmK07rjD2BPspeQqgZOb9JtTikDUMT1lIoyFD@YfFrSiMBLBgHWytnH5sPlgXK1PVNlf2DQ "Python 3 – Try It Online") --- # [Coconut](http://coconut-lang.org/), 17 bytes ``` ''.join<..map$max ``` [Try it online!](https://tio.run/##TZBdTsMwEITfc4pthTCgKOIALRykVMixN4nTtdfyjwIVdw@2ikj9Ymu/mVl5FCt2Oa3D8WMVopvZuEPXWekfrPxaE8b0qWTECEc4NVDOSUxIxK1oQSwcSO/Euf0jxvmcKrg9/uc@8BiktcaN4PP1SiXvERRrhJFp2L1Xj@ME35igKHWWCXULDlFHkBBwkpm2vEsJqhbuZ1R3e3pCp1FX1DPpDZDsX3OAxbiuwjQh7GP2GKDnhfabULOTpGG@yUK2Aw5Yfticm@aujJ83qBU9@WBcglIYDHB4KReZmJ4rLq3GbHH9BQ "Coconut – Try It Online") ]
[Question] [ # Task Given a **non-empty** array of `0` and `1`, halve the lengths of the runs of `0`. # Input An array of `0` and `1`. Acceptable format: * Real array in your language * Linefeed-separated string of `0` and `1` * Contiguous string of `0` and `1` * Any other reasonable format For example, the following three inputs are all acceptable: * `[1, 0, 0, 1]` * `"1\n0\n0\n1"` (where `\n` is a linefeed U+000A) * `"1001"` You may assume that the runs of `0` will have **even length**. # Output An array of `0` and `1`, in the acceptable formats above. # Testcases ``` input ↦ output [1,0,0,1,0,0,1] ↦ [1,0,1,0,1] [1,1,0,0,1,1,0,0,1] ↦ [1,1,0,1,1,0,1] [1,1,0,0,1,1,1,0,0,1,1] ↦ [1,1,0,1,1,1,0,1,1] [1,1,1] ↦ [1,1,1] [0,0,1] ↦ [0,1] [0,0] ↦ [0] [1,1,1,0,0,0,0,1,1,1,1,0,0,1,0,0,1,1,0,0,1,1,1,1,0,0,1,0,0] ↦ [1,1,1,0,0,1,1,1,1,0,1,0,1,1,0,1,1,1,1,0,1,0] ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. [Answer] ## [Retina](https://github.com/m-ender/retina), 4 bytes ``` 00 0 ``` [Try it online!](https://tio.run/nexus/retina#@29gwGXw/7@hoaEBEBiCaRAyROIAAA "Retina – TIO Nexus") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` 00¤.: ``` [Try it online!](https://tio.run/nexus/05ab1e#@29gcGiJntX//4aGhgZAYAimQcgQiQMA "05AB1E – TIO Nexus") **Explanation** ``` 00 # push 00 ¤ # tail, pushes 0 .: # replace ``` [Answer] # [Haskell](https://www.haskell.org/), 33 bytes ``` f(0:0:r)=0:f r f(x:r)=x:f r f e=e ``` [Try it online!](https://tio.run/nexus/haskell#@5@mYWBlYFWkaWtglaZQxJWmUQHiVEA4Cqm2qf9zEzPzFGwVCooy80oUVBTSFKINdUDQAAoNdRB8Q7gIVpnY/wA "Haskell – TIO Nexus") Usage: `f[1,1,0,0,1,1,0,0,1]`. Iterates over the list and replaces two consecutive zeros by one zero. [Answer] # [C (gcc)](https://gcc.gnu.org/), 35 bytes ``` f(char*s){while(*s)putchar(*s),*s++-48?:s++;} ``` 48 is the ascii code of '0' better version 43 bytes as suggested by Neil ``` f(char*s){while(*s)putchar(*s),s+=2-*s%2;} ``` another one 40 byte this time (again as suggested by Neil & VisualMelon) :) ``` f(char*s){for(;*s;s+=50-*s)putchar(*s);} ``` and then 35 bytes thanks to Khaled.K ``` f(char*s){*s&&f(s+50-putchar(*s));} ``` [Try it online!](https://tio.run/nexus/c-gcc#@5@mkZyRWKRVrFmtVaymlqZRrG1qoFtQWgIS1QAKa1rX/s/MK1HITczM09DkquZSSNNQMjAwBCIgADNAwDDGQEnTmqv2PwA "C (gcc) – TIO Nexus") [Answer] # [sed](https://www.gnu.org/software/sed/), 8 bytes ``` s/00/0/g ``` [Try it online!](https://tio.run/nexus/sed#@1@sb2Cgb6Cf/v@/oYEBCHEZgkgkFpgAsg25QGIGBgA "sed – TIO Nexus") [Answer] # Octave, 22 bytes ``` @(s)strrep(s,'00','0') ``` [**Verify all test cases here.**](https://tio.run/#TAaXw) This is an anonymous function taking a string on the format `'1001000011'` as input, and replaces two consecutive zeros with a single zero. [Answer] # [Haskell](https://www.haskell.org/), 28 bytes ``` f(h:t)=h:f(drop(1-h)t) f e=e ``` [Try it online!](https://tio.run/nexus/haskell#@5@mkWFVommbYZWmkVKUX6BhqJuhWaLJlaaQapv6PzOvoLSkWMFWITraUMcACKFkrA6QDxPBLgZnQcVBNEwdkIaJglUh9KDYgmIakkxsLBdXbmJmHtBdBUWZeSUKKgq5iQUKaQoQ5/4HAA "Haskell – TIO Nexus") Recursively takes the first element, dropping the second one if the first one is zero, until the list of empty. If the first entry is `h`, then the first `1-h` are dropped from the remainder. [Answer] # Java, 50 bytes ``` String f(String s){return s.replaceAll("00","0");} ``` [**Try Online**](http://ideone.com/2lMKHM) [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~7 6~~ 5 bytes ``` d'0²0 ``` [Try it online!](https://tio.run/nexus/japt#@5@ibnBok8H//0qGBgYgpAQA "Japt – TIO Nexus") Simply replaces each run of two zeroes in the input by one zero. Uses string input (i.e. `"1001001"`). [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` fG=¹ ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8X@au@2hnf///4@ONtQxAEIoGasD5MNEsIvBWVBxEA1TB6RhomBVCD0otqCYhiQTGwsA "Husk – Try It Online") **How?** The [Husk](https://github.com/barbuz/Husk) `scanl` command (`G`) applies a function to each element of a list and the result-so-far. The initial result-so-far is set to the first element. In this case, used with the `eq` (`=`) function, it checks whether each element is equal to the result-so-far. For runs of `1`, this will always output `1` (truthy). Now, the first of any run of `0`s will be `0` (falsy), of course; then, the next result will be `1` (since `0` is equal to the result-so-far), and then `0`, and so on, alternating `0`s at odd positions in the run and `1`s at even positions, until the end of the run. Since there are always an even number of `0`s in each run, then last result-so-far must be `1`: so, when we enter the next run of `1`s, the first result will be `1` (truthy) again, and so on... So: runs of `0`s get alternating `0` and `1`, and runs of `1`s always get `1`, and we just need to `filter` (`f`) the input list (`¹`) by this. [Answer] ## [Alice](https://github.com/m-ender/alice), 13 bytes ``` /oe00/ @iS0e\ ``` [Try it online!](https://tio.run/nexus/alice#@6@fn2pgoM/lkBlskBrz/7@hoaEBEBiCaRAyROIAAA "Alice – TIO Nexus") ### Explanation ``` /.../ @...\ ``` This is a simple template for linear programs which operate entirely in Ordinal mode. The initial `/` reflects the IP to move south east and then it bounces diagonally up and down through the code until the mirrors at the end. Those simply offset the position by one so that on the way back the IP traverses the remaining cells. Reading the code in this zigzag fashion it becomes: ``` ie00e0So@ ``` This is a simple string substitution: ``` i Read all input. e Push an empty string. 00 Append two zeros to create the string "00". e Push an empty string. 0 Append a zero to create the string "0". S Substitute all occurrences of "00" in the input with "0". o Output the result. @ Terminate the program. ``` There are a few other ways to push the two strings, e.g. `'00'0` or `e000t`, but I haven't found anything that beats 5 bytes there (and I'd have to shave off two bytes to be able to shorten the program). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ṣ1j1,1m2 ``` [Try it online!](https://tio.run/nexus/jelly#@/9w52LDLEMdw1yj////A2kgNIBCQx0E3xAuglUGAA "Jelly – TIO Nexus") Possibly other answers in languages without a `.replace()` or similar could use this trick. **Explanation** ``` ṣ1j1,1m2 - (duplicates the 1s, then halves all lengths) ṣ1 - split by the element 1 j1,1 - join the elements with the two-element list 1,1 m2 - get every second element ``` [Answer] # Perl 5, 7+1(-p flag)=8 bytes ``` <>if/0/ ``` Takes input as newline separated numbers. Skips the next line if it sees a zero. [Answer] # [V](https://github.com/DJMcMayhem/V), 4 bytes ``` òf0x ``` [Try it online!](https://tio.run/nexus/v#@394U5pBxf//BkBgCAQwEsGHAAA "V – TIO Nexus") ``` ò ' Recursively (until we error) f0 ' Go to the next zero (errors when there are no zeros left) x ' Delete it ``` [Answer] # [sed](https://www.gnu.org/software/sed/), ~~8~~ 6 bytes ``` n;/0/d ``` [Try it online!](https://tio.run/##K05N0U3PK/3/P89a30A/5f9/Ay4DLkMwNIBCw3/5BSWZ@XnF//VTUsv0i0tSMvMA "sed – Try It Online") Takes a linefeed-separated string of `0` and `1`. `n` skips a line, and `/0/d` deletes a line if it has a zero in it. This has the net effect of deleting every `0` on an even-numbered line. Since any even-length contiguous list of `0` has the same number of even-numbered and odd-numbered lines, this has the effect of halving the length of every run of `0`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ¹‘ƭƇ ``` [Try it online!](https://tio.run/##y0rNyan8///QzkcNM46tPdb@/3D7o6Y1kf//R3NFG@oYACGUjNUBCcCEcAjCWTAJMAOuFMiAS4BVIvSh2IViIpIMUHMsAA "Jelly – Try It Online") ## Explanation ``` ¹‘ƭƇ Main monadic link Ƈ Filter by ƭ Every time this is called, switch between ¹ doing nothing and ‘ adding 1 ``` [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 42 bytes ``` [0,0|T]*[0|R]:-T*R. [H|T]*[H|R]:-T*R. H*H. ``` [Try it online!](https://tio.run/nexus/prolog-swi#@x9toGNQExKrFW1QExRrpRuiFaTHFe0BFvFAiHhoeej9/x9tqAOCBlBoqIPgG8JFsMrEakXocZUXZZakakRoAgA "Prolog (SWI) – TIO Nexus") [Answer] # PHP, 26 ``` <?=strtr($argn,["00"=>0]); ``` simply replace all `00` by `0`. [Answer] # Lua, 33 bytes ``` print((io.read():gsub("00","0"))) ``` Takes a string via input and condenses double zeros. Easy. [Answer] # [MATL](https://github.com/lmendo/MATL), 5 bytes ``` FFOZt ``` [**Try it online!**](https://tio.run/nexus/matl#@@/m5h9V8v9/tKGOARBCyVgA) ### Explanation This is similar to Stewie Griffin's [Octave answer](https://codegolf.stackexchange.com/a/118609/36398): ``` FF % Push [0 0] O % Push 0 Zt % Implicitly take input. Replace [0 0] by 0. Implicitly display ``` --- # 8 bytes ``` vy~f2L)( ``` This avoids the string/array replacement builtin. [**Try it online!**](https://tio.run/nexus/matl#@19WWZdm5KOp8f9/tKGOARBCyVgA) ### Explanation Consider input `[1,0,0,1,0,0,1]` as an example: ``` v % Concatenate stack (which is empty): pushes [] % STACK: [] y % Implicit input. Duplicate from below % STACK: [1,0,0,1,0,0,1], [], [1,0,0,1,0,0,1] ~f % Negate, find: gives indices of zeros % STACK: [1,0,0,1,0,0,1], [], [2,3,5,6] 2L % Push [2,2,1i]. As an index, this is interpreted as 2:2:end % STACK: [1,0,0,1,0,0,1], [], [2,3,5,6], [2,2,1i] ) % Reference indexing. This selects the even-indexed entries % STACK: [1,0,0,1,0,0,1], [], [3,6] ( % Assignment indexing. This deletes the specified entries % (assigns them the empty array). Implicitly display % STACK: [1,0,1,0,1] ``` [Answer] # [Alice](https://github.com/m-ender/alice), ~~12~~ 10 bytes *2 bytes saved thanks to [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender)* ``` i.h%.7%$io ``` [Try it online!](https://tio.run/nexus/alice#@5@pl6GqZ66qkpn//7@hoaEBEBiCaRAyROIAAA "Alice – TIO Nexus") ### Explanation This is a 1-D code operating in cardinal mode, so it's easy to follow its flow: ``` i Read a byte from input (pushes -1 on EOF) .h Duplicate it and add 1 to the copy % Compute n%(n+1). This will exit with an error on n==-1 and return n for any non-negative n. .7% Duplicate the input again and compute its value modulo 7 This returns 6 for '0' (unicode value 48) and 0 for '1' (unicode value 49) $i If this last result was not 0, input another number. This ignores every other '0' in the input and moves to the following number (another '0') o Output the last byte read At the end, wrap back to the beginning of the line ``` [Answer] # [Java](http://openjdk.java.net/), ~~131~~ 123 bytes ``` int[]f(int[]a){int c=0,i=0,l=a.length;for(int x:a)c+=1-x;int[]r=new int[l-c/2];for(c=0;c<l;c+=2-a[c])r[i++]=a[c];return r;} ``` [Try it online!](https://tio.run/nexus/java-openjdk#bY89bsMwDIV3n0KjBNtqnLGqhh6gU0ZDA6vargpFNig6TWD47K7k9GcpCOFR5HvAx2l@9c4y6yFG9gIuLJsL1Jqe7wJiScqsPlQuPa9B@i4M9K76EbOFXR9B2FI39VXtCdSh@2S59bV9OJrdmPLKPnmVjMcaWmsEtq4sjc69wo5mDAzVuk13nEhASS6je2PnBMVPhC4MiQeHKJbidIvUneU4k5zSgnzgH3ABOZPz8hkRblHSeA/xzJMv40L2/AfOLE2V6/BdTfX3b34n/25WIYQq1mLdvgA "Java (OpenJDK 8) – TIO Nexus") [Answer] # JavaScript (ES6), ~~26~~ 21 bytes Takes the input as a string and returns a string. ``` s=>s.replace(/00/g,0) ``` --- ## Try It ``` f= s=>s.replace(/00/g,0) i.addEventListener("input",_=>o.innerText=f(i.value)) console.log(f("1001001")) // "10101" console.log(f("110011001")) // "1101101" console.log(f("11001110011")) // "110111011" console.log(f("111")) // "111" console.log(f("001")) // "01" console.log(f("00")) // "0" console.log(f("11100001111001001100111100100")) // "1110011110101101111010" ``` ``` <input id=i><pre id=o> ``` [Answer] # Mathematica, 24 bytes ``` StringReplace["00"->"0"] ``` A function that expects a string of `"0"`s and `"1"`s and returns a similar string. Self-explanatory syntax. Mathematica has lots of transformation builtins; the key is to use one that transforms every relevant subexpression (unlike `/.`) but only passes through the expression once (unlike `//.`). [Answer] # [Pip](https://github.com/dloscutoff/pip), 5 bytes ``` aR00i ``` Takes a string of 0s and 1s. [Try it online!](https://tio.run/##K8gs@P8/McjAIPP///@GhoYGQGAIpkHIEIkDAA "Pip – Try It Online") ### Explanation Beating Jelly? Inconceivable! ``` a Take the first command-line argument R and replace 00 00 (an integer literal, so it doesn't need quotes) i with i (variable preinitialized to 0) Autoprint ``` [Answer] # [R](https://www.r-project.org/), 21 bytes ``` function(n)n[n+1:0>0] ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPMy86T9vQysDOIPZ/mkayhqGOARAaamr@BwA "R – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes ``` ɖ=Tİ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLJlj1UxLAiLCIiLCJbMSwxLDAsMCwxLDEsMSwwLDAsMCwwLDEsMCwwLDFdIl0=) Port of [Dominic van Essen's Husk answer](https://codegolf.stackexchange.com/a/241062/100664). See that for a more detailed explanation of how this works. ``` ɖ # Scan by = # Equal to the current result? # For runs of 1s, this is 1, # For runs of 0s this alternates between 1 and 0 Tİ # Keep only items wihtt a 1 in the previous list ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes ``` ḅ{cẹ|ḍh}ᵐc ``` [Try it online!](https://tio.run/nexus/brachylog2#@/9wR2t18sNdO2se7ujNqH24dULy///RhjqGOgZACKdj/0cBAA "Brachylog – TIO Nexus") Not sure this is optimal yet… ### Explanation This exploits the bug that `c` on a list of integers that has leading zeroes will fail. ``` ḅ Blocks; group consecutive equal elements together { }ᵐ Map on each block: c It is possible to concatenate the block into an int (i.e. it contains 1s) ẹ Split it again into a list of 1s | Else ḍh Dichotomize and take the head c Concatenate the blocks into a single list ``` [Answer] # [Python](https://docs.python.org/2/) (list I/O), 36 bytes ``` f=lambda l:l and l[:1]+f(l[2-l[0]:]) ``` [Try it online!](https://tio.run/nexus/python2#@59mm5OYm5SSqJBjlaOQmJeikBNtZRirnaaRE22kmxNtEGsVq/k/Lb9IIUchMy/aUMcACKFkrA6QDxPBLgZnQcVBNEwdkIaJglUh9KDYgmIakkysFRdnQVFmXokC0K2a/wE "Python 2 – TIO Nexus") Recursively takes the first element, then removes the remaining one if the first one was zero. --- **38 bytes:** ``` lambda l:eval(`l`.replace('0, 0','0')) ``` [Try it online](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQY5ValpijkZCToFeUWpCTmJyqoW6go2CgrqNuoK6p@T8tv0ghRyEzL9pQxwAIoWSsDpAPE8EuBmdBxUE0TB2QhomCVSH0oNiCYhqSTKwVF2dBUWZeiUKaRo7mfwA "Python 2 – TIO Nexus") This takes a Python list and outputs a Python list by doing replacement on its string representation. String I/O would allow a more direct and shorter solution, such as ``` lambda s:s.replace('00','0') ``` for `'1001'` format. [Answer] # [///](https://esolangs.org/wiki////), 11 bytes ``` /00/a//a/0/<input goes here> ``` [Try it online!](https://tio.run/nexus/slashes#@69vYKCfqA9EBvr//wMA "/// – TIO Nexus") Fun fact: `/00/0/<input>` won't work, because it reduces `0000` to `0`. Hence the `a`-substitute. ]
[Question] [ Output the device's screen resolution in the **specific** format of `[width]x[height]`(without the brackets). For example, an output could be `1440x900`. [Here's an online tester that you can use to check your own screen resolution.](http://www.whatismyscreenresolution.com/) [Answer] # JavaScript (ES6), 32 bytes ``` (_=screen)=>_.width+"x"+_.height ``` Outputs as function `return`. Add `f=` at the beginning and invoke like `f()`. Uses parameter-initializing to initialize the parameter `_` to `screen` object. The rest is self-explanatory. ``` f=(_=screen)=>_.width+"x"+_.height console.log(f()) ``` **Note:** Passing an argument to this function will cause it to fail. --- # JavaScript (Previous Solution), 35 bytes ``` with(screen)alert(width+"x"+height) ``` Never thought I will one day use `with`! I don't think this can be golfed further. [Answer] # TI-BASIC, ~~30~~ ~~32~~ 29 bytes (non-competing?) \*sigh\* TI-BASIC takes an extra byte for every lowercase letter. +2 thanks to [@Timtech](https://codegolf.stackexchange.com/users/10740/timtech) -3 thanks to [@Timtech](https://codegolf.stackexchange.com/users/10740/timtech) ``` :If ΔX>.1 :Then :Disp "96x64 :Else :Disp "320x240 ``` This only works because TI-BASIC can only be run on calculators with two different screen resolutions: 96 by 64 and 320 by 240. I just test to see which screen I have by setting the Zoom to something that is different depending on screen resolution then outputting the correct resolution. I'm marking this as non-competing for now, since it is hard coded. [Answer] # JavaScript (ES6), 32 bytes ``` _=>(s=screen).width+'x'+s.height ``` ``` console.log((_=>(s=screen).width+'x'+s.height)()) ``` [Answer] # macOS, bash, awk, ~~grep, tr, 51~~ 52 bytes ``` /*/*/sy*r SPDisplaysDataType|awk '/so/{print$2$3$4}' ``` Runs `system_profiler`, gets the `SPDisplaysDataType` information, searches for the first `so` in `Resolution`, and prints the screen resolution. For multiple screens, this prints all resolutions. [![Example of the command running.](https://i.stack.imgur.com/egNTU.png)](https://i.stack.imgur.com/egNTU.png) --- The prior, malcompliant variant: ``` /*/*/sy*r SPDisplaysDataType|grep so|tr -d 'R :a-w' ``` [Answer] # Javascript, 36 bytes ``` s=screen;alert(s.width+"x"+s.height) ``` [Answer] # Processing 3, 37 bytes ``` fullScreen();print(width+"x"+height); ``` `fullScreen()` causes the app to launch with the maximum dimensions - the display resolution. One byte less than the obvious ``` print(displayWidth+"x"+displayHeight); ``` [Answer] # AutoHotKey, 34 bytes ``` SysGet,w,0 SysGet,h,1 Send,%w%x%h% ``` Save this in a file with extension .AHK and run it from a command prompt [Answer] # C (Windows), ~~79~~ ~~78~~ 77 bytes *Thanks to @Johan du Toit for saving a byte!* ``` #import<windows.h> #define G GetSystemMetrics f(){printf("%dx%d",G(0),G(1));} ``` [Answer] # PowerShell, ~~67~~ ~~60~~ 55 Bytes -7 thanks to [Martin Ender](https://chat.stackexchange.com/transcript/message/37106916#37106916) -5 (actually 12!) from [Leaky Nun](https://chat.stackexchange.com/transcript/message/37107030#37107030) , Regex wizardry is beyond me. This is long but not longer than the horrendous `System.Windows.Forms.SystemInformation.PrimaryMonitorSize` solution ``` (gwmi win32_videocontroller|% v*n)-replace" |x \d+\D+$" ``` first we `Get-WmiObject`(`gwmi`) to retrieve the `Win32_VideoController` object, which contains a member named `VideoModeDescription`, which is a string in the format of `1920 x 1080 x 4294967296 colors`, then I run a regex replace to get correct format. ``` PS H:\> (gwmi win32_videocontroller|% v*n)-replace" |x \d+\D+$" 1920x1080 ``` [Answer] ## Mathematica, 51 bytes ``` SystemInformation[][[1,5,2,1,2,1,2,2,;;,2]]~Infix~x ``` This may not work for you depending on what devices you have connected (I don't know). This should always work (assuming you have at least one screen hooked up): ``` Infix[Last/@("FullScreenArea"/.SystemInformation["Devices","ScreenInformation"][[1]]),x] ``` ## Explanation `SystemInformation[]` returns an expression of the form ``` SystemInformationData[{ "Kernel" -> {__}, "FrontEnd" -> {__}, "Links" -> {__}, "Parallel" -> {__}, "Devices" -> {__}, "Network" -> {__}, }] ``` We are interested in `"Devices"`, which can be accessed directly as `SystemInformation["Devices"]` or as `SystemInformation[][[1,5,2]]`. The result will be a list of the form ``` { "ScreenInformation" -> {__}, "GraphicsDevices" -> {__}, "ControllerDevices" -> {__} } ``` We want `"ScreenInformation"`, which can be accessed either as `SystemInformation["Devices","ScreenInformation"]` or more succinctly as `SystemInformation[][[1,5,2,1,2]]`. The result will be of the form ``` { { "ScreenArea" -> {__}, "FullScreenArea" -> {{0,w_},{0,h_}}, "BitDepth" -> _, "Resolution" -> _ }, ___ } ``` The length of the list will be the number of screens you have connected. The first screen is `SystemInformation[][[1,5,2,1,2,1]]` and the width and height can be extracted as `SystemInformation[][[1,5,2,1,2,1,2,2,;;,2]]` Then we just insert an `Infix` `x` for the output format. [Answer] # Java 7, ~~123~~ 114 bytes ``` String f(){java.awt.Dimension s=java.awt.Toolkit.getDefaultToolkit().getScreenSize();return s.width+"x"+s.height;} ``` This method will not work in a headless installation of Java (like on TIO) because it uses the awt libraries. Under the hood, calling `getScreenSize` uses the Java Native Interface to call out (typically into a C library) for the screen width and screen height. -9 bytes thanks to [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236/olivier-gr%C3%A9goire) for reminding me that I can return the string instead of printing it. [Answer] # C#, ~~101~~ ~~95~~ 89 bytes ``` _=>{var s=System.Windows.Forms.Screen.PrimaryScreen.Bounds;return s.Width+"x"+s.Height;}; ``` -6 bytes thanks to *@TheLethalCoder* by reminding me OP didn't mention about printing, so returning a string is also fine. And an additional -6 bytes by changing it to a lambda. [Answer] # Bash + xrandr, 44 characters ``` read -aa<<<`xrandr` echo ${a[7]}x${a[9]::-1} ``` `xrandr` belongs to the X server, on Ubuntu is provided by [*x11-xserver-utils*](http://packages.ubuntu.com/yakkety/amd64/x11-xserver-utils/filelist) package. Sample run: ``` bash-4.3$ read -aa<<<`xrandr`;echo ${a[7]}x${a[9]::-1} 1920x1080 ``` ## xrandr + grep + util-linux, 30 characters ``` xrandr|grep -oP '\d+x\d+'|line ``` Thanks to: * [Markasoftware](https://codegolf.stackexchange.com/users/10973/markasoftware) for the regular expression (-11 characters) Sample run: ``` bash-4.3$ xrandr|grep -oP '\d+x\d+'|line 1920x1080 ``` [Answer] # Python 2, 73 bytes ``` from ctypes import* u=windll.user32.GetSystemMetrics; print u(0),'x',u(1) ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 41 bytes *Thanks to [@Arjun](https://codegolf.stackexchange.com/users/45105/arjun) and [@StephenS](https://codegolf.stackexchange.com/users/65836/stephen-s) for corrections.* ``` fprintf('%ix%i',get(0,'ScreenSize')(3:4)) ``` `0` is a handle to the root graphics object. Its property `'ScreenSize'` contains the coordinates of the screen in pixels. The third and fourth entries give the desired information. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 23 bytes ``` ' '⎕R'x'⍕⌽⊃⎕WG'DevCaps' ``` `⎕WG'DevCaps'` **W**indow **G**et **Dev**ice **Cap**abilitie**s** `⊃` pick the first property (height, width) `⌽` reverse `⍕` format as text `' '⎕R'x'` **R**eplace spaces with "x"s [Answer] ## [Japt](https://github.com/ETHproductions/japt), 24 bytes ``` Ox`ØP(s×Çn)±d+"x"+ight ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=T3hg2FAoc9fHbimxZJArIngiK5RpZ2h0&input=) The compressed string represents `with(screen)width+"x"+height`. `Ox` evaluates this as JavaScript, and the result is implicitly printed. [Answer] # C (SDL2 library) ~~113~~ ~~88~~ 84 (-4 chars due to @AppleShell 's help) Yes. it compiles. ``` m[3];main(){SDL_Init(32);SDL_GetDesktopDisplayMode(0,m);printf("%dx%d",m[1],m[2]);} ``` Run with : `gcc snippet.c -lSDL2 && ./a.out` [Answer] [`xrandr`](https://www.x.org/archive/X11R7.5/doc/man/man1/xrandr.1.html) + awk, 25 bytes ``` xrandr|awk /\*/{print\$1} ``` --- [![enter image description here](https://i.stack.imgur.com/Zplu4.gif)](https://i.stack.imgur.com/Zplu4.gif) [Answer] # Python 2, ~~61~~ 49 bytes Thanks @Jonathan-allan, @felipe-nardi-batista ``` from Tkinter import* print'%sx%s'%Tk().maxsize() ``` For single display setups, this matches the output from the site. This gives entire resolution for multiple displays. [Answer] # ZX Spectrum Basic, 10 bytes just for completeness: ``` PRINT "256x192" ``` outputs `256x192`. The Spectrum has a fixed hardwired screen resolution. [Answer] ## bash + xdpyinfo ~~42~~ 31 bytes ``` xdpyinfo|grep dim|cut -d' ' -f7 ``` From man page: ``` xdpyinfo - is a utility for displaying information about an X server. ``` @Floris @manatwork Thanks for saving a few bytes! [Answer] # Processing, 51 bytes ``` void setup(){fullScreen();print(width+"x"+height);} ``` This outputs in this format: `width height`. Also, the program creates a window that is the size of the screen you are using (because every Processing program creates a window by default) and this program just outputs the height and the width of this window/sketch. [Answer] ### `xdpyinfo` + `awk`, 28 bytes ``` $ xdpyinfo|awk /dim/{print\$2} 3360x1050 ``` Tested on Cygwin with dual heads. [Answer] # Racket, 73 bytes ``` #!racket/gui (let-values([(x y)(get-display-size #t)])(printf"~ax~a"x y)) ``` Just discovered the [(discouraged) shorthand for `#lang`](https://docs.racket-lang.org/reference/reader.html#%28part._parse-reader%29). Saves a few bytes! [Documentation for `get-display-size`](https://docs.racket-lang.org/gui/Windowing_Functions.html?q=gui#%28def._%28%28lib._mred%2Fmain..rkt%29._get-display-size%29%29). [Answer] # Tcl/Tk, 40 ``` puts [winfo screenw .]x[winfo screenh .] ``` [Answer] ## [Lithp](https://github.com/andrakis/node-lithp), 116 bytes ``` ((import html-toolkit) (htmlOnLoad #::((var S(index(getWindow)screen)) (print(+(index S width)"x"(index S height)))))) ``` (Line breaks added for readability) [Try it online!](https://andrakis.github.io/ide2/index.html?code=KChpbXBvcnQgaHRtbC10b29sa2l0KShodG1sT25Mb2FkICM6OigodmFyIFMoaW5kZXgoZ2V0V2luZG93KXNjcmVlbikpKHByaW50KCsoaW5kZXggUyB3aWR0aCkieCIoaW5kZXggUyBoZWlnaHQpKSkpKSk=) Finally, my html-toolkit module gets some use! Only works in the Try it Online link, will not work from command line. A few bytes could be saved if `1024 x 768` could be valid output. We just use `(+ .. "x" .. )` to avoid `print`'s implicit spacing. [Answer] # Lua (löve framework),116 bytes ``` f,g=love.window.setFullscreen,love.graphics function love.draw()f(1)w,h=g.getDimensions()f(0>1)g.print(w.."x"..h)end ``` The programm changes first to fullscreen then it gets the width and height and prints it then :) [Answer] ### xrandr and sh, 23 bytes ``` $ set `xrandr`;echo $6x$8 3360x1050 ``` Tested on a CentOS 5 box with display redirected to a Cygwin machine with two monitors. Here the full `xrandr` output is ``` $ xrandr SZ: Pixels Physical Refresh *0 3360 x 1050 ( 889mm x 278mm ) *0 Current rotation - normal Current reflection - none Rotations possible - normal Reflections possible - none ``` [Answer] ## Ruby + xrandr, 37 bytes ``` puts `xrandr`.split[7..9].join[0..-2] ``` Alternate solution (52 bytes): ``` puts `xrandr`.match(/t (\d+) (x) (\d+),/)[1..3].join ``` ]
[Question] [ I have a number like this: ``` n = 548915381 ``` The output should be the sum of every second digit of that number. In this case 26: ``` 4+9+5+8 = 26 ``` Rules: * This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. * The input consists only of numbers bigger than 10 (at least 2 digits) but smaller than a 32-bit integer. * The input will be a number, not a string Test cases: | Input | Output | | --- | --- | | 10 | 0 | | 101011 | 1 | | 548915381 | 26 | | 999999 | 27 | | 2147483647 | 29 | | 999999999 | 36 | [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes ``` y∑ ``` well. [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ54oiRIiwiIiwiNTQ4OTE1MzgxIl0=) | [1 byte with `s`](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwieSIsIiIsIjU0ODkxNTM4MSJd) **Explanation** ``` y∑ y Uninterleave, push two lists with every second and every second+1 digit ∑ Sum the first list ``` [Answer] ## Python 3, 28 37 32 30 35 bytes ``` lambda n:sum(map(int,str(n)[1::2])) ``` Assuming input is a string number [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 15 bytes ``` {sum m:g/.<(./} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/urg0VyHXKl1fz0ZDT7/2f3FipUKahrZetEGspoKtnYJetGGsQlp@kUJOZl5qsZ2dXnl@UUrxf0MDTk4DLkMDIDTk5DTksgQDTk4jcy4jQxNzEwtjMxNzTiNLqARIztgMAA "Raku – Try It Online") Simple regex based sum of every other digit [Answer] # JavaScript (ES6), 30 bytes *-1 by [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* ``` f=n=>n&&f(i=n/10|0)+i++%2*n%10 ``` [Try it online!](https://tio.run/##hYzRCsIgGEbve4rdbGhS@qtTd2HvMtYMY@ho0VXvbjYagQR93@U5nGv/6Jfh5uf7IcTzmJKzwZ5C0zjkbaDAngwTT0jN96EGloYYljiNxylekEMAGFfbKK3YruDsH8/fGplDwVtpOmiFWZXMuSqEbt03wHUhcJBaGqGkztJb6H4WPpEsCJVe "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 31 bytes ``` f=n=>n?f(n/10|0)+i++%2*n%10:i=0 ``` [Try it online!](https://tio.run/##bczfCsIgFMfx@55iNwNNSo86/wTWs4w1wxgaLbrq3c3GIpDOufx@@F37Zz8P93B77GI6jzl7F90xnjyKFNiLYRIIafk2tsAOwbE8pDinadxP6YI8AoZx8z1KG7ape3lYTelQ9U4aC50wCymdqwrY5X4DXFeAg9TSCCV1QR9g/y6sIwUIld8 "JavaScript (Node.js) – Try It Online") ### Commented ``` f = n => // f is a recursive function taking the input n n ? // if n is not equal to 0: f(n / 10 | 0) + // do a recursive call with floor(n / 10) // it's important to understand that: // 1) n is defined in the local scope of f // 2) i is defined in the global scope // 3) we're not going to execute the code that // follows until the recursion stops and i // has been initialized i++ % 2 * // take the parity of i (increment it afterwards) n % 10 // and multiply by the least significant decimal // digit of n : // else: i = 0 // stop the recursion and initialize i to 0 ``` [Answer] # [R](https://www.r-project.org), ~~40~~ ~~38~~ 36 bytes *Edit: -2 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).* ``` \(x)sum(x%/%10^(nchar(x):0)%%10*1:0) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3VWI0KjSLS3M1KlT1VQ0N4jTykjMSi4BiVgaaqkABLUMgA6o2PE3D0EBTmdOAC8QAQkMgxxDIMTWxsDQ0NbYA8Y3MgAKWYADimQN5RoYm5iYWxmYm5iARS7g8RImxGcT4BQsgNAA) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-hx`](https://codegolf.meta.stackexchange.com/a/14339/), 3 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ì ó ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWh4&code=7CDz&input=NTQ4OTE1Mzgx) ``` ì ó :Implicit input of integer ì :Convert to digit array ó :Uninterleave :Implicit output of sum of last element ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 14 bytes ``` 0i~i:c%@0(?n+! ``` [Try it online!](https://tio.run/##S8sszvj/3yCzLtMqWdXBQMM@T1vx/38jQxNzEwtjMxNzAA "><> – Try It Online") **Explanation** ``` 0 # init sum as 0 i~ # discard an input i: # duplicate an input c%@ # mod the copy by 12 and move down on stack 0(?n # if the other copy was negative, print the sum +! # else add copy to sum and skip the next instruction ``` [Answer] # [Zsh](https://www.zsh.org/), 33 bytes ``` for _ c (`fold -1`)let t+=c;<<<$t ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY3FdPyixTiFZIVNBLS8nNSFHQNEzRzUksUSrRtk61tbGxUSiAKoeoXrDIyNDE3sTA2MzGHiAAA) -3 bytes thanks to roblogic Inputs as a string, because there is no way to input as a number in Zsh. [Answer] # [Pip](https://github.com/dloscutoff/pip), 10 7 bytes ``` $+@SUWa ``` First pip answer, so don't sue me plz. [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCIkK0BTVVdhIiwiIiwiNTQ4OTE1MzgxIiwiIl0=) **Explanation** ``` $+@SUWa @SUWa Uninterweave a, take the second item of the two "every second element" lists $+ Sum the string ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~39~~ 32 bytes -7 (pxeger suggested lambda) ``` lambda n:sum(map(int,`n`[1::2])) ``` [TIO](https://tio.run/##K6gsycjPM/qfaBvzPycxNyklUSHPqrg0VyM3sUAjM69EJyEvIdrQysooVlPzf0ERUEQhUcPQQJMLwQZCQwTf1MTC0tDU2AJJyBIMEHwjQxNzEwtjMxNzdDUgZf8B) EDIT: new test cases [Answer] # [Excel](https://www.microsoft.com/en-us/microsoft-365/excel), ~~39~~ 32 bytes * -7 bytes thanks to [Engineer Toast](https://codegolf.stackexchange.com/users/38183/engineer-toast)! ``` =SUM(--(0&MID(A1,2*ROW(A:A),1))) ``` [![enter image description here](https://i.stack.imgur.com/CNTII.png)](https://i.stack.imgur.com/CNTII.png) [Answer] # [Perl](https://www.perl.org/) `-p`, 18 bytes ``` s/.(.)/$\+=$1/ge}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/79YX09DT1NfJUbbVsVQPz21tvr/fyNDE3MTC2MzE/N/@QUlmfl5xf91CwA "Perl 5 – Try It Online") Input via STDIN. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~40~~ ~~32~~ 31 bytes -8 bytes thanks to [G B](https://codegolf.stackexchange.com/users/18535/g-b) -1 byte thanks to [Armand Fardeau](https://codegolf.stackexchange.com/users/94303/armand-fardeau) ``` ->n{eval"#{n}".scan(/.(.)/)*?+} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhb7de3yqlPLEnOUlKvzapX0ipMT8zT09TT0NPU1tey1ayGq1hUouEWbmlhYGpoaWxjGQgQXLIDQAA) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 9 bytes ``` tssM%2+1z ``` [Try it online!](https://tio.run/##K6gsyfj/v6S42FfVSNuw6v9/I0MTcxMLYzMTcwA "Pyth – Try It Online") ``` +1z # Append '1' before the input %2 # Every 2nd element of ssM # Map to integer and take sum t # Decrease by 1 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` D0ÐoS ``` [Try it online!](https://tio.run/##y0rNyan8/9/F4PCE/OD/h9s1I///NzTQUTA0AEJDHQVTEwtLQ1NjCyDTEgx0FIwMTcxNLIzNTMxhYkAAAA "Jelly – Try It Online") Also 5 bytes ``` DŻm2S ``` [Try it online!](https://tio.run/##y0rNyan8/9/l6O5co@D/h9s1I///NzTQUTA0AEJDHQVTEwtLQ1NjCyDTEgx0FIwMTcxNLIzNTMxhYkAAAA "Jelly – Try It Online") Also also 5 bytes ``` Ds2SṪ ``` [Try it online!](https://tio.run/##y0rNyan8/9@l2Cj44c5V/w@3a0b@/29ooKNgaACEhjoKpiYWloamxhZApiUY6CgYGZqYm1gYm5mYw8SAAAA "Jelly – Try It Online") ### How they work ``` D0ÐoS - Main link. Takes an integer on the left D - Digits Ðo - To digits in odd positions: 0 - Set them to 0 S - Sum ``` ``` DŻm2S - Main link. Takes an integer on the left D - Digits Ż - Prepend a zero m2 - Take every second element S - Sum ``` ``` Ds2SṪ - Main link. Takes an integer on the left D - Digits s2 - Slice into pairs S - Sums Ṫ - Tail ``` [Answer] # [Julia 1.0](http://julialang.org/), 30 bytes ``` !n=sum(i->i-'0',"$n"[2:2:end]) ``` [Try it online!](https://tio.run/##PY1NCoMwFITX5hTPUDCCFuO/Qtx10TOULmJN4RWbilFw4d1t0NKZzcx8i3nNPUq@bJurhZnfDMMGQy/yAnrS9BbXca10d/e352cEBNQwKtn1qJVhPgErGbQgYJCjUWd21VNghh4nhv6BhxH11GsmRePKY3IlCAEtrOuf0ssyqMekOqBB6xN7ufEInIjwyJqDw0mWlhXPktKWOCfVLhsLEvO0SMskTwtbqx/ZYZJ/AQ "Julia 1.0 – Try It Online") [Answer] # [Factor](https://factorcode.org/) + `math.unicode`, 25 bytes ``` [ >dec <odds> 48 v-n Σ ] ``` [Try it online!](https://tio.run/##TY9LTsMwEIb3PsVkT5xn8wJF6gYUCXVTsUIoCo6TVGrsYE8KCHEa7sOVQuq0pf9sRt/882oqhlJNT9ti85CB5m8jF4zr/4zyD1SVhr7Cjg6V0lwt@YEfO0@FUeyYrDkMiiN@DmonEG6h2GTQyn1D1o/FeptBXnMGYuxfuco1zqYWwIJ7cwK4NE3BtufNHDrEQWeOU0umaWPqx/FUqtZhUiAX6LxLVdtl2WJZzmNvru6jHfZ7Qr4IzPJcuMgC98Tm8M7MM2wVJqm3ChLPMD8yMDU6G/3YQN8L4zAJojA2ML1yLmYLgoh8k@l5efhO1rXOIUzgYAv4/YGXqa8GoNMf "Factor – Try It Online") ``` ! 548915381 >dec ! "548915381" <odds> ! "4958" 48 ! "4958" 48 v-n ! { 4 9 5 8 } Σ ! 26 ``` [Answer] # [flax](https://github.com/pygamer0/flax), 2 bytes ``` ΣẎ ``` [Try It Online!](https://dso.surge.sh/#@WyJmbGF4IiwiIiwizqPhuo4iLCLPgiciLCIiLCJbWzEwLDEwMTAxMSw1NDg5MTUzODEsOTk5OTk5LDIxNDc0ODM2NDcsOTk5OTk5OTk5XV0iXQ==) [Answer] # [J](https://www.jsoftware.com), 15 bytes All credit goes to [Raul](https://codegolf.stackexchange.com/users/72244/rdm). ``` [:+/_2}.\,.&.": ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxPtpKWz_eqFYvRkdPTU_JCiJ6016TKzU5I19BI826LlZTzU7B0ACIgNBQwdTEwtLQ1NjCUMESDBSMDE3MTSyMzUzMoSJAADFmwQIIDQA) ``` [:+/_2}.\,.&.": ,.&.": NB. equivalent to ". ,. ": y, convert to digit list _2}.\ NB. behead each non-overlapping window of size 2 [:+/ NB. sum the resulting column ``` # My original 19 bytes from 11 bytes ``` 1(#.]*0 1$~#),.&.": ``` Updated to reflect challenge requirements. Thanks to Jonah for the modifications. [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmux2VBDWS9Wy0DBUKVOWVNHT01PyQoic9Nekys1OSNfQSPNui5WU81OwRCoygAIDRVMTSwsDU2NLQwVLMFAwcjQxNzEwtjMxBwqAgQQYxYsgNAA) ``` 1(#.]*0 1$~#),.&.": ,.&.": NB. same as above 1( ) NB. dyadic hook # NB. use length of right arg to 0 1$~ NB. reshape 0 1, reuses elements to create alternating 1's ]* NB. multiply by the right arg #. NB. 1 #. y sums the result ``` [Answer] # [Dart (2.18.4)](https://dart.dev/), ~~92~~ 77 bytes ``` f(n,[i=1])=>[for(;i<(n='$n').length;i+=2)int.parse(n[i])].reduce((v,e)=>v+e); ``` * [Try it online](https://tio.run/##bYtBDoIwFET3noKFCf8HQiwUgdR6kaaLRoo00S@pyMZ49kqMmxpnVvPypjd@DmEAypWTTKM8quHmQbgDkEy3lGJxsXSeR@EyWaKjuZiMv1sg5TTqwtv@cbIAS27X75JZFOFqHAEmz02STH59wABshyiivZbFrOZtx@qq/cHdJzErGW94W@1588/96q/wBg). * [Full source](https://github.com/alexrintt/algorithms/tree/master/codegolf/sum-every-second-digit-in-a-number/dart-2.18). [Answer] # [Python 3](https://docs.python.org/3/), 35 bytes ``` lambda n:sum(map(int,f'{n}'[1::2])) ``` [Try it online!](https://tio.run/##K6gsycjPM/6faBvzPycxNyklUSHPqrg0VyM3sUAjM69EJ029Oq9WPdrQysooVlPzf0ERUFAjUcPUxMLS0NTYwhAoBgA "Python 3 – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 12 bytes ``` .(.?) $1$* . ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX09Dz16TS8VQRYtL7/9/QwMuQwMgNOQyNbGwNDQ1tjDksgQDLiNDE3MTC2MzE3OoCBAAAA "Retina 0.8.2 – Try It Online") Link includes test cases. Takes input as a string because Retina has no integer types. Explanation: ``` .(.?) $1$* ``` Convert alternate digits to unary, dropping the other digits. ``` . ``` Take the sum and convert back to decimal. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 7 bytes ``` IΣΦS﹪κ² ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0V8MtM6cktUjDM6@gtCS4BCiXrqGpo@Cbn1Kak6@RraNgpAkC1v//m5pYWBqaGlsY/tctywEA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` S Cast the input to string Φ Filter characters where κ Current index ﹪ ² Is odd Σ Take the sum I Cast to string Implicitly print ``` [Answer] # [pl](https://perl1liner.sourceforge.io) – Perl One-Liner Magic Wand, 12 bytes Use **-o** to loop over command line arguments. Global matching regexp returns every other character, in this case digit. By default List::Util::sum is imported, `e(cho)` its result. On the [blog](https://perl1liner.sourceforge.io/Challenge-and-Golf/#o-e-sum..g-10-101011-548915381-999999), hover the ▶ button, or the blue code box, to see the result: ``` pl -o 'e sum/.(.)/g' 10 101011 548915381 999999 2147483647 999999999 ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 18 bytes ``` 1⊑·+˝⌊‿2⥊'0'-˜•Fmt ``` Anonymous tacit function that takes a number and returns a number. [Try it at BQN online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgMeKKkcK3K8ud4oyK4oC/MuKliicwJy3LnOKAokZtdAoKRiA1NDg5MTUzODE=) ### Explanation ``` 1⊑·+˝⌊‿2⥊'0'-˜•Fmt •Fmt Format as string '0'-˜ Subtract '0' character from each, giving a list of digits as numbers ⌊‿2⥊ Reshape into an array with two columns, dropping the last digit if there is an odd number of digits ·+˝ Sum down each column 1⊑ Take the element at index 1 (0-indexed) in the resulting list ``` [Answer] # [sclin](https://github.com/molarmanful/sclin), 13 bytes ``` 2/`1.: map +/ ``` [Try it here!](https://replit.com/@molarmanful/try-sclin) For testing purposes: ``` "548915381" ; n>o 2/`1.: map +/ ``` ## Explanation Prettified code: ``` 2/` 1.: map +/ ``` * `2/`` chunk into pairs * `1.: map` get second element of each pair * `+/` sum [Answer] # [Fig](https://github.com/Seggan/Fig), \$3\log\_{256}(96)\approx\$ 2.469 bytes ``` S]y ``` [Try it online!](https://fig.fly.dev/#WyJTXXkiLCJbNSw0LDgsOSwxLDUsMyw4LDFdIl0=) Port of Vyxal. ``` S]y # Uninterleave ] # Get last S # Sum ``` # [Fig](https://github.com/Seggan/Fig), \$6\log\_{256}(96)\approx\$ 4.939 bytes ``` S-n2'0 ``` [Try it online!](https://fig.fly.dev/#WyJTLW4yJzAiLCJbNSw0LDgsOSwxLDUsMyw4LDFdIl0=) My original answer before seeing Vyxal. ``` S-n2'0 # Input as a digit list n # For every 2 # Second item ' # Replace 0 # With a 0 - # Subtract this from the original list S # Sum ``` [Answer] # [Kotlin](https://kotlinlang.org), 51 bytes ``` {it.map{it.code-48}.foldIndexed(0){i,a,c->i%2*c+a}} ``` No TIO link as it doesn't have an updated version, ATO borks with it for some reason. ``` {it.map{it.code-48}.foldIndexed(0){i,a,c->i%2*c+a}} // String input { } // Lambda expression it.map{it.code-48} // Subtract 48 from each char, turning the string into a list of digits .foldIndexed(0){i,a,c-> } // Fold over the list, starting with 0. i is the index, a is accumulator, and c is the digit i%2*c // Multiply the current digit by the index mod 2. If it is even, it resolves to 1*c, otherwise 0*c +a // Add to accumulator ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 13 bytes ``` +/(2!!#:)#10\ ``` [Try it online!](https://ngn.codeberg.page/k#eJxFj01ugzAQhdedUxCli0SV4x/AgH2CrnqANFKIMQQl2Ck2Fahqz14TpGRmMfPpvcV7tXjDG7ZarcV2TckngBc/r/vprxd1FEWjPNqL3Bzrsr3KUU6y3x5+g2dPiSSH+w1LJZ3/NMkLmsY5lYzPXNxHsmwGRpMsyWOeZJIVT3U2xMENgOHs/c0JjJWtdGOv9c75Ul30qM6lafRO2Q5/Ddr51hqHWZrylGA3dEh/635CTitrKlS1TetRa1CJzNCddA/wbm6Dj15Cnehj8OEHShYksORfiMKjQSDGYcm3iCyDZ4WABTwKBDXm/3A5VUY=) * `10\` convert (implicit) input integer to a list of its digits * `(2!!#:)#` only keep elements at odd indices (0-indexed) * `+/` calculate (and implicitly return) the sum [Answer] # Julia, 28 bytes ``` f(n)=sum(digits(n)[2:2:end]) ``` ]
[Question] [ I've been posting relatively hard challenges recently, so here goes an easy one. ## Task Given an array \$A\$ and a number \$n\$, calculate the sum of all numbers of \$A\$ multiplied by \$n\$, except the last one. All numbers (the elements of \$A\$ and the value of \$n\$) are positive integers, and \$A\$ is non-empty. Shortest code in bytes wins. I have a 3-byte J solution. Can you find it (or beat it in a different language)? ## Test cases ``` A N Ans Explanation 3 1 4 1 5 10 95 (3+1+4+1)*10+5 3 1 4 1 5 1 14 (3+1+4+1)*1+5 1 999 1 1 ``` [Answer] # [J](http://jsoftware.com/), 3 bytes That was fun to find. ``` &+/ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1bT1/2v@VzA0UEhTMFYwVDABYlMuBSCJzLe0tATyDQE "J – Try It Online") ### How it works `10 (&+/) 3 1 4 1 5` will bind `10` as an argument of `+` as `10&+`, one verb that gets inserted between the elements of the list by `/`. So we have: `3 (10&+) 1 (10&+) 4 (10&+) 1 (10&+) 5`. Now `x n&v y` means that `y` gets applied to `n&v` for `x` times. With J's right to left evaluation we get: to 5 add 1 times 10, add 4 times 10, add 1 times 10, add 3 times 10. A challenge made for J's stranger parts. :-) And because `+` is commutative, `+&/` would also be a valid solution. [Answer] # JavaScript (ES6), ~~ 28 ~~ 23 bytes *Saved 3 bytes thanks to @Mukundan314* Expects `(A)(n)`. ``` A=>n=>eval(A.join`*n+`) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@9/R1i7P1i61LDFHw1EvKz8zL0ErTztB839yfl5xfk6qXk5@ukaaRrSxjqGOCRCbxmpqGBpoanLhk8eUNgQKW1paamr@BwA "JavaScript (Node.js) – Try It Online") ### How? We simply join the input array with `"*n+"`, so that `[1,2,3]` is turned into `"1*n+2*n+3"` and evaluate the resulting string. [Answer] # [Haskell](https://www.haskell.org/), 17 bytes ``` foldr1.((+).).(*) ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPy0/J6XIUE9DQ1tTT1NPQ0vzv4aqpm1aTmaBQhpXbmJmnoKtQkFRZl6JgopCdLSxjoKhjoIJmDSNVVBVMDTQUcAiChQ0BDEsLS1j//9LTstJTC/@r5tcUAAA "Haskell – Try It Online") It turns out this this was close to a port of the [intended J solution](https://codegolf.stackexchange.com/a/206979/20260). The pointfree function `((+).).(*)` takes the argument `n` to the map `\a b->a*n+b`, that is, to add `n` times the left value to the right value. This creates the same "verb" as J used, and the `foldr1` does the same a J's automatic right to left evaluation. It starts with the rightmost value in the list, which never gets multiplied by `n`, and applies it right-to-left, effectively increasing the sum so far with `n` times to the new element. [Answer] # [Python 3](https://docs.python.org/3/), 27 bytes ``` lambda a,n:a.pop()+sum(a)*n ``` Port of my Japt solution to python [Try it online!](https://tio.run/##TY2xDoMwDET3fIW3xm2EGgFDkPiStoMrimoJTETSga9Pk8JQSx7u7vnst/hepE4j9HBPE83PgYCMdFT5xWu8hM@sCc@SePbLGiFsQalxWWFieQFLMaoQB5ZOQR4yIAZIQi4sSBX8xFGj2tPs3liiJkYoLcSlgw7qZE74@IGSwcLJcejXokZd6hH6PcxfEFNtrGnytmCv4Fr1p8E2yoJzDuwX "Python 3 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 19 bytes ``` #2Tr@Most@#+Last@#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X9kopMjBN7@4xEFZ2ycRRKn9DyjKzCtRcEiPrjbWMdQxAWLTWh1Dg1gu7BLI4oa1OpaWlrH//wMA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 27 bytes ``` lambda a,n:a.pop()+sum(a)*n ``` [Try it online!](https://tio.run/##dY5NDoIwEIX3PcXs2tFqrEBMSfAiwKIqRBIpTVsWhnD2WurClbOYv@/l5Zm3f046C33VhJcabw8FiutSHc1kGO7dPDKFOx1857yDChiBWIzVGQfBIU@9aOM4IQdZIP8riFzkPy7iT0qJiRAkdnOfaTOfL/mdcviuIqNI@smC5x0MGlKOMnlscXq285guYwftWU8Xv8LhCotbYbF11FTQtSvF8AE "Python 3 – Try It Online") [Answer] ## [Clojure](https://clojuredocs.org/) 41 bytes `#(+(last %1)(* %2(apply +(butlast %1))))` Unfortunately, `+` does have to be `apply`ed. [Try It Online](https://tio.run/##S87JzyotSv2vkZKappD2X1lDWyMnsbhEQdVQU0NLQdVII7GgIKdSQVsjqbQEJgEE/zW5uDQKijLzSnLyFDTSFKKNFQwVTIDYNFbB0EBTE7ckupxhrIKlpSXQRAA) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes -2 bytes thanks to @KevinCruijssen. ``` *`²÷O ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fK@HQpsPb/f//jzbWMdQxAWLTWC5DAwA "05AB1E – Try It Online") ## Explanation ``` * Multiply list by second operand ` Dump ÷ Divide the last item by ² the second operand O Sum the stack ``` # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` „²*ý.VO ``` [Try it online!](https://tio.run/##yy9OTMpM/f//UcO8Q5u0Du/VC/P//z/aWMdQxwSITWO5DA0A "05AB1E – Try It Online") ## Explanation ``` „ 2-char string ²* (Which does when evaluated) Multiply by the second input ý Join the input list by this .V Evaluate O Sum the resulting stack ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 9 [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 infix function. Takes \$A\$ as left argument and \$n\$ as right argument. ``` ⊢/+.×+×∘~ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HXIn1tvcPTtQ9Pf9Qxo@5/2qO2CY96@x51NT/qXfOod8uh9caP2iY@6psaHOQMJEM8PIP/GysYKpgAsalCmoKhARcKl8sQSFpaWgIA "APL (Dyalog Extended) – Try It Online") `×∘~` \$A×(1-n)\$ `+.×+` \$\big(\sum\_{i=1}^N A\_i×n\big)+\$ `⊢/` rightmost element (lit. right-argument reduction) So this effectively implements: $$ \Bigg(\bigg(\sum\_{i=1}^N A\_i×n\bigg)+A×(1-n)\Bigg)\_N\\ \bigg(\sum\_{i=1}^N A\_i×n\bigg)+A\_N×(1-n)\\ \bigg(\sum\_{i=1}^N A\_i×n\bigg)+A\_N-n×A\_N\\ \bigg(\sum\_{i=1}^{N-1} A\_i×n\bigg)+A\_N $$ [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 5 [bytes](https://github.com/abrudz/SBCS) ``` +⍣⎕/⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b/2o97Fj/qm6gMxSOA/ZxqXsYKhggkQm3IZGnCh8kFcQy5LS0sA "APL (Dyalog Unicode) – Try It Online") A full program, which pretty much works like the [3-byte J solution](https://codegolf.stackexchange.com/a/206979/78410). Takes two lines of input, \$A\$ first and \$n\$ second. ### How it works ``` +⍣⎕/⎕ ⎕ ⍝ Take the input A / ⍝ Reduce by... + ⍝ Add the left argument ⍣⎕ ⍝ n times For n=10 and A = 3 1 4 1 5, this becomes: +⍣10/3 1 4 1 5 3 (+⍣10) 1 (+⍣10) 4 (+⍣10) 1 (+⍣10) 5 3 added 10 times to 1 added 10 times to 4 added 10 times to 1 added 10 times to 5 ``` --- # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 8 bytes ``` 1¨⍛,⊥0,⊣ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/3/DQike9s3UedS01ABKL/6c9apvwqLfvUVfzo941j3q3HFpv/Kht4qO@qcFBzkAyxMMz@L@xgqGCCRCbKqQpGBpwoXC5DIGkpaUlAA "APL (Dyalog Extended) – Try It Online") A longer but more interesting one. A tacit dyadic function that takes \$A\$ on its left and \$n\$ on the right. Uses mixed base conversion `⊥`, which does the following: ``` Base: 1 1 1 ... 1 n Digit value: n n n ... n 1 Array value: 0 a1 a2 ... ax-1 ax Total: a1n + a2n + ... + ax-1n + ax ``` ### How the code works ``` 1¨⍛,⊥0,⊣ ⍝ Input: left=A, right=n 1¨ ⍝ An array of ones as long as A ⍛, ⍝ Append n, which becomes the base 0,⊣ ⍝ A prepended with single zero, which becomes the values ⊥ ⍝ Mixed base conversion as described above ``` [Answer] # [R](https://www.r-project.org/), ~~37~~ ~~36~~ 35 bytes -2 bytes with help from Giuseppe ``` function(l,n)rev(l)%*%n^(seq(!l)>1) ``` [Try it online!](https://tio.run/##K/qfpmCjq/A/rTQvuSQzP08jRydPsyi1TCNHU1VLNS9Oozi1UEMxR9POUPN/mkayhrGOoY4JEJtq6igYGmhyYYiBhAx1FCwtLUEsIzjLAML6DwA "R – Try It Online") Reverse the vector, and perform dot product with the vector \$(n^0, n^1, n^1, \ldots,n^1) = (1, n, n,\ldots, n)\$. I just discovered this behaviour of `seq`, which gains 1 byte on item 4 of [this tip](https://codegolf.stackexchange.com/a/138046/86301): `seq(!l)` is equivalent to `seq(along.with = l)` (giving the vector `1 2 3 ... length(l)`) in all situations, even if `l` is of length 1. That is because `!l` is a logical, not an integer, and so we avoid the call to `seq.int` when `l` is a (length 1) integer. [Answer] # [Pyramid Scheme](https://github.com/ConorOBrien-Foxx/Pyramid-Scheme), 407 bytes ``` ^ ^ /l\ /+\ /oop\ ^---^ ^-----^ - /x\ / \ / \ --- /arg\ /set\ -----^-----^ /2\ /+\ --- ^---^ ^- /1\ ^- --- ^- /]\ ^---^ / \ /2\ /set\--- ^-----^ /x\ ^- --- /]\ ^---^ ^- /#\ / \ ---^ /set\ / \ ^-----^ /arg\ - /+\-----^ ^---^ /2\ /*\ - --- ^---^ ^- /#\ /x\ ^--- ---/ \ /arg\ ^----- /1\ --- ``` [Try it online!](https://tio.run/##VZDLDoJADEX3/Yom7jSTER9/M5IQJWoigYAL/fra284AktAHbU9vGb5j0z1vYbo@2q4VYTw1uyPY@Ermdglp7PtB8zqEgDK8Rhy08tGGyGh2qwWKzXhPHKf2nchb3Tr5kBYw2hduFgBslWiVGrWkHsSLd8yzWK9sDW2xTZS9qtJJZPv@ZpnKzo0N4wpnGsfJVE620yjkf7M6y1mcJXDcAjMrzyrLGujBJ8gBnTM3Cyacr15Eqr0cpZKTvucf "Pyramid Scheme – Try It Online") Takes input through command arguments, with `n` as the first argument. This basically implements the algorithm: ``` i = 2 x = 0 o = 0 while args[i]: o += x*args[1] x = args[i] i += 1 print(o + x) ``` But with more nesting and some shortcuts, like using the variable `2`. [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~14~~ 13 bytes **Solution:** ``` {*|x+/y*-1_x} ``` [Try it online!](https://tio.run/##y9bNz/6fZlWtVVOhrV@ppWsYX1H7P01PXUPDWMFQwQSITa0NDTStkblAno6htaWlpabm//8A "K (oK) – Try It Online") **Explanation:** Couldn't figure out a smart way of solving this. ``` {*|x+/y*-1_x} / the solution { } / lambda taking implicity x, y -1_x / drop (_) 1 element from end of x y* / multiply by y x+/ / sum up with x as accumulator *| / take last (reverse, first) ``` **Notes:** * **-1 byte** thanks to coltim - thanks! [Answer] # [Perl 5](https://www.perl.org/) + `-pa -MList::Util+sum`, 19 bytes ``` $_=pop(@F)+<>*sum@F ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3rYgv0DDwU1T28ZOq7g018Ht/39jBUMFEyA25TI04ELiAKGlpeW//IKSzPy84v@6BYk5/3V9fTKLS6ysQksyc7SB@gE "Perl 5 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 7 bytes ``` o +V*Ux ``` [Try it online!](https://tio.run/##y0osKPn/P19BO0wrtOL//2hjHQVDHQUTMGkay2VoAAA "Japt – Try It Online") ## Explanation ``` o +V*Ux o // Pop and return last element of first input + // plus V* // second input times Ux // Sum of first input ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 31 bytes ``` \d+ $* 1(?=.*,1*;(1*)|1*$) $1 1 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyZFm0tFi8tQw95WT0vHUMtaw1BLs8ZQS0WTS8WQy/D/f2MdQx0TIDa1NjTgQuJwGVpbWloCAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` \d+ $* ``` Convert to unary. ``` 1(?=.*,1*;(1*)|1*$) $1 ``` Multiply all but the last element of `A` by `n` and delete `A`. ``` 1 ``` Take the sum and convert to decimal. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 7 bytes ``` +*sPQEe ``` [Try it online!](https://tio.run/##K6gsyfj/X1urOCDQNfX//2hjHQVDHQUTMGkay2Vo8C@/oCQzP6/4v24KAA "Pyth – Try It Online") ## Explanation ``` +*sPQEe Q # First input P # Remove the last element s # Sum elements * E # Multiply by the second input + e # Add the last element of the first input ``` [Answer] # x86-16 machine code, 18 bytes ``` 33 DB XOR BX, BX ; clear running sum 49 DEC CX ; decrement array length 74 09 JZ ADD_LAST ; handle array length of 1 case LOOP_SUM: AD LODSW ; load next value into AX 03 D8 ADD BX, AX ; BX = BX + AX E2 FB LOOP LOOP_SUM ; keep looping 93 XCHG AX, BX ; move sum into AX F7 E2 MUL DX ; DX:AX = AX * DX 93 XCHG AX, BX ; move result back to BX ADD_LAST: AD LODSW ; load last value into AX 03 C3 ADD AX, BX ; AX = AX + BX C3 RET ; return to caller ``` As a callable function: `[SI]` to input array, `CX` array length, `DX` = `N`. Output to `AX`. Rather than make an elaborate test program, here's it being run using DOS DEBUG, entering the input array into memory and setting registers as they would be called: [![enter image description here](https://i.stack.imgur.com/JP7iR.png)](https://i.stack.imgur.com/JP7iR.png) Explanation of above: Enter input array into memory address `DS:200` as 16-bit, little-endian words: ``` -e 200 3 0 1 0 4 0 1 0 5 0 ``` Point `SI` to this input array: ``` -r SI :200 ``` Set `CX` to array's length: ``` -r CX :5 ``` Set `N` to `10` (`0xA` in hex): ``` -r DX :A ``` Execute and stop before last instruction (`RET` will "return to DOS" and clobber registers): ``` -g 111 ``` Result is `AX=005F` or `95` in decimal. [Answer] # [Golfscript](http://www.golfscript.com/), 13 bytes ``` ~:i;-1%{i*+}* ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v84q01rXULU6U0u7Vuv//2hjBUMFEyA2jVUwNAAA "GolfScript – Try It Online") **Explanation:** `~` to convert string input to array and integer on stack. `:i;` assigns \$n\$ to `i` and pops value. `-1%` reverses the array and `{i*+}*` folds the array with `(a, b) -> a*n + b` [Answer] # [Emacs Lisp](https://www.gnu.org/software/emacs/manual/eintr.html) with [dash](https://github.com/magnars/dash.el/tree/732d92eac56023a4fb4a5dc3d9d4e274ebf44bf9#-sum-list) library: ~~38~~ 51 bytes ``` (lambda(n A)(+(car(last A))(* n(-sum(butlast A))))) ``` (38 bytes was the function body' size only.) [Answer] # [Pyramid Scheme](https://github.com/ConorOBrien-Foxx/Pyramid-Scheme), ~~7747~~ ~~3668~~ ~~1985~~ ~~1732~~ 1619 bytes ## Edits * -4079 bytes by giving the variables shorter names... 😅 * -1638 bytes by doing some more manual optimisation * -253 bytes by using more 0-height trees * -113 bytes because out can output the final result directly ``` ^ ^ ^ ^ ^ ^ ^ ^ ^ / \ -^ / \ / \ / \ -^ / \ / \ / \ /set\ -^ / do\ /set\ / \ -^ /set\ / \ /out\ ^-----^ -^ ^-----^ ^-----^ / set \ -^ ^-----^ / \ -----^ /l\ / \ -^/c\ ^-/n\ ^- ^-------^ -^/i\ ^- / loop \ /+\ --- /arg\^---- ^- --- ^- /N\ /#\^---- ^- ^---------^ ^---^ ^------^ / \ /-\ --- ^----^ ^- / \ / \ /s\ /#\ / \ ^- ^---^ ^---^ / \ ^- ^- /<=>\ ^---^ --- ---^ /99 \ ^- / \ / \ /n\ /1\ /arg\^- ^- ^-----^ / \ / \ / \ ----- ^- ^---/ \--- --- ^------^ ^- /i\ /0\ ^---/set\ /arg\ ^- / \ -----^ /n\ ^- /-\ --- ---/ \ ^-----^ -----^ ^- ^--- / \ --- ^- ^---^ ^---/s\ / \ /-\ ^- / \ /set\ ^- /n\ /1\ / \ --- / + \ ^---^ ^- /set\ ^-----^ / \ --- --- ^--- ^-----^ /n\ /1\ ^- ^-----^ /c\ /!\ /set\ / \ /s\ /*\ --- --- -^ /n\ /+\ --- ^--- ^-----^ /set\ --- ^---^ / \ --- ^---^ /=\ /s\ /0\ ^-----^ /#\ /N\ /set\ /n\ /1\ ^---^ --- --- /i\ /-\ ^--- --- ^-----^ --- --- / \ /l\ --- ^---^ / \ /n\ /0\ /arg\--- /i\ /1\ /arg\ --- --- ^----- --- --- ^----- /n\ /i\ --- --- ``` [Try it online!](https://tio.run/##jVTbagIxEH3PV6T4Vgmz0vahUPsJ/YIQEJVW8IZrH/r1aTK3zO4qGGozzJycOXPR899lddhtQr/@2R62OftyEv7RSaP7ZtAYrvwDH31gV7XtfTM4MAoD9NuroMBvTjVIPnR4pRg5q3H6vRaKFOpJCBNb7gIuz5jDOD1zkMfBPqpcWFc7BTjSzc8oA@zYCX5/Op291jKPrkCKsbp8R3yBMLnhi1szM0EhDlRgQiliiVebGiKxcZiftHaSBX2sSVx7mYJwm1vCHPTwsfwkHkLUTCwH3t8VWd/gp/QGFjQEKti2KhmkmTTGmhwcI@cZ1FzlYJuhi4TUyddcTtZPBPnWLAQdpezWMkwXjTyeu2FK3FyzoKrMto3F93GwyoFlNVF@sLNNs2ldk1@tuYyrbcGAIQ3LpG3V9tkC2p5TLmdr5PHgksPTPaG2BEQ@a7LKJuS4@F62fJJ/Sq7I9uOhHsIuR4m76O@wzmL9Wjn7y6C9NQPTDeBntFrB0lJZg@2QqRTCvW2MnrHusuLckc7gcWM19/RUNaSYdnskVsv294@KJaSb5jhG/9gpatztQh86BZlzfsmL/Fo@b3nR/QM "Pyramid Scheme – Try It Online") ## Explanation ``` (set nil (arg 99)) // Make nil // Count the number of input arguments - n (set nargin 0) (do cond ( (set nargin (+ nargin 1)) (set cond (! (= (arg nargin) nil))) ) ) (set nargin (- nargin 1)) (set N (# (arg nargin))) // N - the number all but last of the array elements is getting multiplied by // Add all but last elements of A (set sum 0) (set i (- nargin 1)) (loop (<=> i 0) ( (set i (- i 1)) (set sum (+ sum (* (# (arg i)) N))) // A[i] multiplied by N ) ) (set sum (+ sum (# (arg (- nargin 1))))) // Add the last element of A (out sum) // Print ``` [Answer] # [Ruby](https://www.ruby-lang.org/en/), 46 19 bytes ``` ->a,n{eval a*"*n+"} ``` Courtesy of [petStorm](https://codegolf.stackexchange.com/users/96495/petstorm). **Old answer:** ``` n,*A,l=gets.split(' ').map(&:to_i) p A.sum*n+l ``` [Answer] ## [MAWP](https://esolangs.org/wiki/MAWP), 26 bytes ``` %@_2A<\:.>2M3A[1A~M~]%\WM: ``` Now it works properly on the testcases. Works on MAWP 1.1's integer input. [Try it!](https://8dion8.github.io/MAWP/v1.1?code=%25%40_2A%3C%5C%3A.%3E2M3A%5B1A%7EM%7E%5D%25%5CWM%3A&input=1%202%203%204) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` Ṫṭ×S ``` [Try it online!](https://tio.run/##y0rNyan8///hzlUPd649PD34/@Hl@o@a1kT@/x8dbaxjqGMCxKaxOoYGsTqoAiA@kLC0tIwFAA "Jelly – Try It Online") ``` Ṫ Pop the last element of the left argument, ṭ append it to × the right argument times what's left of the left argument, S and sum. ``` A more fun solution, which borrows Jonathan Allan's base conversion trick: # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` S,¥/ḅ ``` [Try it online!](https://tio.run/##y0rNyan8/z9Y59BS/Yc7Wv8fXq7/qGlN5P//0dHGOoY6JkBsGqtjaBCrgyoA4gMJS0vLWAA "Jelly – Try It Online") ``` / Reduce the left argument by , pair right with S ¥ the sum of left, ḅ and convert from base right. ``` Bonus: `Ä-.ịḅ’}` is a whole 7 bytes, and doesn't even work if the left argument only has one element, but it's just kind of funny. [Answer] # [PHP](https://php.net/), 41 bytes ``` fn($a,$n)=>array_pop($a)+array_sum($a)*$n ``` [Try it online!](https://tio.run/##bYw/C8IwEMX3@xRvuKHRUCzqUGJ1EhwEu5dSQmnI0jY0dRDxs8f4Z3CQ4x3v9457zrqwOzjriNgUwQwJa8mDKPZ6mvStcaOLiVh@yF/7Fy14CIp47vzsUaAioIqzlpncRG1riWyFuP8dfvK3z/McNYhqKCIzTp1uLRJ827WPDgL3@NK1dgSbJE1TnoVEeSqb4@Ws6IHwBA "PHP – Try It Online") Just trying to use all the built-ins! [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 20 bytes ``` {@^a.pop+$^b*@a.sum} ``` By using twigils, `@^a` matches the first arg (the array), and `$^b` the second (the multiplier). [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv9ohLlGvIL9AWyUuScshUa@4NLf2vzUXF1CBgyNQgWNRUWKlXl5quYaxjqGOCRCbauoQFDXUtAab4AQ0wdBAR8FQR8HSEmhqcWKlQppGjUq8pkJafhHIhiigIuv/AA "Perl 6 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṪṭSƊḅ ``` A dyadic Link accepting a list of numbers on the left and a number on the right which yields a number. **[Try it online!](https://tio.run/##y0rNyan8///hzlUPd64NPtb1cEfr////o411FAx1FEzApGnsf0MDAA "Jelly – Try It Online")** ``` ṪṭSƊḅ - Link: list of numbers, A; number n Ɗ - last three links as a monad - f(A): Ṫ - remove the tail (of A) and yield its value S - sum (the remaining elements in A) ṭ - tack -> [sum_of_remaining, tail] ḅ - convert from base (n) -> n×sum_of_remaining+1×tail ``` [Answer] # [Q'Nial](https://github.com/danlm/QNial7), 33 bytes (20 bytes without operator definition) ``` s is op n a{+link[n*front,last]a} %full operator definition +link[n*front,last]a %simple function ``` Explanation: ``` + sum, reduce by + link list of the items of the argument [ atlas (argument of link operation), point-free notation n* n * front all elements but the last of the argument , last last element of the argument ] end atlas a array a (argument of atlas) ``` Intermediate results, for `n=10` and `a=3 1 4 1 5` ``` 10 s 3 1 4 1 5 or s 10 (3 1 4 1 5) or +link[10*front,last]3 1 4 1 5 [n*front,last] a +-------------+-+ |+--+--+--+--+|5| ||30|10|40|10|| | |+--+--+--+--+| | +-------------+-+ link[n*front,last] a +--+--+--+--+-+ |30|10|40|10|5| +--+--+--+--+-+ +link[n*front,last]a 95 ``` [Answer] # [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), ~~29~~ 27 bytes ``` j&10p#v&\10g*\4 _\.@ >+\:# ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz///PUjM0KFAuU4sxNEjXijHhio/Rc1BQsNOOsVL@/9/QQMFYwVDBBIhNFQA "Befunge-98 (PyFunge) – Try It Online") Input is first `N`, then `A`. Note that there has to be a trailing space. Animation of the code: [![enter image description here](https://i.stack.imgur.com/nAF2G.gif)](https://i.stack.imgur.com/nAF2G.gif) The pilcrow (¶) represents a newline (value 10) in the grid. [Answer] # [Julia 1.0](http://julialang.org/), ~~21~~ 19 bytes ``` A$n=pop!(A)+sum(A)n ``` [Try it online!](https://tio.run/##dY5BCsIwEEX3OcW3dJFgFgbroosKPUctIm0KKTUNbQr1HuLK03mRGlMLIvphZmB48@fXQ6NOYpymNNSJac2KpmzdD2c39GRlb3skyAicaLblEByR77vcjQ1Dske8438ACA@IaAEEPpTzOI5ngOSEVG0HSlOuGa8ZlIZ/7w@ro3IxitZcXK5Q@52q5nWCmiyOplPaNpoGj/sVAYd3ez1wJPOUbHr5C7994xzBwVI5GllYWSKsWfB20CVxNT0B "Julia 1.0 – Try It Online") ]
[Question] [ This challenge is inspired by one of my other challenges: [Pointlessly make your way down the alphabet](https://codegolf.stackexchange.com/questions/196192/) That challenge asked you to take a string of text, and for each letter produce a sequence of letters moving down the alphabet to 'a'. For this challenge I'd like to decode the output of that challenge (minus the line breaks), to find a human-readable string from a much longer human readable string. --- Here is some text which has been encoded using the Dreaded Alphabet Cypher™️ hgfedcbaedcbalkjihgfedcbalkjihgfedcbaonmlkjihgfedcba wvutsrqponmlkjihgfedcbaonmlkjihgfedcbarqponmlkjihgfedcbalkjihgfedcbadcba It consists of descending alphabetical sequences, ending in an 'a'. The first character in each of these sequences is a letter in the decoded text. (A space is still a space). # The challenge * Write code to convert a Dreaded Alphabet Cypher™️ encoded string into a decoded, human-readable string. * No need to validate if it is a Dreaded Alphabet Cypher™️ string, I'm not interested in how it handles invalid input. * Use any language you please. * Please include a link to an online iterpreter. * The input will only consist of lower-case letters and spaces. No upper cases, punctuation etc. * Code golf, try to write short code, standard loopholes etc. # Test Cases Input: ``` hgfedcbaedcbalkjihgfedcbalkjihgfedcbaonmlkjihgfedcba wvutsrqponmlkjihgfedcbaonmlkjihgfedcbarqponmlkjihgfedcbalkjihgfedcbadcba ``` Output: ``` hello world ``` --- Input: ``` abacbadcbaedcbafedcbagfedcbahgfedcbaihgfedcbajihgfedcbakjihgfedcbalkjihgfedcbamlkjihgfedcbanmlkjihgfedcbaonmlkjihgfedcbaponmlkjihgfedcbaqponmlkjihgfedcbarqponmlkjihgfedcbasrqponmlkjihgfedcbatsrqponmlkjihgfedcbautsrqponmlkjihgfedcbavutsrqponmlkjihgfedcbawvutsrqponmlkjihgfedcbaxwvutsrqponmlkjihgfedcbayxwvutsrqponmlkjihgfedcbazyxwvutsrqponmlkjihgfedcba ``` Output: ``` abcdefghijklmnopqrstuvwxyz ``` --- (beware the multiple a's) Input: ``` aarqponmlkjihgfedcbaonmlkjihgfedcbanmlkjihgfedcba a aarqponmlkjihgfedcbaonmlkjihgfedcbanmlkjihgfedcbasrqponmlkjihgfedcbaonmlkjihgfedcbanmlkjihgfedcba hgfedcbaasrqponmlkjihgfedcba anmlkjihgfedcba aarqponmlkjihgfedcbadcbavutsrqponmlkjihgfedcbaarqponmlkjihgfedcbakjihgfedcba ``` Output: ``` aaron a aaronson has an aardvark ``` --- Input: ``` hgfedcbaaponmlkjihgfedcbaponmlkjihgfedcbayxwvutsrqponmlkjihgfedcba gfedcbaonmlkjihgfedcbalkjihgfedcbafedcbaihgfedcbanmlkjihgfedcbagfedcba ``` Output (is a secret, shh) [Answer] # JavaScript (ES9), ~~37 33~~ 26 bytes Returns an array of characters. Either a negative look-behind: ``` s=>s.match(/(?<![b-z])./g) ``` [Try it online!](https://tio.run/##lVJLEoIwDN17CmRDu6BcQPQgjovyB4EiRVQuXxUBoaSg02knTV@Sl9cktKbcLeOiMnPm@SKwBbf3nGS0ciNkocNue3TM5oSJFWLhspyz1CcpC1GA9CgMfM91aHuk5yTuHWOb5dn4qt3qa8XLSyH5pescMLbfW8ckYXGODAPjjUSMOrRDtfBPUBfb5xiSfdMqqk1oLLKWOc@amLcFSAHJA2oGK6kQ@K7wP1QPjfJlUXq6@rfSQLzWvzH83xq9AUVqM0IAHbXcAPhHqYYMxcoYKT9Cg5sf29KwT4EASfEE "JavaScript (Node.js) – Try It Online") Or a positive look-behind: ``` s=>s.match(/(?<=a| |^)./g) ``` [Try it online!](https://tio.run/##lVLbEoIgEH3vKxxfhIfwB7L@pBm8awomZpfx361MTWHRGgZmWc7unj1sSmsqvDIpqi3jftCGTiucvSA5rbwY2eiwc2hjNEdM7Ai3HmeCZwHJeIRCZMZRGPieS7sjO6XJ4JjanOXTq3GtL5Uoz4Xkl64qYGq/t4lJyhOGLAvjjUSMurRHdfBPUB875BiTfdNqqs1oLLKWOStNqG0BUkDygJrBSmoEvmn8d93DQ/uyKD1d/VtpIF7r3xjxb43BgCINhRBARy83AP5RqjFDsTJG2o8w4OantjTscyBAsn0C "JavaScript (Node.js) – Try It Online") --- ## 25 bytes If the input is guaranteed not to contain leading or double spaces (or we're allowed to remove and collapse them respectively), the positive look-behind can be made 1 byte shorter: ``` s=>s.match(/(?<=a|\b)./g) ``` [Try it online!](https://tio.run/##lVJLEoIwDN17CoYN7cJyAdGLuCl/EFqkiJ/x7qgICG0KMp120vQleXlNSmsqvDIpqi3jftCETiOcvSA5rbwY2eiwc@jz6GJiR7jxOBM8C0jGIxQiM47CwPdc2h7ZKU16x9jmLB9fjWt9qUR5LiS/dFUBY/uzTUxSnjBkWRhvJGLUpR2qhX@Dutg@x5Dsl1ZTbUJjlrXMWWlCbQuQApIH1AxWUiPwTeO/6x4e2pdZ6eni30oD8V5rY8TaGr0BRRoKIYCOXm4A/KdUQ4ZiYYy0H2HAzY9tadinQIBk8wI "JavaScript (Node.js) – Try It Online") [Answer] ## Haskell, 32 bytes ``` f s=[y|(x,y)<-zip('a':s)s,x<'b'] ``` [Try it online!](https://tio.run/##lVJLDoIwEL3KhJgACXoAAzdw55KwKAqCfKwU5BPvXhUpltJKSNNmPm/aN28aIZIEaUppCMRx26fRWK1pb7sYGzrS98QkVmPrvu7RDMU5OICr8lgWhxx2QKJbDRvIEIYQXC26hMH55KP@SJNrzAK8fcsz3oX6UZWkuGMhLrhzAG9/tmaBhnw0eH34mxwwDDsW/coVt06e@8tO5DYjO6cvaVkmg1QbuWIKIRtFvFUlOmWmlxgtzkoY8HutrSFr32CGrBJmhCR01LJKwIIkIxIvfAulsCBvkreFzzsFMjIefQE) For each pair of consecutive characters, if the first one is `'a'` or `' '`, output the second one. Prepends an `'a'` to the string so that the first character is always output. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` OŻI‘Tị ``` A monadic Link accepting a list of characters which yields a list of characters. **[Try it online!](https://tio.run/##y0rNyan8/9//6G7PRw0zQh7u7v7//79SYmJRYUF@Xm5OdlZmRnpaakpyUiIaF5WnAISk6ikm1Q4YA5tOBQwHYXEOCJeVlmDRjkUxElMJAA "Jelly – Try It Online")** ### How? ``` OŻI‘Tị - Link: list of characters, S e.g. " baadcba acbaedcba " i.e. [' ',' ','b','a','a','d','c','b','a',' ',' ','a','c','b','a','e','d','c','b','a',' ',' '] O - to ordinal (vectorises across S) [ 32, 32, 98, 97, 97,100, 99, 98, 97, 32, 32, 97, 99, 98, 97,101,100, 99, 98, 97, 32, 32] Ż - prepend a zero [ 0, 32, 32, 98, 97, 97,100, 99, 98, 97, 32, 32, 97, 99, 98, 97,101,100, 99, 98, 97, 32, 32] I - incremental differences [ 32, 0, 66, -1, 0, 3, -1, -1, -1,-65, 0, 65, 2, -1, -1, 4, -1, -1, -1, -1,-65, 0] ‘ - increment (vectorises) [ 33, 1, 67, 0, 1, 4, 0, 0, 0,-64, 1, 66, 3, 0, 0, 5, 0, 0, 0, 0,-64, 1] T - truthy indices [ 1, 2, 3, 5, 6, 10, 11, 12, 13, 16, 21, 22] ị - index into (S) [' ',' ','b', 'a','d', ' ',' ','a','c', 'e', ' ',' '] i.e. " bad ace " ``` [Answer] # [J](http://jsoftware.com/), ~~22 13~~ 12 bytes –9 bytes, thanks @Jonah! ``` #~1,1-{:I.}: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/lesMdQx1q6089Wqt/mtypSZn5CukKahnpKelpiQnJSYW5Ofl5mRnZcIE0PmVFeVlpSXFRYXoEgpQGk0YmQ0h4VxUhVBKHe6kxERMS9C4aC4AQlL1FJNqBzygsAUBhoOwOAeEsYcgFsVITPX/AA) [Answer] # [Perl 5](https://www.perl.org/) (`-p`), ~~15~~, 16 bytes ``` s/[b-z]\K.*?a//g ``` [Try it online!](https://tio.run/##K0gtyjH9/79YPzpJtyo2xltPyz5RXz/9//@M9LTUlOSkRDCRk52VCRNAZufn5SJzFcrLSkuKiwoL0MTRuJgKkNkgzJWYlAhlgsUgMlAFMIVwHQi9OIxEsQuv09AdhuFSTLdj8S@2MMAaMNiDC0coVuAQr8QlUYVThisxkWAsoUUtEJKqp5hUO2AMbDoVMByExTm4wxSLYuTwgCsrIJAgcAapAnYfIrPRki2qQij1L7@gJDM/r/i/bgEA "Perl 5 – Try It Online") or using options trick # [Perl 5](https://www.perl.org/) (`-nF/(?<![\x20a])(?!^)[b-z]*a/`), 7 bytes ``` print@F ``` [Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvxMHt//@M9LTUlOSkRDCRk52VCRNAZufn5SJzFcrLSkuKiwoL0MTRuJgKkNkgzJWYlAhlgsUgMlAFMIVwHQi9OIxEsQuv09AdhuFSTLdj8S@2MMAaMNiDC0coVuAQr8QlUYVThisxkWAsoUUtEJKqp5hUO2AMbDoVMByExTm4wxSLYuTwgCsrIJAgcAapAnYfIrPRki2qQij1L7@gJDM/r/i/bp6bvoa9jWJ0TIWRQWKspoa9YpxmdJJuVaxWoj4A "Perl 5 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 43 bytes ``` lambda s:[r for l,r in zip(' '+s,s)if'b'>l] ``` An unnamed function accepting a string which returns a list of characters. **[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYKrpIIS2/SCFHp0ghM0@hKrNAQ11BXbtYp1gzM009Sd0uJ/Z/SWpxiYKtgnpiYlFhQX5ebk52VmZGelpqSnJSIhoXlacAhKTqKSbVDhgDm04FDAdhcQ4Il5WWYNGORTESU52Lq6AoM69EI00DFEKamv8B "Python 3 – Try It Online")** --- To accept & return lists use `...zip([' ']+s...` instead (45) To accept & return strings use `lambda s:''.join(r for l,r in zip(' '+s,s)if'b'>l)` (50) [Answer] # [C (clang)](http://clang.llvm.org/), ~~100~~ ~~98~~ ~~96~~ ~~95~~ ~~94~~ ~~92~~ ~~90~~ ~~88~~ ~~64~~ 46 bytes Saved 24 bytes thanks to @Neil!!! Saved 18 bytes thanks to @dingledooper (removed #include<stdio.h>) ``` f(char*c){while(*c)for(putchar(*c);*c++>97;);} ``` [Try it online!](https://tio.run/##lVPbDoIwDH3nKxaehsTEN2OW@CW@jMlNceAA8RK/HQfCxNGJQEbarj07PStsyRLKw7oOMIuoWDDnUUVx4mNpBanAWVk08cYlC@a6282aOORZx7xAJxpz7FgPC8knwHYUBv6eebT9JMdD3AeGdspPQxdVl7LIxTnT4po7ThjazbId0vLIhKQmyex4H5EO9WiX1ua/q7riHkShfXANx9ktLEL2F6Gf/HX2o3YU5rhTQB1IMVBGBQurbBD/aogrtJsp427c@X0/dHICtLGR79yafO4ZvQFVohEhgE6zYDWA5H@1UhDZxIwZrwLB3Q9t7Zf4TtRYCr8oBUcrYj2t@gU "C (clang) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes *-1 byte thanks to Kevin Cruijssen* ``` AηíR¬S.: ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f8dz2w2uDDq0J1rP6/z8xsaiwID8vNyc7KzMjPS01JTkpEY2LylMAQlL1FJNqB4yBTacChoOwOAeEy0pLsGjHohiJCQA "05AB1E – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), ~~10~~ ~~9~~ 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` óÈ¥YcÄÃy ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=88ilWWPEw3k&input=ImhnZmVkY2JhZWRjYmFsa2ppaGdmZWRjYmFsa2ppaGdmZWRjYmFvbm1sa2ppaGdmZWRjYmEgd3Z1dHNycXBvbm1sa2ppaGdmZWRjYmFvbm1sa2ppaGdmZWRjYmFycXBvbm1sa2ppaGdmZWRjYmFsa2ppaGdmZWRjYmFkY2JhIg) ``` ó split between those characters that return true when passed through... È Ã function : ¥ x equal to.. YcÄ character next to y y transpose Flag -g used to get 1st element ``` Saved 1 thanks to @Shaggy [Answer] # [R](https://www.r-project.org/), ~~57~~ 56 bytes -1 byte thanks to Giuseppe. ``` function(s)intToUtf8(c(v<-utf8ToInt(s),0)[c(0,v)%%32<2]) ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jWDMzryQkP7QkzUIjWaPMRrcUyArJ98wrAUrpGGhGJ2sY6JRpqqoaG9kYxWr@T9NQykhPS01JTkoEEznZWZkwAWR2fl4uMlehvKy0pLiosABNHI2LqQCZDcJKmlxAJyQmJUL5YAmINFQVTDVcG8IAHOaiWIjXfeiuw3AupgeweBpbQGANHexhhiMoK3CIV@KSqMIpAw3kRILxhRbJQEiqnmJS7YAxsOlUwHAQFufgDlgsijECBa62gEDSwBm4Cti9icxGS8CoClHjSEnzPwA "R – Try It Online") Could probably be made shorter with a regex, but this is more R-like. Converts to integers (vector `v`), then keeps only the first character and the characters which follow a space or an `a`. Since the corresponding codepoints are 32 and 97, we can check whether \$v\_i\mod 32 <2\$ to get the relevant entries. [Answer] # [Haskell](https://www.haskell.org/), 59 bytes ``` f""="" f(x:s)|x<'b'=x:(f s)|1>0=x:(f$tail$dropWhile(>'a')s) ``` [Try it online!](https://tio.run/##lVJBDoIwELzziqYhAW56JcILvHnwXIQKUqBS0Gr8e0UEhNJKCIHM7s6ys9PGiKURIUJgCD0IDWxzlzkvvrMCy@OujUETbf1Ni80KJcQMy4Ie44REtm8hy2GOyFCSe2FhAFpXh6rc5yYGMD7jKDwFqP2Q9JL0iTEu8mwcgvutrlh5pVJeCueEMf68cKoFBagrtIwvr6P3bUP/70@aAZPJf4XKMme655sotlc5orRJbZ7GU67JP3SFp7Yiu40WT1A69uZZ28PWzuiBqhPMBCnk6B1WkPXuDE104bJo7QbqfcdYutJTYq9LvAE "Haskell – Try It Online") No match for regex solutions, but I figured I'd try a recursive solution. [Answer] # JavaScript, ~~35~~ ~~32~~ 31 bytes ``` s=>s.replace(/ |.*?a/g,x=>x[0]) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1q5Yryi1ICcxOVVDX6FGT8s@UT9dp8LWriLaIFbzf3J@XnF@TqpeTn66RpqGUkZ6WmpKclIimMjJzsqECSCz8/NykbkK5WWlJcVFhQVo4mhcTAXIbBBW0tT8DwA) [Answer] # [Ruby](https://www.ruby-lang.org/en/), 28 bytes ``` ->s{s.scan(/(?<=a|\b)./)*""} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664ulivODkxT0Nfw97GNrEmJklTT19TS0mp9n9BaUmxQppecmJOjoZ6RnpaakpyUiKYyMnOyoQJILPz83KRuQrlZUAjigoL0MTRuJgKkNkgrK7JxYXimsSkRKgUWA1EJVQDTCPcBIRZOKxAsRuvU9EdiuFyTL9g8T@2MMEaUNiDD0eoVuAQr8QlUYVTBjO8EwnGIlrUAyGpeopJtQPGwKZTAcNBWJyDO4yxKMYXPnBtBQQSDM4gV8DuY2Q2WrJGVQh32X8A) This is a port of [Arnauld's Javascript answer](https://codegolf.stackexchange.com/questions/196466/decode-the-dreaded-alphabet-cypher%ef%b8%8f/196467#196467) to Ruby. [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 14 bytes ``` {x@&1,98>-1_x} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qusJBzVDH0sJO1zC@ovZ/mrqGUkZ6WmpKclIimMjJzsqECSCz8/NykbkK5WWlJcVFhQVo4mhcTAXIbBBWslZKTEqEcsCiEDmoEphSuB6EbhyGotiG13HoTsNwK6brsfgYWyhgDRrsAYYjHCtwiFfikqjCKQMK4USCMYUWvUBIqp5iUu2AMbDpVMBwEBbn4A5VLIpRQwSusIBAosAZrArY/YjMRku6qAphbtH8DwA "K (oK) – Try It Online") Inspired by [FrownyFrog's/Jonah's J solution](https://codegolf.stackexchange.com/a/196475/75681) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-S`](https://codegolf.meta.stackexchange.com/a/14339/), ~~9~~ 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ¸®ò§ mά ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVM&code=uK7ypyBtzqw&input=ImFhcnFwb25tbGtqaWhnZmVkY2Jhb25tbGtqaWhnZmVkY2Jhbm1sa2ppaGdmZWRjYmEgYSBhYXJxcG9ubWxramloZ2ZlZGNiYW9ubWxramloZ2ZlZGNiYW5tbGtqaWhnZmVkY2Jhc3JxcG9ubWxramloZ2ZlZGNiYW9ubWxramloZ2ZlZGNiYW5tbGtqaWhnZmVkY2JhIGhnZmVkY2JhYXNycXBvbm1sa2ppaGdmZWRjYmEgYW5tbGtqaWhnZmVkY2JhIGFhcnFwb25tbGtqaWhnZmVkY2JhZGNiYXZ1dHNycXBvbm1sa2ppaGdmZWRjYmFhcnFwb25tbGtqaWhnZmVkY2Jha2ppaGdmZWRjYmEi) ``` ¸®ò§ mά :Implicit input of string ¸ :Split on spaces ® :Map ò : Partition between characters where § : First is <= second m : Map Î : First character ¬ : Join :Implicit output, joined with spaces ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` Ḳµ=Ṃk⁸ZḢ)K ``` [Try it online!](https://tio.run/##y0rNyan8///hjk2Htto@3NmU/ahxR9TDHYs0vf///5@YWFRYkJ@Xm5OdlZmRnpaakpyUiMZF5SkAIal6ikm1A8bAplMBw0FYnAPCZaUlWLRjUYzEBAA "Jelly – Try It Online") A monadic link taking a Jelly string and returning a Jelly string. When run as a full program takes a string as its argument and implicitly prints the output string. [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 106 bytes ``` I =INPUT S I LEN(1) . X :F(O) O =O X R = REVERSE(&LCASE) X REM . R I X R REM . I :(S) O OUTPUT =O END ``` [Try it online!](https://tio.run/##K87LT8rPMfn/n9NTwdbTLyA0hCsYyPRx9dMw1FTQU4jgtHLT8Nfk4vRXsPVXiODiDFKwBRKuYa5Bwa4aaj7OjsGumgoRCkGuvkDVQVxAvUAOlOvJaaURrMnlz@kfGgI0GWgCl6ufy///iYlFhQX5ebk52VmZGelpqSnJSYloXFSeAhCSqqeYRPUA "SNOBOL4 (CSNOBOL4) – Try It Online") ``` I =INPUT ;* Read input S I LEN(1) . X :F(O) ;* extract the first letter or goto O if none exist O =O X ;* append that letter to the output R = ;* set R to the empty string REVERSE(&LCASE) X REM . R ;* Set R to the letters up to 'a', starting at X. ;* R is empty string if X is space or 'a' I X R REM . I :(S) ;* Set the REMainder of I after (X + R) to I; goto S O OUTPUT =O ;* output the string END ``` [Answer] # [Red](http://www.red-lang.org), 74 bytes ``` func[s][parse s[any[copy t thru"a"(prin#"`"+ length? t)opt[sp(prin sp)]]]] ``` [Try it online!](https://tio.run/##lVPbUsMgEH3PV@ysL@34B33xH3xlmJFyaaoVEEhr/PnYxKSlXNSGCbOXs3A4LE6K4VkKQhu1gUF1mhNPiWXOS/CE6Z5wY3sIEFrXIcOVdXv9gC/4CAepd6F9grA2NhBvpxR4u6bnb1DGScZb4EZIAQTbnZKCb9k0Hd5e90sgto1@j104Hbvg3YdN4ombA2J7/LFBtmWzM0V/cjNkgV5qrtWVRW92@5VcSi3jmrMvnLikQlGasmAVHT8r8b6W@KpmRoXZnzeVXO953Fvj791jMUqVkBEq0KmrWgDHikBzafqsC/6tOJQPGdtJ794CFzIUiJrf4vhMAyDS4Rs "Red – Try It Online") [Answer] # [braingasm](https://github.com/daniero/braingasm), ~~20~~ 18 bytes ``` ,[.32-n[65-$[,]],] ``` It's been a while since I worked on braingasm. There seems to be a `compare` function, but I guess I didn't come around to implement a way to use the result. Well, this works: ``` , # Read a byte from input [ ] # While the current byte is not zero . # Print it 32- # Decrease by 32 n[ ] # If the result is non-zero (meaning it wasn't a space): 65- # Subtract 65, leaving 'a' => 0, 'b' => 1, 'c' => 3, etc $[,] # That many times, read a byte from input , # Read another byte ``` Doesn't handle newlines or anything other than lowercase letters and spaces in the input. [Answer] # [Pip](https://github.com/dloscutoff/pip), 12 bytes ``` aR`\w*?a`_@0 ``` [Try it online!](https://tio.run/##K8gs@P8/MSghplzLPjEh3sHg////GelpqSnJSYlgIic7KxMmgMzOz8tF5iqUl5WWFBcVFqCJo3ExFSCzQRgA "Pip – Try It Online") ### Explanation ``` a The input, as a command-line argument R Do a regex replacement: `\w*?a` Match a non-greedy series of letters ending in a _@0 Replace with the first character of the match ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 33 bytes ``` x=>x.Where((_,l)=>l<1||x[l-1]<98) ``` [Try it online!](https://tio.run/##lVRdb8IgFH0ev4L4BEk18W1LP17MlizZuw/GLJRRy6zUAdVu09/eWWu1UpixpM39OBcOB26pGlLFq5dC0EBpycXCe30WxYpJEmcsoCmRUZSEVRlG5WiaMskQevcyHEZZMN7tylk2HM@Dp0dc@WBDJNRMaQVDKNh2Noe/4GGQLhL2QWNy/GTLT94GunYuVl0XbjeFVvJrbcQNtw/o2vU78A4MSExO7jHeZE@gFnyuutQ7pr1a7196Jrke2z5/y55tOljFsUvmULJ0xL9diR9nptGY3Dwt44gP494ade8arWGrhD1CFjpuXS1gU5MzdH3jYjilhfZddm3j@l4DWzZg74Mkl4zQFLVdCrlouhXXbTqVXLM3Lhhq/gKjSS4o0ShBNQZj7IM9gJ2nIuAP "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/), ~~66~~ 48 bytes edit: -18 bytes thanks to @dingledooper (removed #include) ``` P;D(char*T){*T?P>97||putchar(*T),P=*T++,D(T):0;} ``` [Try it online!](https://tio.run/##S9ZNzknMS///P8DaRSM5I7FIK0SzWivEPsDO0rympqC0BCSmARTUCbDVCtHW1nHRCNG0MrCu/Z@ZV6KQm5iZp6HJVc2lAAQuGkqJiQoZ6WmpKclJiWAiJzsrEyaAzM7Py0XmKpSXlZYUFxUWoImjcTEVILNBWEnTGuwUmLvVY/LUoUJg1xG0As1dQEiqnmJS7YAxsOlUwHAQFueAMPbww6IYiYk/sOBmoJuAzq@swBF7Cti9j8yGkDhCBs2ZRaklpUV5CgbWXLVc/wE "C (clang) – Try It Online") ``` int P; // previous character D(char*T) { if (*T) // check for end of string { if (!(P > 'a')) // output current if previous was 'a' or ' ' putchar(*T); P = *T; // update previous D(T + 1); // find next } } ``` [Answer] # x86 machine code, 12 bytes (Runs in any mode, 16-bit, 32-bit, or 64-bit.) This is based on [@Noodle9's C algorithm](https://codegolf.stackexchange.com/a/196505/30206), but with rearrangement into do{}while asm loop structure. NASM listing: address, machine code (hex dump of the actual answer), source ``` 1 decda: ; (char *dst=RDI, const char *src=RSI) 2 00000000 AC lodsb ; AL = *src++ 3 .loop: ; do{ 4 00000001 AA stosb ; *dst++ = AL 5 .skip_until_a: ; do{ 6 00000002 3C61 cmp al, 'a' 7 00000004 AC lodsb 8 00000005 77FB ja .skip_until_a ; }while((AL=*p++) > 'a') 9 00000007 84C0 test al,al 10 00000009 75F6 jnz .loop ; } while(AL != terminator) 11 ; stosb ; append a terminating 0 12 0000000B C3 ret ; output end pointer returned in RDI ``` [Try it online!](https://tio.run/##lVRNbxoxED3Xv2J6ArIQQVtVEYhKkXqJFPWQHiO0ml0bcOK1tx4vgbb57XR2zceGkEqxBNgz82be84xBIlVkZjOwSMV2K1UucQwwgW6@RA8XksL07vtNH3JnKUA0ks@ndz9vegJ4GScpg/aawPUtTJuwJBGXxrlyDCdrAtL9afAU3Ak@@uvSScJ5rm/ruEt61GVa2aBNiuMzeSAvSgA0fehgJ1oaanH7gCcpIvj5aamN6navb6cXZZL04FuNjsKCYsGcD01zfLC/odHSqv0MEc96P04Z4AttMTjfE5Pz0iaAZamsBDxEa7uAYVPBqyAm/FV5SxxQOm05CIIDZ9WgRAqDGurmEJYKXBXKigE5GsNRaLxCuYEl1thMLbQ9ZlhiqDEb4CSkJFQktg1DtWa/ZaLeKCvaJs5NLwxqrYMQUs2xMoG5xltZGJehgZQC@iDizzjiCrdiTVL34d5TmVxBAlcXo9nuGvxidT@axchawp7DhwnoojQ612HA50VYgrZMBkipgkAhaeVbBVS@7rN1LeIwKtzX5PvJqvlMHKnQ/6kcmDSPQERnbEvTkbf6wRfNL6Rdn87Xl8yUucWpr7K9hfRuNKLctrba//WLaBk48@gwS3PZcuG67UrTH3fpk9dBxXIbaqQd/I2rO@pDpFmX6Ymj5jfu8ditZjwa29p5iMzUTlvDJxL69Hl0vn49TenCu6rsDnutKdiNmSCVB@0sXEoMKCKHMQRdKGKqIDPo/O3EVCtNOjMq/jeRgyfeouUuBs4BjJtz09xKeV9ZEnsKMdVoOKxzDcV2i@h/lc4W5vFBLxdzJfMMT44vT/zM3o2h99bYb84h4RWhM3Tqz4qb9dpzJri1Ff8A "Assembly (nasm, x64, Linux) – Try It Online") The input is an implicit-length (0-terminated) C string. The output is an explicit-length buffer. This function returns (in RDI) a pointer to one-past-the-end. (The caller already knows where the output buf starts, so it has C++-like .begin and .end iterators). Making this function append a terminating `0` would cost 1 extra byte for another `stosb` after the loop, unless there's a way to rearrange things that I'm not seeing. --- A sample caller that passes the output of `decda(argv[1])` to a `write` system call is included in the TIO link. You can `inc edx` in that caller to prove that the output didn't over-write beyond where it's supposed to. I had been thinking of using `loop .loop` instead of `test al,al/jnz` but then the inner loop would need a `dec ecx` or something. (Without that, it loops until writing RCX *output* bytes, which only works if the caller knows the decrypted length, not the source length.) Worth considering for a 32-bit-only version that can use 1-byte `dec ecx`, unless that could reach `loop` or `loopne` with ECX<=0 for valid inputs. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 69 bytes Hard to beat Regex on this one ``` s=>System.Text.RegularExpressions.Regex.Replace(s,"([b-z]).*?a","$1") ``` [Try it online!](https://tio.run/##ZYoxD4IwFIR3fkXTOLQGSJwRnXRyUhMH41DqA6tQsK8o@ueraEwavOTdu/tyEiOJyi1bLadojdJF@H0zkpPUYTrbPNBCFW@hs/EairYUZtE1BhBVrbFH0L29KYUEhiFl@yx6Hng8ngsa0tGEcpcEO6MsrJQGljN6KnI4ykx8rLyc1Q/4udaVX8n91lo012bAB/V/4Of@KOdJQDy5Fw "C# (Visual C# Interactive Compiler) – Try It Online") **Returns an array of Matches (characters), 64 bytes** ``` s=>System.Text.RegularExpressions.Regex.Matches(s,"(?<![b-z]).") ``` [Try it online!](https://tio.run/##fU9Nb8IwDL33V4SeEgnyB/qxQwWncYEJDhOHkLklLKQsdiDjz3e006SKSViy9fz8/KVxptF0AY1r2PobCU7yDSLJFTTBKj@PZw@IpnWYJYvgdI7k79rpUpE@VK21oOleLVnNig6L8vmMnoIoh2ZAjtOUv@ST9/3sthMyFV2WbL0heDUO@O8iWbVOK@I1Tw9NDR96r4ZgP4/mjxjj1p3GKbteAqH/Oj/wD@l/wRj3ngpZKaR8OL3kQq6hf51HVpQsyo2yAYQQWcJG1v0A "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # Ruby, 20 + 1 bytes ``` gsub /(?<!a|\b)./,'' ``` 1 extra byte for the `p` command line option: ``` $ ruby -p alphabet_cypher.rb <<< "hgfedcbaedcbalkjihgfedcbalkjihgfedcbaonmlkjihgfedcba wvutsrqponmlkjihgfedgfedcbarqponmlkjihgfedcbalkjihgfedcbadcba" hello world ``` [Try it online!](https://tio.run/##KypNqvz/P724NElBX8PeRjGxJiZJU09fR139//@M9LTUlOSkRDCRk52VCRNAZufn5SJzFcrLSkuKiwoL0MTRuJgKkNkg/C@/oCQzP6/4v24BAA "Ruby – Try It Online") [Answer] # [Gema](http://gema.sourceforge.net/), 41 characters ``` \A\P?=? \P?=$0 ?\P?=@cmps{?;?;$2;$2;} ?= ``` Unfortunately recognizers can not be combined. ☹ Sample run: ``` bash-5.0$ gema '\A\P?=$0; \P?=$0;?\P?=@cmps{$1;$2;$2;$2;};?=' <<< 'cbagfedcba cbacba' cg cc ``` [Try it online!](https://tio.run/##S0/NTfz/P8YxJsDe1p5LAUSpGHDZg2iH5NyC4mp7a3trFSMQquWyt/3/PzGxqLAgPy83JzsrMyM9LTUlOSkRjYvKUwBCUvUUk2oHjIFNpwKGg7A4B4TLSkuwaMeiGIkJAA "Gema – Try It Online") [Answer] # Perl, 20 bytes ``` s:[^a]*a(.):a$_\1:g; ``` is **almost** there. Unfortunately, it will lose the first letter, and I don’t know how to get around that. [Answer] # [Keg](https://github.com/JonoCode9374/Keg), `-ir`, `-lp`, ~~9~~ 7 bytes ``` (⑩(a-|_ ``` [Try it online!](https://tio.run/##y05N//9f49HElRqJujXx//9npKelpiQnJSYW5Ofl5mRnZcIE0PmVFeVlpSXFRYXoEgpQGk0YmQ0h4VxUhVDqv25m0X/dnAIA "Keg – Try It Online") *2 bytes saved thanks to @A̲̲ suggesting to use a for loop over a while loop* ## Answer History ``` {!|⑩(a-|_ ``` [Try it online!](https://tio.run/##y05N//@/WrHm0cSVGom6NfH//2ekp6WmJCclJhbk5@XmZGdlwgTQ@ZUV5WWlJcVFhegSClAaTRiZDSHhXFSFUOq/bmbRf92cAgA "Keg – Try It Online") ``` {!|⑩(a-|_ {!| #While there are still items on the stack: ⑩ #Print t.o.s without popping (a-| #Subtract the code point of a from tos and repeat that many times: _ #Pop items off the stack ``` [Answer] # C++, 464 bytes I'm still a beginner so will be grateful for any advice. ``` #include <iostream> #include <string> using namespace std; int main() { string input , output; getline(cin,input); output = input[0]; for (int i = 0 ; i<input.size() ; i++) { if (input[i] == 'a') { output += input[i+1]; } else if (input[i] == ' ') { output += input[i+1]; } else { continue; } } cout << output; } ``` [Try it online!](https://tio.run/##lVBBboMwELz7FSP1AIi0Ss9APlJxcI2h28JCsN1KrXg7tSGhKDnVku3dmdkZ2WoYHhul5vmBWLWu0sipN3bUsjuJP8wjxM1JOOMvsOy0GaTSMLbKhCC26CRxnOBHAKsYxIOzOKB31heZJxptW2IdK@LDwiYBXXkU68DLsfSOQN2PiIMxeeaIDJQv/JOhb@2DPJCma15YVAd1mKcSRYFIRgk2NqxLTHrNofS5zC78BOjW6HsXRMm/TfZ61bMldnrThKdNIhDeJs@3z5nm@a2pdaVe5XK0H@90BfZ1z92@xdens2Y8Dzf4TXsv2Ndh/wI "C++ (gcc) – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 50 bytes ``` import re f=lambda s:re.sub('([b-z]).*?a',r'\1',s) ``` Regex stolen from [Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/196467). [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/PzO3IL@oRKEolSvNNicxNyklUaHYqihVr7g0SUNdIzpJtypWU0/LPlFdp0g9xlBdp1jzf0FRZl6JRppGZl5BaYmGpqbm/4z0tNSU5KREMJGTnZUJE0Bm5@flInMVystKS4qLCgvQxNG4mAqQ2SAMAA "Python 3.8 (pre-release) – Try It Online") ]
[Question] [ ## Introduction The [Prime Counting Function](http://mathworld.wolfram.com/PrimeCountingFunction.html), also known as the Pi function \$\pi(x)\$, returns the amount of primes less than or equal to x. ## Challenge Your program will take an integer x which you can assume to be positive, and output a single integer equal to the amount of primes less than or equal to x. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the winner will be the program with the fewest bytes. You may use any language of your choosing provided that it existed before this challenge went up, but if the language has a built-in prime-counting function or a primality checking function (such as Mathematica), that function cannot be used in your code. ## Example Inputs Input: `1` Output: `0` Input: `2` Output: `1` Input: `5` Output: `3` [A000720 - OEIS](http://oeis.org/A000720) [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 3 bytes ``` !fg ``` This assumes that factorization built-ins are allowed. [Try it online!](http://05ab1e.tryitonline.net/#code=IWZn&input=NQ) ### How it works ``` ! Compute the factorial of the input. f Determine its unique prime factors. g Get the length of the resulting list. ``` [Answer] ## Python 2, 45 bytes ``` f=lambda n,k=1,p=1:n/k and p%k+f(n,k+1,p*k*k) ``` Uses the [Wilson's Theorem](https://codegolf.stackexchange.com/a/27022/20260) prime generator. The product `p` tracks `(k-1)!^2`, and `p%k` is 1 for primes and 0 for nonprimes. [Answer] # [MATL](http://github.com/lmendo/MATL), ~~11, 10, 8~~, 5 bytes ``` :pYFn ``` [Try it online!](http://matl.tryitonline.net/#code=OnBZRm4&input=MTU) I wrote a version that had a really cool explanation of how MATL's matrices work: [`:YF!s1=1`](http://matl.tryitonline.net/#code=OllGIXMxPTE&inputc=MTU) But it's no longer relevant. Check out the revision history if you want to see it. New explanation: ``` :p % Compute factorial(input) YF % Get the exponenents of prime factorization n % Get the length of the array ``` *Three bytes saved thanks to [Dennis's genius solution](https://codegolf.stackexchange.com/a/94364/31716)* [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~8~~ 5 bytes *3 bytes saved thanks to @Dennis!* ``` RÆESL ``` [Try it online!](http://jelly.tryitonline.net/#code=UsOGRVNM&input=&args=NQ) Port of [DJMcMayhem's MATL answer](https://codegolf.stackexchange.com/a/94354/36398) (former version) refined by Dennis. ``` R Range of input argument ÆE List of lists of exponents of prime-factor decomposition S Vectorized sum. This right-pads inner lists with zeros L Length of result ``` [Answer] # MediaWiki templates with [ParserFunctions](https://www.mediawiki.org/wiki/Help:Extension:ParserFunctions), 220 + 19 = 239 bytes ``` {{#ifexpr:{{{2}}}+1={{{1}}}|0|{{#ifexpr:{{{3}}}={{{2}}}|{{P|{{{1}}}|{{#expr:{{{2}}}+1}}|2}}|{{#ifexpr:{{{2}}} mod {{{3}}}=0|{{#expr:1+{{P|{{{1}}}|{{#expr:{{{2}}}+1}}|2}}|{{P|{{{1}}}|{{{2}}}|{{#expr:{{{2}}}+1}}}}}}}}}}}} ``` To call the template: ``` {{{P|{{{n}}}|2|2}}} ``` Arranged in Lisp style: ``` {{#ifexpr:{{{2}}} + 1 = {{{1}}}|0| {{#ifexpr:{{{3}}} = {{{2}}} | {{P|{{{1}}}|{{#expr:{{{2}}} + 1}}|2}} | {{#ifexpr:{{{2}}} mod {{{3}}} = 0 | {{#expr:1 + {{P|{{{1}}}|{{#expr:{{{2}}} + 1}}|2}} | {{P|{{{1}}}|{{{2}}}|{{#expr:{{{2}}} + 1}}}}}}}}}}}} ``` Just a basic primality test from 2 to *n*. The numbers with three braces around them are the variables, where `{{{1}}}` is *n*, `{{{2}}}` is the number being tested, `{{{3}}}` is the factor to check. [Answer] # Perl, 33 bytes Includes +1 for `-p` Give the input number on STDIN `primecount.pl` ``` #!/usr/bin/perl -p $_=1x$_;$_=s%(?!(11+)\1+$)%%eg-2 ``` Gives the wrong result for `0` but that's OK, the op asked for support for positive integers only. [Answer] # Retina 0.8.2, ~~31~~ 22 bytes Byte count assumes ISO 8859-1 encoding. ``` .+ $* (?!(..+)\1+$).\B ``` [**Try it online**](https://tio.run/##K0otycxL/P9fT5tLRYtLw15RQ09PWzPGUFtFUy/G6f9/QwMA) - Input much larger than 2800 either times out or runs out of memory. ### References: [Martin's range generator](https://codegolf.stackexchange.com/a/58682/34718) [Martin's prime checker](https://codegolf.stackexchange.com/a/57618/34718) [Answer] ## PowerShell v2+, 98 bytes ``` param($n)if($j='001'[$n]){}else{for($i=1;$i-lt$n){for(;'1'*++$i-match'^(?!(..+)\1+$)..'){$j++}}}$j ``` *Caution:* This is **slow** for large input. Basically the unary-based lookup from [Is this number a prime?](https://codegolf.stackexchange.com/a/57636/42963), coupled with a `for` loop and a `$j++` counter. A little additional logic on the front to account for edge cases input `1` and `2`, due to how the fenceposting works in the `for` loops. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 3 bytes ``` !Æv ``` [Try it online!](http://jelly.tryitonline.net/#code=IcOGdg&input=&args=) ### How it works ``` !Æv Main link. Argument: n ! Compute the factorial of n. Æv Count the number of distinct prime factors. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13 11 10 9 8 7~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) **Using no built-in prime functions whatsoever** -1 byte thanks to @miles (use a table) -1 byte thanks to @Dennis (convert from unary to count up the divisors) ``` ḍþḅ1ċ2 ``` **[TryItOnline](http://jelly.tryitonline.net/#code=4biNw77huIUxxIsy&input=&args=MTA)** Or see the first 100 terms of the series `n=[1,100]`, also at **[TryItOnline](http://jelly.tryitonline.net/#code=4biNw77huIUxxIsyCsKzw4figqw&input=)** How? ``` ḍþḅ1ċ2 - Main link: n þ - table or outer product, n implicitly becomes [1,2,3,...n] ḍ - divides ḅ1 - Convert from unary: number of numbers in [1,2,3,...,n] that divide x (numbers greater than x do not divide x) ċ2 - count 2s: count the numbers in [1,2,3,...,n] with exactly 2 divisors (only primes have 2 divisors: 1 and themselves) ``` [Answer] # JavaScript (ES6), ~~45~~ 43 bytes ``` f=(n,x=n)=>n>1&&(--x<2)+(n%x?f(n,x):f(n-1)) ``` A modification of my ~~36~~ ~~35~~ 33-byte primality function (1 byte saved by @Neil, 2 by @Arnauld): ``` f=(n,x=n)=>n>1&--x<2||n%x&&f(n,x) ``` (I can't post this anywhere because [Is this number a prime?](https://codegolf.stackexchange.com/q/57617/42545) only accepts full programs...) ### Test snippet ``` f=(n,x=n)=>n>1&&(--x<2)+(n%x?f(n,x):f(n-1)) ``` ``` <input type="number" oninput="console.log('f('+this.value+') is '+f(this.value))" value=2> ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 5 bytes Assumes that prime factorization builtins are allowed. Code: ``` LÒ1ùg ``` Explanation: ``` L # Get the range [1, ..., input] Ò # Prime factorize each with duplicates 1ù # Keep the elements with length 1 g # Get the length of the resulting array ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=TMOSMcO5Zw&input=NQ) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḷ!²%RS ``` This uses only basic arithmetic and Wilson's theorem. [Try it online!](http://jelly.tryitonline.net/#code=4bi2IcKyJVJT&input=&args=MTAw) or [verify all test cases](http://jelly.tryitonline.net/#code=4bi2IcKyJVJTCsW8w4figqxH&input=&args=MSwgMiwgNQ). ### How it works ``` Ḷ!²%RS Main link. Argument: n Ḷ Unlength; yield [0, ..., n - 1]. ! Factorial; yield [0!, ..., (n - 1)!]. ² Square; yield [0!², ..., (n - 1)!²]. R Range; yield [1, ..., n]. % Modulus; yield [0!² % 1, ..., (n - 1)!² % n]. By a corollary to Wilson's theorem, (k - 1)!² % k yields 1 if k is prime and 0 if k is 1 or composite. S Sum; add the resulting Booleans. ``` [Answer] # C# 5.0 78 77 ``` int F(int n){int z=n;if(n<2)return 0;for(;n%--z!=0;);return(2>z?1:0)+F(n-1);} ``` Ungolfed ``` int F(int n) { var z = n; if (n < 2) return 0; for (; n % --z != 0;) ; return F(n - 1) + (2 > z ? 1 : 0); } ``` [Answer] # Regex (Perl / Java / PCRE), 32 bytes ``` ((?=(\2?+x*?(?!(xx+)\3+$))xx)x)* ``` [Try it online!](https://tio.run/##RU7dSsMwGL3fU8QRlnxLu6YVb0yzdjBvvfLOjjBlg0DcalIhEuKlD@Aj@iI1q4I3h@87nL/@YM3N@PKOsBUomPPz3iBciPTKert52Kzj7Hi2FDvJRb0WEJA@pg9Cb/VpQPPuNBcRtUa63uiBkpxk7u3JDcmisrzMSji8XkTNP8sTD7dYgbhkudS4t62pKwiteSx3MiHfiThDaGrWfwTWtZwE6WIMQvJS4onHGuRHgW0BAbvFYto1zUqbS/E7E@sVQd@fX4isaMtSWt7mCUHEGJW6u98qNVLaSNpVDfPLhjZX1HsG3TXDAN6Dh@U48rzi/Ac "Perl 5 – Try It Online") - Perl [Try it online!](https://tio.run/##bVLLbtswELz7KzZCA5OyzcjprYxgtEULFGjaIjk6PtASZTOhKJWkYjlBrv2AfmJ/xF3K7CNAdFnt7nCWM9xbcS9mt@XdQdVtYz3cYs5Uw1IO/1c6r/SLNSs3ssfOqO3WWhVQaOEcXApl4BFizXnhMdw3qoQaO@TaW2U2IOzGLVcU/NY2Owcf@kK2XjV4cgTwUWkJVW7kbvglCSuaUjLsJ5S/66pKWlleSVFKC@sB9rxI/pyMaUUpj3Pd1PPdNvAT4vI1ahDlZ2UkofQkN53WVFXEMfm9E9qR5CxN04TSx@fQIwMh/kWCR2TwfxmQ4AwZ1oi7426Sj2/MOETPn461p2/Ce2kN2Dz@odq6DQMc5ejGumm0FAYe8goZJYfrQhiD0pVpOw85BLWxRq73zsuaKUM5RJ0DjG2F@yJ7j9ccLAaIhmi8O3IcQQYRUWLsL1egsR1QzLVaeZLM8BEQ78Fk2PlkPK6BZa2wTmJC9DJb0SmY@YtNpqXZ@O3FOSwgIOENhvkKGYutsMtVH/UMmZmvOLy1Vuwdq5TWpJ@O@/FgCkDV2KANr5GbjIO5yM0cw2SCAi@FL7boUI1sltXHjAyba3DB3yP5cWPYzoqWxBFF0@6/VlfCbCROyqaG0qC0AlLjeFOid@FtH2g0uUHHdlZ5ScKjUv6Qe9uF9/nXbtFDX5HktIRfP37CaZmgM1Oo2cY2XUsyGv1Aav4UvlHYuAMhi5zcnC8mfbogixPS9xN683ryitK@pz1ND2GrDtnsPMt@Aw "Java (JDK) – Try It Online") - Java [Try it online!](https://tio.run/##XVDNatwwEL7nKaZC4Jm11ut105ZFa3xpC4HSQ9NbHITjamNTWxayAoaQax@gj9gX2Y6X9NLDDPP3fd/M@M6fj5XvPMgAJYidgAx8sI8mWD80rcVkl20qY7pmiKadRt8PNtRYk66/7eZEQcJ24qJ5tOuAi9bFGY35fPPlkzGkYE9MycQaeteb2UYUvg02e2janzGwM0M/9lEoENfF4frw/kNxeCdIX52mgLIvcy2H8sTsM95@/3jzlTQ9Q39COdzNMQzWcUTb/X1ZitoJ4uH56YE7XFa52u5pxdvFD9MPi2IrFI9rxrfTk4sr9lgw6I4J2Of3@grgouxec@mO5aXPUZoSSwNePjQ2se1QBsVi67tsEzFZEiUdKTkSwfO6ZU@27aZ1NQ18zV7DmoN0mYA/v36DyP5dMbIa6ZeX/56NpM@IVYl1UaXLpsLqDS5LSvXbVBItCy20OZ/zbZHnfwE "PHP – Try It Online") - PCRE Takes its input in unary, as a string of `x` characters whose length represents the number. Returns its output as the length of the match. ``` # tail = N = input value; no anchor needed, as every value returns a match # Count the number of primes <= N, from the largest to the smallest prime. ( # J = 0 (?= # \2 starts at zero, and on each subsequent iteration, contains the difference # N-P-(J-1) where P is the previously found prime, and J is the running total of # our prime count. ( \2?+ # Start from the previous value of \2, atomically so that it # can't be backtracked and started again from zero if the # following fails to match. This will make tail = P-1, where # P is the previously found prime. x*? # Advance as little as necessary to make the following match, # and add this to \2, while subtracting it from tail. (?!(xx+)\3+$) # Assert tail is not composite; note that this needs to be # inside group \2 for it to work in PCRE1 and older versions of # PCRE2, which atomicize groups that have nested backreferences ) xx # Assert tail is prime by eliminating the false positives 0, 1 ) x # J += 1; tail -= 1 )* # Iterate zero or more times, until there are no more smaller primes # Return J as our match ``` # Regex (Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) / Ruby), ~~41~~ 39 bytes ``` ((?=(?=(\3?))(\2x*?(?!(xx+)\4+$))xx)x)* ``` [Try it online!](https://tio.run/##PY5NTsMwEIX3OcVgIXUmf4pTVglWDpJmEYHbGjlOZBvhXoADcEQuEuwikGbx5ud987abv67muKtlW60Hd3OllRcZyje3mh6ssIyxHXEQqU7HgQhPbcgHHB4whIJOT8UjUQgUKN/j7ci7ik89KNFk59WCBmUStnb@VZkuAy107TatPLKKUQbqDFoa1PTcdqBHPgk9NlMGyWyS2c7mIlEZj2lB5a/iExWcIg8WcU9cOznblyvaElhguYnoxF7SSRKqg80mL/X3ieD9X6713dcfVnmJzls0VBzg@/MLDkVql5h2NkjxY/WvYw7am6ptmh8 "Python 3 – Try It Online") - Python `import regex` [Try it online!](https://tio.run/##PY5BasMwEEX3OcXEhFrj2EJ2u4orjGlM6SaFtDs7mJYojkAoRnGIuumyB@gRexFXdtrAMPAf/898c3r/6A1wWItG2JZqcYZl/ppTI9624QUuFk@Pq@d18ZC/FClIzlI476USoHgjuqNDO1BlFG849yrtpY6rklEaJZsUhN6OgB5bJTviRz5eAlQJ3XR7gveJM5Qu7UKXwARgdzCgQWoYIO0OtSQxQ0oH41WOh4hnvUAj8E8wI5DToWF7GpqN3yWPnTZSd6BDH36@vsEPZzfXAn@2/zWp62K1rOuekIwPU91miKRKbJCRbEqsnWN1N58hWosWg75nUcLYLw "Ruby – Try It Online") - Ruby This is a port of the Perl/Java/PCRE regex to flavors that have no support for nested backreferences. Python's built-in `re` module does not even support forward backreferences, so for Python this requires [`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/). ``` # tail = N = input value; no anchor needed, as every value returns a match # Count the number of primes <= N, from the largest to the smallest prime. ( # J = 0 (?= # \2 starts at zero, and on each subsequent iteration, contains the difference # N-P-(J-1) where P is the previously found prime, and J is the running total of # our prime count. (?=(\3?)) # \2 = \3 (or 0 if \3 is unset), to make up for the lack of # nested backreferences ( \2 # Start from the previous value of \3 (as copied into \2). # This will make tail = P-1, where P is the previously found # prime. x*? # Advance as little as necessary to make the following match, # and add this to \3, while subtracting it from tail. (?!(xx+)\4+$) # Assert tail is not composite; note that this needs to be # inside group \3 for it to work in PCRE1 and older versions of # PCRE2, which atomicize groups that have nested backreferences ) xx # Assert tail is prime by eliminating the false positives 0, 1 ) x # J += 1; tail -= 1 )* # Iterate zero or more times, until there are no more smaller primes # Return J as our match ``` # Regex (.NET), 35 bytes ``` ((?=((?>\2?)x*?(?!(xx+)\3+$))xx)x)* ``` [Try it online!](https://tio.run/##ZZHNTuswEIX39yncCqke8qOk7DBukSIWSCCubpFYAAuTToslx4lsp5gGtvcBeERepLhJYYMlS2PNsec7x6VNytrgTosKbSNKJItX67DqWiv1mhS8qLWtFbLhfIvepf9w3SphLnxj0FoZBKxUwlpSddYJJ0uyqeWSXAupCYVuIwyx/Hy8o3TOw549TOfgj@d0PqLeR/BwEh0BeA8ejndjtpcbrvGFhDnoqU0X7ZN1JoyneWzTK9Rr95xMIe77N43bE6RFXTVS4RLYoCWKrWpDpXZE84xRxYsALpZXUiMFGHHdKsU0z6GTK6pnGRTpnZEOB0GP0XCVLholHZ0kE2D7t2SM7E@40Bw4ZtO3t1FopLfm9a8wFmlznz3GdRuk8Lv1fS3JBw3C91g6vtQboUJuRug1npIuex/HChgqi32Gvg9lMSQx8ZNYwo/FbbAozzgyGUWxj3hoQ3ctXPlMKm7SvqI@WFjRKuRZluHjeuPbX8a3PGc/TAGCfP7/IF0eYPwBPq4OBbD3Ye2yZJplXw "C# (.NET Core) – Try It Online") This is a direct port of the Perl/Java/PCRE regex. # Regex (.NET), 35 bytes ``` ^(?=(x*?(?!(xx+)\2+$)x)*x)(?<-1>x)* ``` [Try it online!](https://tio.run/##ZZFNbtswEIX3PQVtFPBM9APJyzK0CwhdFEjQog7QRX8AVh47BChKICmXsZJtD9Aj9iIuLTnZhKsh5g3ne4@1y@rW0snIhlwna2KbB@epGXqnzJ5VomqNazXx6X5HwedfaN9raT@EzpJzKgp4raVzrBmcl17V7NCqLbuVyjDA4SAtc@L9/PQT1gLC1RrWMwghwe/L5C0GvAoI6@usXMXyNOdnuRWGfrO4hwK4fNP/ct7G9VCmLr8hs/f32RLTsf@p82eCvGqbTmnaIp@0TPNda0EZz4woOGhRRXC5vVGGAHEmTK81N6LEQe3ArAqs8q9WeZoEI0YndL7ptPKwyBbIz2@plPibONBdOFbLx8dZbOR39uGztI6g@1b8SNs@SvF163ksKycN4fNamH80B6ljblaaPb1jQ/E0TzVy0o7GDMMYymZKYhEWqcIXi8doUV0L4ipJ0pCI2MbhVvr6njXC5mMFIVrYQRPzrOv4caPx4yvjR1HyF6YIwf79@cuGMsKEC3zaXArkT9M5ldmyKP4D "C# (.NET Core) – Try It Online") This uses the .NET feature of balanced groups to do the counting. It does not return a value for zero, but doing so only requires +1 byte (**36 bytes**): ``` ^(?=(x*?(?!(xx+)\2+$)x)*x|)(?<-1>x)* ``` [Try it online!](https://tio.run/##ZZHPTuMwEMbvPIVbIdVD/ijpEeN2pYgDEmhXFIkD7EredFosOU5kO8U07XUfYB@RFyluUrjg01jzjef3fS5tUtYGD1pUaBtRIlm8WYdV11qp16TgRa1trZAN9wf0Lr3HdauEufaNQWtlELBSCWtJ1VknnCzJppZLciekJhS6jTDE8h/jwx8659RfzOl8RL2P4HkanYOHC78DOr9K8lmoD2N21Buu8ZWEReipTRftX@tM2E/z2Ka3qNfuJZlC3Pd/Nu6IkBZ11UiFS2CDlii2qg2V2hHNM0YVLwK5WN5KjRRgxHWrFNM8h06uqJ5lUKSPRjocBD1Gw1W6aJR0dJJMgB3fkjGyszDQnDhm091uFBrpg3n7JYxF2jxlv@O6DVL43vocS/JBg/C5lo5v9EaoEJwReo2XpMv241gBQ2WxD9H3oSyGJCZ@Ekv4srgNFuUVRyajKPYRD23o7oQrX0jFTdpX1AcLK1qFPMsy/FxvfPvN@Jbn7IspQJD3f/9JlwcYf4KPq1MBbD@cQ5ZMs@wD "C# (.NET Core) – Try It Online") ``` ^ # tail = N = input number (?= ( x*? # Advance as little as necessary to make the following match (?!(xx+)\3+$) # Assert tail is not composite x # Eliminate the false primality positive of 0, and advance forward # so that the next prime can be found (if we didn't do this, the # regex engine would exit the loop due to a zero-width match) )* # Every time this loop matches an iteration, the capture group 1 # match is pushed onto the stack. This (balanced groups) is how we # count the number of primes. x # Eliminate the false primality positive of 1 | # Allow us to return a value of 0 for N=0 ) (?<-1>x)* # Pop all of the group 2 captures off the stack, doing head += 1 # for each one. This gives us our return value match. ``` --- I strongly suspect this function is impossible to implement in ECMAScript regex, even with the addition of `(?*)` or `(?<=)` / `(?<!)`. There doesn't seem to be room to multiplex the count and the current prime into a single tail variable, but I [don't know if this can be proved](https://cs.stackexchange.com/questions/137112/what-can-be-proven-regarding-the-differences-in-power-between-unary-ecmascript-r). Only one variable can be modified within a loop, such that must decrease by at least 1 on every step – and only \$O(n)\$ space is available; no variable may contain a value larger than \$n\$, and the language has no concept of arrays (although it is possible to take them as immutable input), only scalar variables (i.e. capture groups and the cursor position). So it would seem that calculating this function would require \$O({n^2\over log(n)})\$ scratch space, to multiplex the iteration count and current prime into a single number. While multiple loops in a row would be able to get closer to \$\pi(n)\$ than a single loop, the number of such loops could only be a constant; it seems that it would need to be able to grow with \$n\$ to be able to actually asymptotically calculate \$\pi(n)\$. And a nested loop would still have to distill all the information gained by its innermost loop into a single number \$\le n\$. But these things are just indications and vague evidence, not a proof. I have [set a bounty](https://codegolf.meta.stackexchange.com/a/21941/17216) regarding this open question. [Answer] # Pyth - ~~7~~ 6 bytes Since others are using prime factorization functions... ``` l{sPMS ``` [Test Suite](http://pyth.herokuapp.com/?code=l%7BsPMS&test_suite=1&test_suite_input=1%0A2%0A5%0A100&debug=0). [Answer] # Bash + coreutils, 30 ``` seq $1|factor|egrep -c :.\\S+$ ``` [Ideone.](https://ideone.com/VwKgoN) --- # Bash + coreutils + BSD-games package, 22 ``` primes 1 $[$1+1]|wc -l ``` This shorter answer requires that you have the bsdgames package installed: `sudo apt install bsdgames`. [Answer] ## Pyke, ~~8~~ 6 bytes ``` SmPs}l ``` [Try it here!](http://pyke.catbus.co.uk/?code=SmPs%7Dl&input=5) Thanks to Maltysen for new algorithm ``` SmP - map(factorise, input) s - sum(^) } - uniquify(^) l - len(^) ``` [Answer] # C#, 157 bytes ``` n=>{int c=0,i=1,j;bool f;for(;i<=n;i++){if(i==1);else if(i<=3)c++;else if(i%2==0|i%3==0);else{j=5;f=1>0;while(j*j<=i)if(i%j++==0)f=1<0;c+=f?1:0;}}return c;}; ``` Full program with test cases: ``` using System; class a { static void Main() { Func<int, int> s = n => { int c = 0, i = 1, j; bool f; for (; i <= n; i++) { if (i == 1) ; else if (i <= 3) c++; else if (i % 2 == 0 | i % 3 == 0) ; else { j = 5; f = 1 > 0; while (j * j <= i) if (i % j++ == 0) f = 1 < 0; c += f ? 1 : 0; } } return c; }; Console.WriteLine("1 -> 0 : " + (s(1) == 0 ? "OK" : "FAIL")); Console.WriteLine("2 -> 1 : " + (s(2) == 1 ? "OK" : "FAIL")); Console.WriteLine("5 -> 3 : " + (s(5) == 3 ? "OK" : "FAIL")); Console.WriteLine("10 -> 4 : " + (s(10) == 4 ? "OK" : "FAIL")); Console.WriteLine("100 -> 25 : " + (s(100) == 25 ? "OK" : "FAIL")); Console.WriteLine("1,000 -> 168 : " + (s(1000) == 168 ? "OK" : "FAIL")); Console.WriteLine("10,000 -> 1,229 : " + (s(10000) == 1229 ? "OK" : "FAIL")); Console.WriteLine("100,000 -> 9,592 : " + (s(100000) == 9592 ? "OK" : "FAIL")); Console.WriteLine("1,000,000 -> 78,498 : " + (s(1000000) == 78498 ? "OK" : "FAIL")); } } ``` Starts to take awhile once you go above 1 million. [Answer] # Matlab, 60 bytes Continuing my attachment to one-line Matlab functions. Without using a factorisation built-in: ``` f=@(x) nnz(arrayfun(@(x) x-2==nnz(mod(x,[1:1:x])),[1:1:x])); ``` Given that a prime `y` has only two factors in `[1,y]`: we count the numbers in the range `[1,x]` which have only two factors. Using factorisation allows for significant shortening (down to 46 bytes). ``` g=@(x) size(unique(factor(factorial(x))),2); ``` Conclusion: Need to look into them golfing languages :D [Answer] # Actually, 10 bytes This was the shortest solution I found that didn't run into interpreter bugs on TIO. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=O-KVl3JgUOKVnD5g4paRbA&input=MzA) ``` ;╗r`P╜>`░l ``` **Ungolfing** ``` Implicit input n. ;╗ Duplicate n and save a copy of n to register 0. r Push range [0..(n-1)]. `...`░ Push values of the range where the following function returns a truthy value. P Push the a-th prime ╜ Push n from register 0. > Check if n > the a-th prime. l Push len(the_resulting_list). Implicit return. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ÆRL ``` Jelly has a built-in prime counting function, `ÆC` and a prime checking function, `ÆP`, this instead uses a built-in prime generating function, `ÆR` and takes the length `L`. I guess this is about as borderline as using prime factorisation built-ins, which would also take 3 bytes with `!Æv` (`!` factorial, `Æv` count prime factors) [Answer] # PHP, ~~96~~ 92 bytes ``` for($j=$argv[1]-1;$j>0;$j--){$p=1;for($i=2;$i<$j;$i++)if(is_int($j/$i))$p=0;$t+=$p;}echo $t; ``` Saved 4 bytes thanks to Roman Gräf [Test online](http://sandbox.onlinephpfunctions.com/code/f2572d44a90f3d1e3c4d0b9f0bf839c102b97ea8) Ungolfed testing code: ``` $argv[1] = 5; for($j=$argv[1]-1;$j>0;$j--) { $p=1; for($i=2;$i<$j;$i++) { if(is_int($j/$i)) { $p=0; } } $t+=$p; } echo $t; ``` [Test online](http://sandbox.onlinephpfunctions.com/code/b7278074256589459c294fdeb1f7dc791acec6bb) [Answer] # Java 8, ~~95~~ 84 bytes ``` z->{int c=0,n=2,i,x;for(;n<=z;c+=x>1?1:0)for(x=n++,i=2;i<x;x=x%i++<1?0:x);return c;} ``` **Explanation:** [Try it online.](https://tio.run/##hZDBasMwEETv@Yq9FCTkGMvQS2QlX9Bccgw9qIpSNnXWRpaD4uBvd2U315LLwM5bmGEu5mbWTevocvqZbG26Dj4M0mMFgBScPxvrYD@fiwGWzTpwlZxxlaQLJqCFPRBomIb19rG86SIjXWaYRXVuPFNU6UFZoeNW7uSm4LMZNQmRoS4VVlFFHd9QiEruik3kyrvQewKrxknNOW3/VaecZ9ytwRNcU1F2CB7p@/hp@F/Jw70L7po3fcjbREJNjHLLJF8q/8vLF/z9BZcFf24yTr8) ``` z->{ // Method with integer parameter and integer return-type int c=0, // Start the counter at 0 n=2, // Starting prime is 2 i,x; // Two other temp integers for(;n<=z; // Loop (1) as long as `n` is smaller than or equal to the input `z` c+=x>1?1:0) // and increase the counter if we've came across a prime // (if `x` is larger than 0, it means the current `n` is a prime) for(x=n++,i=2;i<x;x=x%i++<1?0:x); // Determine if the next integer in line is a prime by setting `x` // (and increase `n` by 1 afterwards) // End of loop (1) (implicit / single-line body) return c; // Return the resulting counter } // End of method ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 13 [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 charater set") ``` 2+.=0+.=⍳∘.|⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wQjbT1bAyB@1Lv5UccMvRogDZQ4tMJQwUjBFAA "APL (Dyalog Unicode) – Try It Online") `⍳` **ɩ**ndices 1…N  ⧽ `∘.|` remainder-table (using those two as axes) `⍳` **ɩ**ndices 1…N `0+.=` the sum of the elements equal to zero (i.e. how many dividers does each have) `2+.=` the sum of the elements equal to two (i.e. how many primes are there) [Answer] # [MATL](http://github.com/lmendo/MATL), 9 bytes This avoids prime-factor decomposition. Its complexity is O(*n*²). ``` :t!\~s2=s ``` [Try it online!](http://matl.tryitonline.net/#code=OnQhXH5zMj1z&input=NTA) ``` : % Range [1 2 ... n] (row vector) t! % Duplicate and transpose into a column vector \ % Modulo with broadcast. Gives matrix in which entry (i,j) is i modulo j, with % i, j in [1 2 ... n]. A value 0 in entry (i,j) means i is divisible by j ~ % Negate. Now 1 means i is divisible by j s % Sum of each column. Gives row vector with the number of divisors of each j 2= % Compare each entry with 2. A true result corresponds to a prime s % Sum ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 12 bytes ``` (≢⊢~∘.×⍨)1↓⍳ ≢ ⍝ tally ⊢~ ⍝ index values not in matrix of composite numbers ∘.×⍨ ⍝ outer product of positive integers with themselves 1↓⍳ ⍝ range from 1–n less the first element ``` h/t [@adám](https://codegolf.stackexchange.com/users/43319/ad%C3%A1m) [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wSNR52LHnUtqnvUMUPv8PRHvSs0DR@1TX7UuxkorWDAlaZgCMRGQGwKxJbmQMLYwMAAAA "APL (Dyalog Unicode) – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/), 49 bytes ``` p(n,i){for(i=n;--i&&n%i;);return--n?p(n)+!--i:0;} ``` Assumes `n` is positive. [Try it online!](https://tio.run/##DYzBDoIwEAXP7VesJJBuYBPFmyv6I14IiHmJLqRBL4Rvr73OTGaQ4d3bK6UlWAPepjkGdKYiqCoroazxuX6jidg9N1wfsrocdU@w1X96WPjNGNlv3mVCUO/yhAKoo5MS6ErnVqmuwd65JeZoCkUp7Uhyo3J8WNEQGloCmNXv6Q8 "C (clang) – Try It Online") [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$ 4 \log\_{256}(96) \approx \$ 3.29 bytes ``` FAFL ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_UXTsgqWlJWm6FkvcHN18IEyoyIKFphAGAA) Port of Dennis's 05AB1E answer. #### Explanation ``` F # Push the factorial of the input AF # Get the unique prime factors L # Push the length of the list ``` [Answer] ## JavaScript (ES6), ~~50+2~~ ~~46+2~~ 43 bytes Saved ~~3~~ 5 bytes thanks to Neil: ``` f=n=>n&&eval(`for(z=n;n%--z;);1==z`)+f(n-1) ``` `eval` can access the `n` parameter. The `eval(...)` checks if `n` is prime. --- **Previous solutions:** Byte count should be +2 because I forgot to name the function `f=` (needed for recursion) 46+2 bytes (Saved 3 bytes thanks to ETHproductions): ``` n=>n&&eval(`for(z=n=${n};n%--z;);1==z`)+f(n-1) ``` 50+2 bytes: ``` n=>n&&eval(`for(z=${n};${n}%--z&&z;);1==z`)+f(n-1) ``` ]
[Question] [ [Inspired](https://chat.stackexchange.com/transcript/message/58359892#58359892) by [Wzl](https://codegolf.stackexchange.com/users/90614/wzl) Determine if a given square binary matrix has exactly one row or column consisting of entirely `1`s, and the rest of the matrix is `0`s. For example, these are all true: ``` 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 1 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 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 1 1 1 1 1 1 1 1 1 ``` And these are all false: ``` 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 1 1 1 1 1 1 1 0 1 0 0 0 0 1 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 0 ``` The reasons for the false ones: * More than one row * More than one row or column * There are `1`s outside the "all `1`s column" * There isn't a row or column of all `1`s (describes the last 4) You should take a square binary matrix of side length \$n \ge 2\$, in any reasonable format, and output 2 distinct, consistent values to indicate whether it has a single straight line. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. --- **Keep your golfing in your code, not your inputs/outputs**. I'm very liberal with the I/O formats, including but not limited to: * A multiline string * A list of lines * A 2D list (or matrix) consisting of two distinct consistent values (e.g. `0`/`1`, space/`'*'`, `5`/`'('`) * A flat array, and \$n\$, as separate arguments * Two distinct consistent values (e.g. `1`/`0`) to indicate the output * Erroring/not erroring * Two families of values, one of which consists of values that are truthy in your language and the other falsey (for example, natural numbers and zero) * etc. As a broad, general rule, so long as the input can be clearly understood and the outputs clearly distinguished, it's fair game. --- ## Test cases | Input | Output | | --- | --- | | ``` 000000000000000000000000000000000000000000000000000000000000000000000000111111111 ``` | true | | ``` 0000011111000000000000000 ``` | true | | ``` 1000100010001000 ``` | true | | ``` 0101 ``` | true | | ``` 0000000111111100000001111111000000000000000000000 ``` | false | | ``` 0100011111010000100001000 ``` | false | | ``` 0100110101000100 ``` | false | | ``` 1000010000100001 ``` | false | | ``` 000101000 ``` | false | | ``` 000000000 ``` | false | | ``` 001100010 ``` | false | | ``` 0100 ``` | false | [Answer] # [Python 2](https://docs.python.org/2/), 49 bytes Takes as input a 2D binary matrix \$ a \$, and its size \$ n \$. ``` lambda a,n:sorted(map(sum,a+zip(*a)))[-2:]==[1,n] ``` [Try it online!](https://tio.run/##rU7BbsMgDL37K7gFb6yCHiPlS5IcWEM0pIQgoIfu5zNDEjWrtNsssP38/Gz7R/pa3HUdm26d9Pw5aKaFq@MSkhn4rD2P91no92/r@ZtGxPbjWvdN0yrh@tXOnhpZfEQYl8BuOhpmXcaXmAbrLsHogSOBQHqKfrKJV53rXIU1bIKmhCdXIdAQT/U23f1kyhXWJcEsIst7bF6SRT0wH4hiIzV4wSbjeK4jrvIw@J9MHQZwKsCpbfegCvvbgVT5wcu0P/FrJPFpZ8nPvgRi5UZujsQKdlQ2Q@HlDo5fTpM/ "Python 2 – Try It Online") There may be shorter approaches, but this is what I could find for now. Please let me know if the algorithm is incorrect. ## Explanation Since there is exactly one line, there should be exactly one row/column which contains \$ n \$ ones. Furthermore, since every \$ 1 \$ in the matrix exists on that line, there can be no other row/column containing more than one \$ 1 \$. Since if there were another \$ 1 \$ existing somwhere not on that line, it would create a row/column with at least two \$ 1 \$s. Given this, it suffices to check that the two rows/columns with the largest number of \$ 1 \$s have counts of `[1, n]`. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` {z|}≡ᵛ+1 ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXV3@cOuERx3LH@7a8XBXZy2Qo5ZzePujpibrhzsXZT1q6k23VlKoqakJU1CqSgbKAhWB1FQ/atvwqKkFqFGppKg0VU@pBsRMS8wpBrJrQYp2bIOa97@6qqb2UefCh1tnaxv@/x8dHW2go4AdxeooDCdJQx0F7CgWJBuNXz2G6UQIgI01RDeTGB7MQTBrsTkRr8dwBAbpqkkQhjuaYCgaopuFTwDNWISZBhgGovGQwwwRwMi@xVCChYkeFwbocYHiS7TQQeMRTBFwtYZovNhYAA "Brachylog – Try It Online") ``` {z|} Either the rows or the columns ≡ᵛ are all the same list +1 which sums to 1. ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 47 bytes ``` ->m,n{m.uniq[1]?m-[[0]*n]==[[1]*n]:m[0].sum==1} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5XJ686V680L7Mw2jDWPlc3OtogVisv1tY2GsgHMqxygQJ6xaW5traGtf8LFNKigSp0DHQMY3XQ6Fgd41guXAoMCSkAQkImYCgwgOvUiTaEW/EfAA "Ruby – Try It Online") ### Explain please: Split the two cases: * If m has at least 2 different rows, remove all zeros and check if we are left with a single row consisting of ones. * If not (all the rows are the same), check that the sum of the first row is one. [Answer] # [Factor](https://factorcode.org/) + `math.unicode`, 59 bytes ``` [ [ concat Σ = ] keep dup flip [ all-equal? ] bi@ or and ] ``` [Try it online!](https://tio.run/##3VRLTsMwFNznFHMBooaPECAoO8SGDWJVdWEct1h1bWM7UqvIp@E@XClYBERI7dAgsSFeJJl5fmPPe3oLQp0yzcP97d3NOYi1ilqsmJFMwLLniknKLNbEPeWV5FSVDNow57bacOm@QnK2cYZYLI2qNJdLXGRZnSE8Nc7QfrV/k53l/zVb7KyW9eH9YdBJwqB4Gv9j7H5o5wDH3w5QROV/g3UkDnt37N8jYsvpQN@kHfZ/tmccM1DfYkR9i6jcPmiyvp@BfflJQjyNdSSOIsXqN0bM6NGJhpERHdfd4psZZqBKUuLw@oJLzMMUZBplpbEQXAeWCHEQxh0R00A@8msoAyJLzJs65HgfnVdropE3bw "Factor – Try It Online") Takes \$n\$ and a matrix of \$1\$s and \$0\$s, in that order. * `[ concat Σ = ] keep` Is the sum of the matrix equal to \$n\$? * `dup flip [ all-equal? ] bi@ or and` And are all the rows in either the original matrix or its transposition equal? [Answer] # JavaScript (ES6), 46 bytes *Thanks to [@PertinentDetail](https://codegolf.stackexchange.com/users/103228/pertinentdetail) for a bug fix* Expects a multiline string with a trailing line feed. Returns a Boolean value. ``` s=>/^(0*10*\n)\1*$|^(0+\n)*1+\n[^1]*$/.test(s) ``` [Try it online!](https://tio.run/##rVBNj8IgEL3zK4gxKWBE5mzqbfcPeFzWpKnUxTTgMuwmRve3V1rUVBNvO4E3bz6YR2Zf/VZYB3uIc@e3pmvKDsvVYsOUACW04xrE9JzCWeICEn5s4FNMFzIajAx5F8z3jw2GFQ0WXAZTbd9ta9ZHVzPFZfTrGKzbMS7x0NrIJtppN@Gy8eGtqr8Y0nJFT4RSpLOSFtoVyxTU3qFvjWz9jjVJhS/JH@8AgCilhttDtn9icLPr6Jwgo7YrEhiqj0AU9Of@rdu4l/GzT69HogMf4@BSVeViBpLl4b6Q0Xb65AU "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` S;§ṢIṪ‘=L ``` [Try it online!](https://tio.run/##y0rNyan8/z/Y@tDyhzsXeT7cuepRwwxbn/8Pd2@xfdQw1/Bwu@Z/Axjgog7LEAa4uJAEuJCUQUkuQ7AsKsFlYAhCSCIGhjACWa0hQgOqvTj56DTYTLjr4FbBSIiVQHsMkV0AcQDYUAgHhsHuBlKp/9Vj8tT1svIz8zQyS1KLNDLzCkpLdNRT1TU19YoLcjJLNIAKgEo0AQ "Jelly – Try It Online") Slightly modified port of dingledooper's algorithm. ### How it works ``` S;§ṢIṪ‘=L Monadic link; input = matrix M S;§ Column sums of M ++ Row sums of M Ṣ Sort I Increments; (next - previous) for each adjacent pair Ṫ Last item ‘ +1 =L Equals the length of M? ``` # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ZEȯE×SS=L ``` [Try it online!](https://tio.run/##y0rNyan8/z/K9cR618PTg4Ntff4/3L3F9lHDXMPD7Zr/DWCAizosQxjg4kIS4EJSBiW5DMGyqASXgSEIIYkYGMIIZLWGCA2o9uLko9NgM@Gug1sFIyFWAu0xRHYBxAFgQyEcGAa7G0il/lePyVPXy8rPzNPILEkt0sjMKygt0VFPVdfU1CsuyMks0QAqACrRBAA "Jelly – Try It Online") Slightly modified port of chunes's algorithm. ### How it works ``` ZEȯE×SS=L Monadic link; input = matrix M ZE 1 if transpose(M) has all rows equal ȯE or M has all rows equal, 0 otherwise ×SS times column sum, and sum again (= times the sum of the entire matrix) =L equals the length of M? ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/mathematica/), ~~21~~ ~~13~~ 35 bytes ``` Norm@#==#2&&Norm@Eigenvectors@#>#2& ``` [Try It Online!](https://tio.run/##zVM9C4NADN39FQGh0w1nPygdLC5dS6GjOEgR66BSe3Qp/nar9azxzFkRKcWAyb3kmbyLsS@uQeyL6OIXoV0c0yx2TNs2l4vF2z9EYZA8gotIs7tj7svz4pRFiQAndJ9PzpQnZ391ZjHlyXN2vmXC3XmeQc2BazCn1pd8my6fhdj0nqxdq73UX/70utT0Ss2o6jACH45lD9tejxq9LMRD@bReEpdsHHMhT6dXq@pnviZ3Red237pcyUbeA1SXDKXx0nIGTQTsHfEakBiK1BnkukBLhq0l/gYaAGQC79cNgYhmQjXimFxdSQTNPwpIpIlsDVh1NZBAq9wHFZox1ZTVNPOINJ9GygZMWEPdIg1W/2CRihc) (Thanks to @ZaMoC for configuring this.) Takes `#` as the matrix, and `#2` as the square root of the side length, n. Returns True if the conditions are met, and False otherwise **Explanation** In Mathematica, the `Norm` function, when applied to a matrix, will perform a singular value decomposition and then identify and return, from among the resulting matrices, the element with the largest value. For most square binary matrices with n ≥ 2, the conditions will be met IFF the `Norm` of the matrix equals sqrt(n), i.e., if the following returns True: ``` Norm@#==#2& ``` However @Nitroden found an exception, which can be generalized as follows: If sqrt(n) is an integer, and the matrix contains a sqrt(n) x sqrt(n) submatrix that is all 1's, and has 0's everywhere else, its `Norm` will also equal sqrt(n). Thus, to eliminate those, I added an additional test: that the `Norm` of the `Eignevectors` of the matrix is greater than sqrt(n). My *Try It Online!* link contains all the OP's test matrices and, at the end, Norden's case plus three additional matrices of that form. These now all return False. Alas, Mathematica's `Eigenvectors` function is 12 bytes. Thanks to @Bubbler for the tip that my `If` wrapper was unnecessary. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 12 bytes ``` :∑$v∑Js¯Nt›= ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%3A%E2%88%91%24v%E2%88%91Js%C2%AFNt%E2%80%BA%3D&inputs=%5B%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%5D%2C%20%5B1%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%5D%5D%0A9&header=&footer=) Yay! Beating Lyxal by 1 byte with a different approach!!! -1 byte from @Lyxal himself thanks [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes Based on the first part of [Bubblers Jelly answer](https://codegolf.stackexchange.com/a/229886/64121), which uses dingledooper's algorithm. Input is a 2d matrix and the side length, output is `1` for truthy inputs and any other integer for falsy ones. This is the definition of truthiness in 05AB1E. ``` Dø«O{¥θα ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f5fCOQ6v9qw8tPbfj3Mb//6OjDXQUsKNYHYXhJGmoo4AdxcZyWQIA "05AB1E – Try It Online") or [Try all cases!](https://tio.run/##yy9OTMpM/X9o2aEVjxrmcXEdWqjOdW7LoYWPmtYAUTBXWWV65X@XwzsOrfavPrT03I5zG/@72J@boaSgcXi/ppLOfyUlJS4DGKASyxAGuLiQBLiQlEFJLkOwLCrBZWAIQlxopuHko9NAzUh2gtnIJJgCyhpAJCEEF8R2sKEQDgyDXWPABQwmAA "05AB1E – Try It Online") ``` D # push two copies of the input matrix ø # transpose one copy to get a list of columns « # concatenate to the list of rows O # sum each sublist { # sort the row and column sums ¥ # take consecutive differences θ # get the last one (largest value - second largest value) α # absolute difference with the second input ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` S;§>Ƈ1⁼LW$ ``` [Try it online!](https://tio.run/##y0rNyan8/z/Y@tByu2Ptho8a9/iEq/x/uHuL7aOGuYaH2zUj/xvAABd1WIYwwMWFJMCFpAxKchmCZVEJLgNDEOJCMw0nH50GakayE8xGJsEUUNYAIgkhuCC2gw2FcGAY7BqIGNhMiD1c6M4HYkMIwZX6Xz0mT10vKz8zTyOzJLVIIzOvoLRERz1VXVMz2krXMFavuCAns0QDqAqoThMA "Jelly – Try It Online") Uses Unrelated string's test suite. Fixed with some help from Unrelated string. ## Explanation ``` S;§>Ƈ1⁼LW$ S sums of columns ; concat with § sums of rows Ƈ keep the sums which are: > 1 greater than 1 ⁼LW$ = [length] ? ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ŒṪZEƇȧiɗJ ``` [Try it online!](https://tio.run/##y0rNyan8///opIc7V0W5Hms/sTzz5HSv/w93b7F91DDX8HC75sOd@x41rYn8bwADXNRhGcIAFxeSABeSMijJZQiWRSW4DAxBiAvNNJx8dBqoGclOMBuZBFNAWQOIJITggtgONhTCgWGwayBiYDMh9nChOx@IDSEEV@p/9Zg8db2s/Mw8jcyS1CKNzLyC0hId9VR1Tc1oK13DWL3igpzMEg2gKqA6TQA "Jelly – Try It Online") The *fourth* totally different Jelly 9 byter. Returns either 1 or 2 for truthy and either an empty list or the number 0 for falsy. Also the program structure is more convoluted. ### How it works ``` ŒṪZEƇȧiɗJ Monadic link. Input: the matrix M of size n ŒṪZ Take the transpose of multi-dimensional indices of 1 the result is a 2-row matrix X; in order to satisfy the condition, one of the rows must be all-equal, and the other must be identical to 1..n ....ɗJ A dyad with ^ as left arg and 1..n as right: EƇ Collect every row that is all-equal from X ȧ Chain onto Python's `and`... i Get 1-based index of 1..n in X, 0 if not found ``` [Answer] # [J](http://jsoftware.com/), 25 bytes ``` (1:0}0"0)e.],&(#\|."{])|: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NQytDGoNlAw0U/ViddQ0lGNq9JSqYzVrrP5rcnGlJmfkKxgq2CqkKSjpKRlY68UbKcSCDDDgMoABKrEMYYALZq8BVnsNaW4vHv9CVHMhmQEl8es1BGtFJfD7Es11OPnoNAFTDZH8AGYjk5r/AQ "J – Try It Online") Not the shortest (my previous translation of dingledooper's was a couple bytes shorter), but I wanted to come up with a different approach: * `(1:0}0"0)` Is the matrix with all ones in the first row and zeros elsewhere... * `e.` an elment of... * `],&(#\|."{])|:` All possible rotations of the input, and all possible rotations of its transpose, catted together? [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ,ZfJṁ=ⱮJƲ ``` [Try it online!](https://tio.run/##y0rNyan8/18nKs3r4c5G20cb13kd2/T/4e4tto8a5hoebn@4sw2INCP/G8AAF3VYhjDAxYUkwIWkDEpyGYJlUQkuA0MQ4kIzDScfnQZqRrITzEYmwRRQ1gAiCSG4ILaDDYVwYBjsGogY2EyIPVzozgdiQwjBlfpfPSZPXS8rPzNPI7MktUgjM6@gtERHPVVdUzPaStcwVq@4ICezRAOoCqhOEwA "Jelly – Try It Online") [Idea stolen from Razetime in TNB](https://chat.stackexchange.com/transcript/message/58362379#58362379) ``` , Pair the input with Z its transpose. f Filter the pair to elements contained in Jṁ=ⱮJƲ every matrix of the same dimensions with a single column of 1s. Jṁ Mold [1 .. len(input)] to the shape of the input. ⱮJ For each 1 .. len(input), = is each element equal to it? ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 25 bytes ``` #||#/.{a_..}:>Tr@a==1& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X7mmRvl9f7u@XnVivJ5erZVdSJFDoq2todr/gKLMvJJoZV27NIeQfNeKgqLU4uLM/DwH54zEosTkktSiYofgEqCa9OCCnEygQh0lLqVYMKFWF5ycmFdXzaVkAANc1GEZwoCSDtRwiBAXkkIICVJgCJZHIcD6gMoRBiBM5cLFR6MhZiDZDWYjkTAFQHkDiDSYgFrJBRZEcKEY5jIDJa7a/wA "Wolfram Language (Mathematica) – Try It Online") Returns `True` if the matrix has a single line, and non`True` otherwise. ``` #||# input OR its tranpose /.{a_..}:> replace lists of repeated elements with Tr@a==1 (is the sum of that element equal to 1?) ``` Then, any `Or` expression with `True` as an argument gets reduced to `True`. [Answer] # [Python 2](https://docs.python.org/2/), 43 bytes *Heavily based on [dingledooper's answer](https://codegolf.stackexchange.com/a/229880/16766), which you should upvote.* ``` lambda a,n:set(map(sum,a+zip(*a)))=={0,1,n} ``` [Try it online!](https://tio.run/##rU7BbsMgDL37K7gFb6iCHSvlS5YdWEM0pIRYQA/dtG/PDEnUrNJus8D28/OzTbf8MYeXZWi7ZbTTe2@FVeGcXJaTJZmuk7LPn57kk0XEtv3SyqjwvfiJ5phFuiUY5iguNjnhQ8GnlHsfTtHZXiKDyGKONPosmy50ocEzrIK2hjvXIPAQ4vprvtLo6gk@ZCU8oih7fFlSRG8gKDIlBm4gJUYXZKkjLno3@J/M7AZwKMChbfNgKvvbgTblwcO0P/FjZPFhZ82PvgZm9UqujsUGNlQ3Q@X1BvZfT9M/ "Python 2 – Try It Online") Or: ### [Python 3](https://docs.python.org/3/), 44 bytes: ``` lambda a,n:{*map(sum,a+[*zip(*a)])}=={0,1,n} ``` Saves bytes with set unpacking, but loses bytes because `zip` doesn't return a list. [Try it online!](https://tio.run/##rU5BjsMgDLz7FdyCU1SBequUlzQ90E2iRUoIAnpoq749NSTRZiv1Vgtsj8dj293i72gPU1fVU6@HS6OZFvb4KAfteLgOQu9O5d04Xmo847OqHlIoYZ@TGdzoIwu3AN3o2Y8OLTM24X2IjbF73@qGIwFPaoquN5EXta1tgUeYBVUOf1yBQEMc1U/x6vqWpyuMjYIZRJb2mLQkic7AnCeKd9TgBOtby1MdESe5GnwnU6sBbAqwaVs8qMz@dyBVevA27SN@jyTe7Mz51udArJzJ2ZFYwYLyZsi8XMD682nyBQ "Python 3 – Try It Online") ### Explanation In a truthy input, the sum of a row or column must be one of these three numbers: * \$0\$, if it is parallel to the line of \$1\$s * \$1\$, if it is perpendicular to the line of \$1\$s * \$n\$, if it is the line of \$1\$s Any number other than these three indicates the existence of multiple lines or a partial line. Furthermore, all three of these numbers must be represented among the list of sums: * If \$n\$ is missing, there is no row or column that contains all \$1\$s. * If \$1\$ is missing, there are multiple rows and columns containing \$1\$s. * If \$0\$ is missing, the input has two perpendicular lines of \$1\$s (as in the second falsey test case). Conveniently, we don't have to worry about the case of a \$1 \times 1\$ matrix, because we're given that \$n \geq 2\$. Therefore: ``` set( ) # The set of map(sum, ) # the sums of each a+ # row and zip(*a) # column == # must be exactly {0,1,n} # that set ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 32 bytes ``` ^(0*10*)(¶\1)*$|^(0+¶)*1+(¶0+)*$ ``` [Try it online!](https://tio.run/##K0otycxL/P8/TsNAy9BAS1Pj0LYYQ00tlRqggPahbZpahtpAIQNtoND//wYgwGUIAlwQNhIJAA "Retina 0.8.2 – Try It Online") Turns out to be much like @Arnauld's answer, except I wanted to solve it for no trailing newline instead. [Answer] # [Julia](http://julialang.org/), 37 bytes ``` x$n=(l=sum([x x'],dims=1))[l.>1]==[n] ``` [Try it online!](https://tio.run/##tZBBCsMgEEX3nmIWgSpI0QPYi4iLgBYsxoY4AdvLW2tIWrvvzGb@m/8ZmNsa/ChzKXmIigaV1onqDPlkuPVTUpIxHc4XaZTS0RR0CRMooJoI6PrvWkLXxHBd2b7bXL@gmUQ1iyPwnsUe/uKb6zjcUfmhhJHrfQEEH6E9g0At69McxgdF1uS8@Igh0l7hkPzTUeT1p8RFW14 "Julia 1.0 – Try It Online") uses [Razetime's approach](https://codegolf.stackexchange.com/a/229881/98541) [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 14 bytes ``` :ÞTJv∑s2Nȯ1?"⁼ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%3A%C3%9ETJv%E2%88%91s2N%C8%AF1%3F%22%E2%81%BC&inputs=%5B%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%2C%200%5D%2C%20%5B1%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%2C%201%5D%5D%0A9&header=&footer=) Another stealing of the python answer. ## Explained ``` :ÞTJv∑s2Nȯ1?"⁼ :ÞTJ # merge the input list with itself transposed. v∑s # sort the list that results from getting the sum of each item 2Nȯ # take the last two items of that list 1?"⁼ # and check for equality with the list [1, second_input] ``` [Answer] # T-SQL, 152 bytes Input is a table variable Returns 1 for true, 0 for false To save bytes, this can only handle matrix up to length 10 ``` SELECT top 1iif(x=replace(a,0,'')or sum(x)over()=x*2-1and a not like'%0%'and 0=min(a)over(),1,0)FROM(SELECT rank()over(order by a)x,*FROM @)c ORDER BY-x ``` **[Try it online](https://data.stackexchange.com/stackoverflow/query/1423953/is-there-a-single-straight-line-in-the-matrix)** [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 88 bytes ``` (load library (d _(q((M)(e 1(*(sum(map all M))(sum(map any M (q((M)(+(_ M)(_(transpose M ``` The solution is the anonymous function in the last line. [Try it online!](https://tio.run/##fcoxCoAwFAPQ3VNkTHXRS7j1DOWLDoVvra0OPX1VENxMlgTe4UNRn2Ot1E1mqJ@SpNJwhuNOWsMFA1vmc@UqEaIKa8z3Q4F9@Pjyju4GdDyShBy3vMBWjuAOckD/1OB33akX "tinylisp – Try It Online") Here's an ungolfed version that verifies all test cases: [Try it online!](https://tio.run/##zVK7EoMgEOz5iiuPTvID6dL5Dc45mBln8IkWfr0B4gPQmJSRZm@5W/Z2HMp6UqVu5xlVQxJUmffUT5yhLJ6QMUBFVS4JMOUMAItuJHUHYTBgNaqbBYB6rExJLZBSkHIes/VkWfu9hR8HYZLSaWEGjrAAh55q3Ta6WKZnp2aHO0DGEBOIjhn9R1JAdEwQvv2gJ1C5KJyE8AWu4PLgoh4bODV6WOe3ji/EauTj5sKfPC18iVUgCcZ9GOcUtLhiN@nnsqa3bxldRmC7FFvu23NR/K62P/QL "tinylisp – Try It Online") ### Explanation Define a helper function `_` that takes a matrix (list of lists) `M`: ``` (sum(map all M)) Number of rows that are all 1s (sum(map any M)) Number of rows that have any 1s (* ) Multiply those two numbers (e 1 ) Is the product equal to 1? ``` In other words, is there exactly one row that has all 1s, which is also the only row that has any 1s? Then our main function needs only apply `_` to the matrix and its transpose, and return truthy if either result is truthy: ``` (_ M) Test M (_(transpose M)) Test transpose(M) (+ ) Add the two results ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes ``` WS⊞υι∨∧⁼⌊υ⌈υ⁼¹Σ⌈υ⁼ΦυΣι⟦⭆⌈υ¹ ``` [Try it online!](https://tio.run/##TY2xDsIwDET3foVHRwoSmTsxgMQQUakjYohKRSyloU1j4O9DonaIB@t8z2cP1oThbVxKX0tuBLz6mWMfA/kXCgEdrxZZAom26bIZ8Rbw5J94Xti4FTV5mnhCFhK0@e06DztXEvpsVaiCF3JxDOV82aFC7ttrbeYqI0GJRw62KR1LNapUs@m6p8PH/QE "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a newline-terminated list of strings. Explanation: ``` WS⊞υι ``` Input the matrix. ``` ⁼⌊υ⌈υ All rows are identical ∧ Logical And Σ⌈υ The sum of a row ⁼¹ Equals literal `1` ∨ Logical Or υ Input array Φ Filtered where ι Current row Σ Is non-zero ⁼ Equals ⭆⌈υ¹ Row of 1s ⟦ As a 1-row 2D array ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~63~~ 55 bytes ``` {(F⍉⍵)+(F←{(1↑⍴⍵)=(+/,⍵)×+/∧/⍵})⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v1rD7VFv56PerZraQFbbhGoNw0dtEx/1bgEJ2Wpo6@uAGIena@s/6liuD2TXaoKI/2lAtY96@x51NT/qXQNUfmi9MUhf39TgIGcgGeLhGfw/TcFYwRgoZ6AAgoZgCGZzpSmYKJjAZWByUFkE5EKYYAhVByWBMkYKRlAZQyJMhPLRTISpAWIA "APL (Dyalog Unicode) – Try It Online") * changed approach * F used on input + input transposed ``` ×+/∧/⍵ ⍝ number of all 1s lines multiplied by (+/,⍵) ⍝ total 1s (1↑⍴⍵)= ⍝ equal to side length? ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~49~~ ~~45~~ 46 bytes inspired by [Arnauld's](https://codegolf.stackexchange.com/a/229896/80745) and [Neil's](https://codegolf.stackexchange.com/a/229900/80745) answers. +1 bytes with additional Test cases. ``` "$args "-match'^(0*10* )\1+$|^(0+ )*1+ [0 ]*$' ``` [Try it online!](https://tio.run/##tVPLasMwELzrKxajVpYfIF0DhXxDe@wL4ypNQW0Sy6aFJN/uqnq4iixILtnLanc8s7My2m6@RafWQsoRr@AO9mOGm@5dQVZ/Nn27Ji85KzgrgD7xEh90VQIteAmPDJ4LTMYjQsscoSrHfTeIChHmg1y34D4InY2fcBJ2osMJjXtWKp8OsKJ@7KqRKlg7cEYu6SaOZ3TZeYVLdDnjbsFEjizw2ZX6TnSY8yyNTawpx24CyHie9kxctPPpPkjjQYpx7n6sGzhzbXl/bQoHuIE9Ah1Y/GxF24u3CrD8@BJKvxb8aqFOqEH2unGrH9HSoMggpLZBTJU9DG0rlFoAzj2nFrt/aVrBvWkvvGZmB1jJ4/gL "PowerShell – Try It Online") * convert the arguments to a string with space char as separator * add the trail space char * match with regexp [Answer] # [GNU-APL](https://www.gnu.org/software/apl/), 34 bytes ``` {+/(⍺≡+/,⍵)∧(⍵∧.=⍺⍴1)∨((⍺⍴1)∧.=⍵)} ``` Input the size of the matrix, and the matrix itself. ``` ⍵∧.=⍺⍴1 finds the row with all ones, a1=1∧a2=1∧a3=1 ... (⍺⍴1)∧.=⍵ finds the column with all ones The disjunction of the above two ensures atleast one of them happends ⍺≡+/,⍵ ensures that only required numbers of ones are present ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~121~~ 119 bytes *-2 bytes thanks to ceilingcat* ``` l;e;r;o;a;f(m,n)int*m;{r=l=o=0;for(e=a=~0;r++<n;o|=*m,a&=*m++)~*m<<32-n?e&=!*m:++l;for(o-=a;a;a/=2)l+=a&1;r=l<2&&e^!o;} ``` This has entire rows stored in integer arrays, making the maximum matrix size 32. [Try it online!](https://tio.run/##vVFNj5swEL37V0yQwkLsiI@0qhpjrfZSqVIPlfbY3UoWcVpSMBFQNdJu9q@ntsFANqRVL0UJHmbmvXlvnC6/penplFNBK1pSTrdeQaSfyWZR0KeK5axkId2WlScYZy8hrTBOJC2f2aIg3FVvjP2XRZEkq3gpb4XLZotijXFuMOWSccXJAxb7OWbcjaiiTGLXFV9nJT2e1BwoeFNlhy@r@JGiuqmasvDS77xS/KDL0n9CAJpNf2XAIKTqSEBSwDgzVbAk2aOpm5SF7FrIzkJ2HWQMShIGEe3S2RY87QtmDG7CG79Lj/uf@/ZjOx5jCkFQ/8j2IMWvPJMC6doRoUbUzbmh9hCHvUgbsfHByOmc6@Ub4iC4bhn2lSpsPWd@eJAOGXS1UA2qRP0zbxRS3aepWl5d3PO6ViXbw3ot3eSevl7DfAOeOOjTV//DfPMg57WZqllunc939/fO2vlw9/GTyrWUpCck2q36Fe3wvxD/E6liVNsteCY9daFmy8gJ7aPI/sdXZB8tHr0nEClZYy1D14C@EhH0lozgUY@@FhD0ZgwIuxGtlpi8lnIueWzmj/npmKB3JBzPnvDa5y4j7fUVvEOHA3gcaK/hxHKGPhVZjdElYFhd79A0raaazs@LpsheglUw0WSndHehS8fTbw "C (gcc) – Try It Online") [Answer] # [jq](https://stedolan.github.io/jq/), 38 bytes Reads a 2D array, outputs a boolean. ``` (.+transpose|map(add)-[0,1])==[length] ``` [Try it online!](https://tio.run/##yyr8/19DT7ukKDGvuCC/OLUmN7FAIzElRVM32kDHMFbT1jY6JzUvvSQj9v//aC4FBaAoGozVGRLChjpoMJYrlgvVR2gK0YwjwIWZZohqFiEOwhFw@7C4DIc3sHiYFFUEhZAchzeEDFGNwMFFMw1hlgGaSagcrAGLphLMRfYBWhgiwhw5NLCpwWAiqzFEijskd2CLRJAgAA "jq – Try It Online") ]
[Question] [ Your task is to write a program or function. Its output/return value must follow these rules: * The program outputs `1` * The program repeated `n` times outputs `n` * The program backwards outputs `-1` * The program backwards and repeated `n` times outputs `-n` * A mix of forward and backward programs will output `number_forward - number_backward` Take the program `aB` for example. * `aB` should output `1` * `aBaB` should output `2` * `Ba` should output `-1` * `BaBa` should output `-2` * `aBBa` should output `0` * `aBBaBa` should output `-1` * `aaB`, `C`, or `​` would not need to be handled This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest in bytes per language wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` NC ``` **[Try it online!](https://tio.run/##y0rNyan8/9/P@f9/AA "Jelly – Try It Online")** Or see all [test-cases](https://tio.run/##y0rNyan8///h7i1lj5rWGPz//9/PmcvPGUg4@wERkPBzhhLOfgA "Jelly – Try It Online"). ### How? In Jelly any sequence of monadic atoms forms a monadic chain which simply applies those monadic atoms in turn from left to right, starting with the value of it's left argument. When a full program is run with no arguments zeros are implicitly supplied as necessary, i.e. `main_link(0)` is called. As such `NC` is `C(N(0))` and `CN` is `N(C(0))`. ``` NCNC ... CN ... NC - Main Link: no arguments N - negate((implicit)0) -1 * 0 = 0 C - complement(that) 1 - 0 = 1 N - negate(that) -1 * 1 = -1 C - complement(that) 1 - -1 = 2 ... - ... - ... = a C - complement(a) 1 - a = 1 - a N - negate(that) -1 * (1 - a) = a - 1 ... - ... - ... = b N - negate(b) -1 * b = -b C - complement(that) 1 - -b = b + 1 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes I wonder if 2 bytes is possible in some language (I suspect that'd require it to consider the parity of the positions of the commands). ``` ‘ḷ’ ``` Explanation: `‘` increments, `’` decrements, and `ḷ` takes the left one, and for some magic reasons, when repeated, the program works as requested. [Try it online!](https://tio.run/##y0rNyan8//9Rw8yHO7Y/apgBRGDGTLwMqOL//wE "Jelly – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/), 39 Thanks to: * @pxeger for `s/EXIT|TIXE/0/` * @Sisyphus for `s/0 # 0/0/` ``` trap echo\ $[++a] 0 ]a--[$ \ohce part ``` [Try it online!](https://tio.run/##jY/BCoMwEETv@xVzEISKsR8gvbXXfoB6WKMlUEokDW3/PrUidVNEetvZeTPLtnw3QbNHWSI9nk8pDrhY92TXqdEh73hAr42tkVRZxg32aDjPqwS1NbrHwM5TGJNErn@gFOmxqmV9nRXR54xwI3AWy26iRTyal2J54Kc/DszGn/xmNn7K3GwHzl7YTVoV4gdVSPZrrRKr5OZSmOEN "Bash – Try It Online") [Answer] # Polyglot [Japt](https://github.com/ETHproductions/japt), R, Applescript, 5 bytes All credit for this one goes to @DanielSchepler. Daniel, if you open a duplicate answer to this, I will happily delete this one. ``` 0+1-0 ``` I don't know Japt at all, but this is just simple arithmetic evaluation. The result of the last evaluation is output at the end of the program by default. Japt was the first language that I found that satisfied this, but I'm sure there are others. Forward (1): [Try it online!](https://tio.run/##y0osKPn/30DbUNfg/38A "Japt – Try It Online") Forward-Backward-Backward-Forward-Forward-Backward-Backward (1):[Try it online!](https://tio.run/##y0osKPn/30DbUNfAQNdQG0qAuahi//8DAA "Japt – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-0777p`, 13 bytes ``` ++$_;#;_$-- ``` [Try it online!](https://tio.run/##K0gtyjH9/59LW1sl3lrZOl5FV5fr//9/@QUlmfl5xf91fU31DAz/6xqYm5sXAAA "Perl 5 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ¾¼.¾ ``` [Try it online - 1x forward: `1`](https://tio.run/##yy9OTMpM/f//0L5De/QO7fv/HwA). [Try it online - 1x backwards: `-1`](https://tio.run/##yy9OTMpM/f//0D69Q3sO7fv/HwA). [Try it online - 3x forward: `3`](https://tio.run/##yy9OTMpM/f//0L5De/SABAr1/z8A). [Try it online - 3x backwards: `-3`](https://tio.run/##yy9OTMpM/f//0D69Q3sO7UOl/v8HAA). [Try it online - 1x forward + 1x backwards: `0`](https://tio.run/##yy9OTMpM/f//0L5De/SAxD69Q3sO7fv/HwA). [Try it online - 2x forward + 5x backwards + 1x forward: `-2`](https://tio.run/##yy9OTMpM/f//0L5De/SABIzSO7SHEAVW@f8/AA). **Explanation:** The *1x forward* program does the following: ``` ¾ # Push the counter variable to the stack (0 by default) ¼ # Increment the counter variable . # No-op, because `.¾` doesn't exist as 2-byte command, so it just ignores this ¾ # Push the counter variable to the stack (which is 1 now) # (implicitly output the top of the stack as result) ``` The *1x backward* program does the following: ``` ¾ # Push the counter variable to the stack (0 by default) .¼ # Decrement the counter variable ¾ # Push the counter variable to the stack (which is -1 now) # (implicitly output the top of the stack as result) ``` Any combination of these two programs after one another increments and decrements the counter variable, but only the last value pushed to the stack is output implicitly at the very end. [Answer] # [R](https://www.r-project.org/), 26 bytes ``` F+ 1->F#F=FF FF=F#F>-1- +F ``` [Try it online!](https://tio.run/##K/r/302by1DXzk3ZzdbNjcsNSCq72eka6nJpu/3/DwA "R – Try It Online") [!enilno ti yrT](https://tio.run/##K/r/302bS9dQ185N2c3WzY3LDUgqu9npGnJpu/3/DwA "R – Try It Online") [Twice backwards and four times forwards](https://tio.run/##K/r/302bS9dQ185N2c3WzY3LDUgqu9npGnJpu@GVwSKhS3WZ//8B "R – Try It Online") A very different (and shorter) approach to [Giuseppe's R answer](https://codegolf.stackexchange.com/a/216464/86301) (in which he predicted that this answer was coming!). `F` is initially a shorthand for `FALSE` and so gets coerced to `0`. When the program is run forwards, we use rightwards assignment to get `F=F+1` and `FF=F`. When concatenated with itself, the program becomes ``` F+ 1->F#F=FF FF=F#F>-1- +FF+ 1->F#F=FF FF=F#F>-1- +F ``` [Try it online!](https://tio.run/##K/r/302by1DXzk3ZzdbNjcsNSCq72eka6nJpu@GW@f8fAA "R – Try It Online") and so the second time, we are doing `F=+FF+1` which also increments `F`. When run backwards, the only difference is that we use `+-1` instead of `+1`. When the final line is run, we print `+F`. [Answer] # [C++ (gcc)](https://gcc.gnu.org/), ~~324~~ ~~325~~ 323 bytes Note the leading and trailing newlines. Thanks to [Jonathan Allen](https://codegolf.stackexchange.com/users/53748/jonathan-allan) for spotting the need for a leading newline. ``` #ifndef M// #define M(a,b)a##b// #define W(z,x)M(z,x)// #import<cstdio>// int n;struct X{X(int d){n+=d;}};main(){printf("%d",n);}// #endif// X W(a,__LINE__)=1;//;1-=)__ENIL__,s(W X //fidne# //};)n,"d%"(ftnirp{)(niam;}};d=+n{)d tni(X{X tcurts;n tni //>oidtsc<tropmi# //)x,z(M)x,z(W enifed# //b##a)b,a(M enifed# //M fednfi# ``` [Try it online!](https://tio.run/##Tc4/y8IwEAbwvZ8iNAgJRoJzrJuDYFzbLaT583JDr6WNIJZ@9r6Jk8vx8IPn7tw0nf6c2/eKQkQfItFSVjQHwEA0s6LnltL@B1v2EW@uv7MwDNM4p4tbkofxmgUwEVRLml8ukW7tWAHPVzw2Xm2bGiwg4@s0Z4@sPvhaIFdb2RXQQ8yhy1esMOZxf96M4c1ZSanOp4Ybc3veH8aIhbWkq6SM4DHQHDbFUdT@ULOYEOZp5QzBDuWgb464ck@ys/wPSe41p0Vhgdy8juDT4i5pHqcByi7@Fh@mv7MlASEGX7in1PJeWKZ/UJMcMObevv8D "C++ (gcc) – Try It Online") [aBaB](https://tio.run/##7dA9q8MgFAbgvb9CIgWlFuls061DoemabGI0Xs6QEzEWSkN@e6526n7XuxxeHjgfHBvC8cfabdtR8OgGTxopdzQHwIE0zIieG0r7L2zZW7x486mFYQxTTGc7JwfTJQtgIqjmFJ82kW7pWAHHFzzUTq2rGg0g40uI2T2r9q4SyNVaZg3owOfQ5S1GaH2/Pa5a8/qkpFSnY821vj5ud63FzFrS7aT04HCgOayKo6jcvmI@IcSwcIZgxrLQ1QdcuCPZWb6HJPuMaVZYIHdeJnBptucUpzBCmcVf4s2aT23JgOAHV7in1PBeGNZ8YUNyQJ/7/l/45xdu2y8 "C++ (gcc) – Try It Online") (2) [Ba](https://tio.run/##Tc4/y8IwEAbwvZ8iNAgJRopzrJuDYFzbLaT583JDr6GNIJZ@9r6Jk8vx8IO752yMpz9r972iEND5QFTTVDQHQE8UM2LghtLhBzv2EW@uvrMwjHGa08UuycF0zQKYCMolzS@bSL/2rIDjKx5bJ7dNjgaQ8TXO2QOrD64WyOVWbnl0EHLoc8sitH7cnzeteXs6y6aR55ZrfXveH1oLwzrSV00TwKGnOWySo6jdoWYhIcxx5QzBjKXQtUdcuSPZWf6HJPua0yKxQN68TuDSYi9pnuII5RZ/iw9T39kRjxC8KzxQaviQq9UPKpIDhry37/8 "C++ (gcc) – Try It Online") (-1) [BaBa](https://tio.run/##7ZC9isMwEIT7PIWwCEhEQaRWnC5FIE5rd8LWz7GF10JWIMT42X1SqvTXXjMMH8zMsiaE448x27aj4NE6TxopdzQbQEca1ouB95QOX7Blb/HizUcLhjFMMZ3NnCxMl0wAE0E1p/g0iXRLxwqwfMFDbdW6qrEHZHwJMXPPqr2tBHK1li6HFnw2XV6Zhdb32@OqNa@PJyWlOtVc6@vjdtda9Kwl3U5KDxYdzWZVHEVl9xXzCSGGhTOEfiyDtj7gwi3JnOV7SDLPmGaFBeTkZQKbZnNOcQojlC7@Em/WfLQlDsE7W/BAac@HPN18wYZkgz7n/l/45xdu2y8 "C++ (gcc) – Try It Online") (-2) [aBBa](https://tio.run/##zZDBqoMwEEX3fkUwFBIaCV2ndtdFoXaruxAT85iFo2gKpeK326Rv4yd0M1wO3Jnh2HEs/qzdtoyCR9d5UkmZ0RgAO1IxI1puKG13sGZv8eLVdyYM/ThM4Wzn4GC4RAIYCKo5TE8bSLM0LAHHFzyWTq2r6g0g48s4Re5ZfnC5QK7WtKtDBz6GJl4xQuv77XHVmpcnJaU6FSXX@vq43bUWM6tJk0npwWFHY1gVR5G7Q858QJjGhTME06eDrjziwh2JnMV/SLDPKcwKE4jNywAuzPYcpmHsIe3iL/Fm1XfWpEPwnUu4pdTwVhhW7WBFYkAfe7@ncN4pLP4d7hSa31O4bR8 "C++ (gcc) – Try It Online") (0) [BaaB](https://tio.run/##zZDBqoMwEEX3fkUwFBIaCV2ndtdFoXaruxAT85iFo2gKpeK326Rv4yd0M1wOzNzh2HEs/qzdtoyCR9d5UkmZ0RgAO1IxI1puKG13sGZv8eLVdyYM/ThM4Wzn4GC4RAIYCKo5TE8bSLM0LAHHFzyWTq2r6g0g48s4Re5ZfnC5QK7WdKtDBz6GJrbMQuv77XHVmpfFSUmpTiXX@vq43bUWhtWkyaT04LCjMayKo8jdIWc@IEzjwhmC6VOhK4@4cEciZ/EfEuxzCrPCBOLmZQAXZnsO0zD2kG7xl3iz6jtr0iH4ziXcUmp4G6urHaxIDOjj3u8pNDuF/waLncL59xRu2wc "C++ (gcc) – Try It Online") (0) [aBBaBa](https://tio.run/##7ZDBioMwEIbvPkUwFBIaCT2n9tZDofaqtxATs8zBUTSFUvHZ3aR78RGWZS/Dzwf/zPDZcSy@rN22jIJH13lSSZnRGAA7UjEjWm4obXewZm/x4tVnJgz9OEzhbOfgYLhEAhgIqjlMTxtIszQsAccXPJZOravqDSDjyzhF7ll@cLlArta0q0MHPoYmXjFC6/vtcdWalyclpToVJdf6@rjdtRYzq0mTSenBYUdjWBVHkbtDznxAmMaFMwTTp4OuPOLCHYmcxX9IsM8pzAoTiM3LAC7M9hymYewh7eIv8WbVZ9akQ/CdS7il1PBWGFbtYEViQB97v0/hvFNY/DjcKTT/Cv@gwm37Bg "C++ (gcc) – Try It Online") (-1) ## Rundown Comments are used to make the code legal in forward as well as reversed form. ``` #ifndef M// ... #endif// ``` These are your basic guards to make sure we only define things once. ``` int n;struct X{X(int d){n+=d;}};main(){printf("%d",n);}// ``` Inside the guard we also declare the integer n, which will be automatically initialized to 0 by virtue of being a global, as well as define a struct X, whose constructor takes an integer value to add to the global n. The `main()` function simply prints the value of n. `main()` is run after all global variables have been sorted out, so we use the declaring of globals as a way to alter that value of `n` before `main()` is entered. This requires a way to declare an arbitrary amount of variables, leading to: ``` #define M(a,b)a##b// #define W(z,x)M(z,x)// ``` The main magic of the stew: Helper macroes that allow the gluing of tokens together in a very useful way. Calling `W(a,b)` will yield the token `ab`, with the potent twist of evaluating `b` as a macro first, which makes these kinds of things possible: ``` #define M(a,b)a##b #define W(z,x)M(z,x) #define b 10 int W(a,b); // This makes an int called "a10" ``` We combine this with the special preprocessor macro `__LINE__` which always expands to the current line number, allowing us a way to produce an arbitrary amount of variables having unique names. ``` X W(a,__LINE__)=1;//;1-=)__ENIL__,s(W X ``` Suppose we are at line 553; this will then declare a variable `a553` of type `X`, running its constructor with the argument 1. The reversed version is identical, save for using -1 instead. Our preprocessor guards make sure the above line and its reverse are the only things repeated. [Answer] # [Nim](http://nim-lang.org/), 115 bytes ``` when not declared i:#1=-i var i=0;addQuitProc do:echo i#i ohce:od corPtiuQdda;0=i rav i+=1#:i deralced ton nehw ``` There is a leading and trailing newline. The second line has a trailing space. [Try it online!](https://tio.run/##Dc1BCoQwDAXQfU8R6HIY0G2ld9AjhCTQD04DoerxO17gvY7fnOlp1qn7IDU5OUwJJa/1i0Q3B6EuG6seF8YeLqReTJoTMsibWHEl8dgHrkOVt6WCgm9K@NQ1F7xs8CkvO/x9rD1pzj8 "Nim – Try It Online") [Try it online!Try it online!Try it online!](https://tio.run/##5c3BCcMwDAXQu6f44GMoJFcH75CMYCSBBakFwknGd71HF3iv6XeM8FZpaNbBQldxYWiKW/5owFMcmte9MJ@39sONwJaEqkGjwipJMgaZH13vk7nsa1Z4eRB0yVtMOlkvF02223ykvuE/yjF@ "Nim – Try It Online") [!enilno ti yrT](https://tio.run/##Dc1BCoQwDAXQfU8R6HIY0G2ld9AjhCTQD04DoerxO17gvY7fnOlp1qn7IDU5OUwJJa/1g0Q3B6EuG6seF8YeLqReTJoTMsibWHEl8dgHrkOVt6WCgm9K@NY1F7xs8CkvO/x9rD1pzj8 "Nim – Try It Online") [!enilno ti yrT!enilno ti yrTTry it online!!enilno ti yrT](https://tio.run/##zc/BCYUwDIDhe6cI9CiCXivdQUcISaABbSBUHb@vO7yLC/wff9Wr9/AWqVCtAQud6MKgKa550gAPOmheNmQ@bm27GwFbEioGGhWskCRjIPO96X0w47ZkBccHgs55jUlH1vGkkW02HClv@BA5/01OH7rs/Qc "Nim – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 41 bytes ``` $.+=1;END{exit!p$.}#}.$p!tixe{DNE;1=-.$ ``` [Try it online!](https://tio.run/##KypNqvz/n0tFT9vW0NrVz6U6tSKzRLFARa9WuVZPpUCxJLMitdrFz9Xa0FZXT4Xr/38A "Ruby – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~99~~ 91 bytes ``` l=readLines();`*`=grepl;1+sum("^l"*l-"^r"*l)#1-)r*'r^'-r*'l^'(mus;lperg=`*`;)(seniLdaer=r ``` [Try it online!](https://tio.run/##tc4xCoQwEIXh3mMkRTKRFKlDbuAZBgUHEUaRFzx/NouwneVWf/U@HprVAlnWaT@lespzmMsGuTSnsd6HN6wmaDSMHrIpEoIDu9ij7Pxx16yXYCt9mclXOfdpXQQFg8UL/YUdqwuIjtFDMVnSB9YfPKYXWtvwv9etfQA "R – Try It Online") -8 bytes thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)! [Tripled](https://tio.run/##1c4xCoQwEIXh3mMkxWQiKVKH3MAzDAoGEUaRFzx/NsvCdpZbbPVX7@OhWc0oyzrtZ6mO0@znvKFcmuJY78MZUeM1GEEP2xgYniAUelTIHXdNehVsuS8Tu1rOfVqXgozB4oF@wyRKHoEEPRyiZf3A@oXH@EBrG373@j/p1l4) [Reversed](https://tio.run/##tcwxCoQwEEbhPscwRTKRFKlDbuAZBgUHEUaRP3j@bBZhO8utXvU@NKsFsqzTfkr1lOcwlw1yaU5jvQ8/sA5B48DoIZsiITiwiz3Kzh93zXoJttLPTL7KuU/rIigwFi/0F3asLiA6Rg/FZEkfWH/wmF5obeZvtGntAw) [Forwards and Backwards](https://tio.run/##tc8xCoAwEETRPsdImh00RWrxBp5BEFxEWEUmeP6IhUXsU/7q8VmCjdRlnfZTs2BIXb4P2aiXiZ/N94b4Fd9CSBFg7zl7sUu5xbfsKznuPECynvu0LsqRLrAifgArgEBMAbAKsB/QpYqw4tpfuOYXrpQH) Yet [another iteration](https://codegolf.stackexchange.com/a/177886/67312) on [third time the charm](https://codegolf.stackexchange.com/questions/157876/third-time-the-charm/157943#157943). R has an odd but often useful (and not just for golfing) feature where data can be stored in the code, and read in as such. `readLines()` reads in lines until the end of the file. Then the `grepl` counts lines beginning with `l` (adding 1) and the ones beginning with `r` (adding `-1`), then incrementing/decrementing as appropriate: the first non-empty line is not counted as it's the only code that is run. Starts/ends with a newline for reversing and concatenation purposes. Possibly some `->` or `<-` chicanery will yield a shorter result -- indeed, Robin Ryder has [proven me right](https://codegolf.stackexchange.com/a/216483/67312), and it's shorter by a lot! [Answer] # [Brain-Flak (Rain-Flak)](https://github.com/DJMcMayhem/Brain-Flak), 16 bytes ``` ({}())#)])([}{( ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X6O6VkNTU1kzVlMjurZag@v/fwA "Brain-Flak – Try It Online") ## Explanation Making a program that when repeated counts up is easy ``` ({}()) ``` This adds 1 and with no input it defaults to zero, so repeating it counts the number of times. However reversing is a little trickier. Only one balanced string is also a balanced string in reverse and that is the empty string, so we need to use some comments. We use the line comments of the Rain-Flak interpter and hide a payload between a `#` and a newline. Which simply is ``` ({}[()]) ``` This works the same way as the original program but with minus 1 instead of 1. [Answer] # Python IDLE, 5 bytes ``` 0-~+0 ``` [Try it online!](https://tio.run/##XU65DsIwDN3zFd5IVSpVYkOiW1lZ2KOSpmoEOeQmgi799RBCD8Qb7HfYsu3oeqMPIXRoFDDWeedRMAZSWYMOLErtoqu5k0aTNMVNK5acG2XlQ7DYVaNbQp59lHBFL44EIhyOX/LBACeQ2npHs@SJFxfWQX0514gGt8EbiuaeVHqA7qqq2u1hWNYEp3@X6ZBlIZTFlJck1ZnmUzHXma7Zr17zTb4B "Python 3 – Try It Online") ## Explanation ### Forwards ``` 0 # zero -~ # minus-complement (the increment prefix "operator", which # also works as a binary add-plus-one) +0 # zero ``` ### Concatenated ``` 0 # zero -~ # plus one plus +00 # zero -~ # plus one plus +0 # zero ``` ## Reversed ``` 0 # zero + # plus ~- # complement-minus (the decrement prefix "operator") 0 # zero ``` ## Bonus variants * `0-~-0`, which counts up regardless of flipping (in fact, it's palindromic); * `0+~+0`, which counts down regardless of flipping. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 5 bytes ``` ›#‹ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%0A%E2%80%BA%23%E2%80%B9%0A&inputs=&header=&footer=) [Try it Online!Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%0A%E2%80%BA%23%E2%80%B9%0A%0A%E2%80%BA%23%E2%80%B9%0A&inputs=&header=&footer=) [Try it Online!Try it Online!Try it Online!Try it Online!Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%0A%E2%80%BA%23%E2%80%B9%0A%0A%E2%80%BA%23%E2%80%B9%0A%0A%E2%80%BA%23%E2%80%B9%0A%0A%E2%80%BA%23%E2%80%B9%0A%0A%E2%80%BA%23%E2%80%B9%0A&inputs=&header=&footer=) [!enilnO ti yrT](http://lyxal.pythonanywhere.com?flags=&code=%0A%E2%80%B9%23%E2%80%BA%0A%0A%E2%80%BA%23%E2%80%B9%0A%0A%E2%80%B9%23%E2%80%BA%0A&inputs=&header=&footer=) [!enilnO ti yrTTry it Online!!enilnO ti yrT](http://lyxal.pythonanywhere.com?flags=&code=%0A%E2%80%B9%23%E2%80%BA%0A&inputs=&header=&footer=) [Answer] # [Haskell](https://www.haskell.org/), 35 bytes ``` main=print$0--1- +1--0$tnirp=niam ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oCgzr0TFQFfXUFeBS0HbUFfXQKUkL7OowDYvMzH3/38A "Haskell – Try It Online") I tried for quite a bit to do this without comments. It doesn't seem impossible, but it does seem very hard. [Answer] # [Wolfram Language (Mathematica REPL)](https://www.wolfram.com/wolframscript/), 5 bytes ``` 0+1-0 ``` Test cases: ``` 0+1-0 1 0+1-00+1-0 2 0-1+0 -1 0-1+00-1+0 -2 0+1-00-1+0 0 0+1-00-1+00-1+0 -1 ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2gbXFKUmZcelFqQk5icGq3030DbUNfgv5KOUkyekq6dklKsNVc1V0i@a0VBUWpxcWZ@XnRirK2toQ6amI0dSNgITRhmeFlqUXEqUCNQia4hATU2dth0GWFaiEWZAWFV2I035Kr9/1@3AChRAgA "Wolfram Language (Mathematica) – Try It Online") [Answer] # ARM Thumb, 8 bytes excluding return statement Raw machine code: ``` 2101 1840 3901 2100 ``` Assembly: ``` .thumb @ R1 = 1 movs r1, #1 @ r0 += 1 adds r0, r1 @ Dummy code subs r1, #1 movs r1, #0 ``` Reverse each 16 bits ``` 2100 3901 1840 2101 ``` ``` .thumb @ r1 = 0 movs r1, #0 @ r1 = -1 subs r1, #1 @ r0 += -1 adds r0, r1 @ Dummy code movs r1, #1 ``` Going forwards, it sets r1 to 1 and adds it to r0 Going backwards, it sets r1 to 0, subtracts 1 to get r1 to -1 (since Thumb can only load 0-255), then adds it to r0 effectively subtracting 1. Call it with r0 = 0. You need to end it with a return statement (`bx lr` or `4770` in hex) at the end, but those four instructions can be repeated forward and backwards as many times as you desire. [Answer] # ARM (NOT thumb), 16 bytes excluding return instruction Second, entirely different answer, still 4 instructions though. Machine code: ``` 01 10 80 e3 01 00 80 e0 e0 80 00 01 e3 f0 10 00 ``` This one, unlike my Thumb submission, is entirely different in that it is **byte** reversible (hence why it is split in 8 bits instead of 32 bits) It happens to do basically the same thing, though, add 1 on forwards and -1 on backwards. Forwards: ``` movs r1, #1 add r0, r0, r1 smlatteq r0, r0, r0, r8 andseq pc, r0, r3, ror #1 ``` Backwards: ``` movs r1, #-1 @ a.k.a. mvns r1, #0 add r0, r0, r1 smlatteq r0, r0, r0, r8 tsteq r0, r3, ror #1 ``` You may be asking yourself, "`smlatteq`? `andseq`? `tsteq`? What the \*\*\*\* do those do?" The answer is nothing unless the zero flag is set. This code **heavily** abuses ARM's conditional execution and "s" instructions. `movs` will set the condition flags on the value it sets (why this exists for the immediate form, I will never know). I set them to 1 on forwards, and -1 on backwards. These are both non-zero, so they **clear** the zero flag. We also use the version of `add` which does not update the flags, so the zero flag remains clear. Therefore, since the zero flag is not set, all instructions with the `eq` suffix will be ignored. And that is a VERY good thing, because `ands pc, r0, r3, ror #1` would almost certainly crash the program (it would jump to a garbage address) Therefore, in terms of what is effectively executed, it is this: Forwards: ``` movs r1, #1 add r0, r0, r1 nop nop ``` Backwards: ``` movs r1, #-1 @ a.k.a. mvns r1, #0 add r0, r0, r1 nop nop ``` Similar to my Thumb answer, you can repeat these as much as you wish, but you must put a `bx lr` (`e12fff1e`) at the end, and it is called with `r0 == 0`. [Answer] # [Python 3](https://docs.python.org/3/), ~~109~~ 107 bytes Same approach as my zsh answer, but it actually beats the other Python answer! ``` c=open(__file__).read().count;print(c('w ')-c('y\t'))#))' y'(c-)'t\w'(c(tnirp;tnuoc.)(daer.)__elif__(nepo=c ``` [Try it online!](https://tio.run/##DcYxCoRADADA2ndckaRwmyvFnwhBYuQWJAlLRPb1e1Yz0fPn9h1DVg81ZD7rpcxUmu4HUhG/LZdo1RIF4ZmA5te@JRB9iGDqgDIT5Pa8wbTaYkm7XQrhsWsrxKxXPZnRNHyVMf4 "Python 3 – Try It Online") -2 bytes thanks to @Jakque [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~77~~ 71 bytes ``` for i in(1,a:=0):#)a(tnirp ro i=-a a+=i or print(a)#:)0=:a,1(ni i rof ``` [Try it online!](https://tio.run/##NU7LisMwELvnK4RzsUkKDXtZBnzxb5Q9DM10O5B1jGv6@PqskzYXaSSkQelVrnP8@k554QAPY8xymTMUGu3QM/mjo9axLVFzQp6h/sBowJ1X1GDKGotl15I7euJ@sLF2a/Cy1F@ngQ7DD9osf/NdUK6CSXjU@AuOI0pmnVYR5VFZmsB1A4cTrbWm2ZfAcDB9hW7jwBt0G1dz13vofVKDzzqJo9fOgGBcNUt@EeQpZyt3nqy61ZTnWVIhJL7dln8 "Python 3.8 (pre-release) – Try It Online") (include testcases) ## How it works The starting code is this : ``` for i in(1,a:=0):#<...> a+=i or print(a)#<...> ``` At the first iteration of the `for` loop * The `for` loop assigns `a` to `0` and `i` to `1`. * since `i` is equal to `1`, `i or print(a)` won't evaluate the print and will be equal to 1 * `a+=` we increment a (become `a-=` in the reversed program) At the second iteration of the `for` loop: * The `for` loop assigns `i` to `0`. * `i or print(a)` will print `a` since `i` is evaluated as `False` and return `None` * it then crash the program (to avoid multiple printing) since we try to add `None` to an integer When chained, the prgrams become : ``` for i in(1,a:=0):#<...> a+=i or print(a)#<...>for i in(1,a:=0):#<...> a+=i or print(a)#<...> ``` There is only one active `for` loop (the other one are commentated), and the incrementation (or decrementation when reversed) occurs once for each repetition of the program. The printing occurs only once beacause of the crash. The reverse program is only changing `a+=` by `a-=` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes ``` υΣI⁰⎚¹±υ⊞υ¹⎚⁰IΣυ ``` [Try it online!](https://tio.run/##S85ILErOT8z5//9867nF7/esfNS44VHfrEM7D2083/qoa9751kM7gXygKFDu3OLzrf//AwA "Charcoal – Try It Online") Explanation: ``` υ ``` Print the list. ``` ΣI⁰ ``` Cast 0 to string, then take the digital sum and print it (this happens to do nothing). ``` ⎚ ``` Clear the canvas. ``` ¹ ``` Print a `-`. ``` ±υ ``` Print the negated list. ``` ⊞υ¹ ``` Push `1` to the list. (This is what actually affects the final output.) ``` ⎚ ``` Clear the canvas. ``` ⁰ ``` Print nothing. ``` IΣυ ``` Cast the sum of the list to string and print it. (This code at the end of the last copy is the only output that survives the program.) [Try it reversed!](https://tio.run/##S85ILErOT8z5//9867nF7/esfNS44VHfrEM7z7c@6pp3vvXQxkM7gXygKFDu3OLzrf//AwA "Charcoal – Try It Online") Explanation: The middle instructions differ slightly when the code is reversed: ``` ¹ ``` Print a `-`. ``` υ ``` Print the list. ``` ⊞υ±¹ ``` Push `-1` to the list. [Answer] # [Python 3](https://docs.python.org/3/), 164 bytes ``` import atexit as a;a._clear();a.register(lambda:print(v));v=locals().get('v',0)+1#;1-)0,'v'(teg.)(slacol=v;))v(tnirp:adbmal(retsiger.a;)(raelc_.a;a sa tixeta tropmi ``` **[Try it online!](https://tio.run/##DcfRCoMwDEDRXxH2YMK2ouzN4rdIrMEVoi1pKO7rXZ/uufln33R@7jseOal1ZHzFltKRJ7cEYVLARuU9FmMFoWPdaMoaT4OK6OssKZAUQLezQV/714DP8eHHNw6vtmC8O4QiFJLM1SNWsDNqnmhbDxJQthJ3VkceQYklLI3UFeosXmwtmvIR7/sP "Python 3 – Try It Online")** Or use [this program builder](https://tio.run/##PU/RasMwDHzvV5juwVLXhpa9JeR1H5DXMYqaapmLExtZNdnXZw7rCoI73engFH/0O0xvy9KHK7fW2o0bYxA1pDy7AslQQ9W590wCWKjw4JKygKfxcqU6ipsUMmKTWx968gmwGljBZrs/4uvppTkd8LgvKygPFULy1Aff5gYxg05OYk3Xy0gehDW5gaWiBkGIfX8ulEwio25mLSAhjm6zFo0SBqGxlK5uwU2wfvBR13A44W4HuW1tZ/HTfAUx2bipTLwrIG7@Gm8f@Xr7rzyE54FwuntdfZ65f9rL8t51vw "Python 3 – Try It Online") (Input `F` for forward and `R` for reverse). [Answer] # [Zsh](https://www.zsh.org/), 91 bytes ``` <<<$[`grep -c wx $0`-`grep -c y\z $0`];:<<'Q' 'Q'<<:;]`0$ zy c- perg`-`0$ x\w c- perg`[$<<< ``` [Try it online!](https://tio.run/##qyrO@P/fxsZGJTohvSi1QEE3WaG8QkHFIEEXzq@MqQIJxFpb2dioB6pzAbGNjZV1bIKBikJVpUKyrkJBalE6UAOQXxFTDheIVgGa@/8/AA "Zsh – Try It Online") ## Explanation The overall idea is to read the source file and count the number of occurrences of the code forwards, minus the number backwards. ``` `grep -c wx $0` # count occurrences of `wx` `grep -c y\z $0` # count occurrences of `yz`* $[ - ] # subtract <<< # print ; # then : # do nothing, <<'Q' # with the rest of the file** ``` `*`: The backslash in the middle prevents the call to grep itself from being counted as an instance. In the mirrored copy on the next line, the backslash is placed inside `wx` instead, so that when re-reversed, it matches the negative one instead. `**`: This starts a [here-document](https://google.com?q=zsh+heredoc), which consumes as input the rest of the file until the first line containing only `FW`. The single-quotes prevent execution of any `$[...]` and ``...`` parts from any possible repeated sections afterwards. We can't use line comments because `grep -c` outputs the number of matching lines, not individual matches. In another language we won't have this limitation. The whole program is then duplicated, with the `\` inside the `wx` instead of the `yz`, is then reversed and put on the next line, so that it works as expected when the first instance is a reversed one. [Answer] # [Klein](https://github.com/Wheatwizard/Klein) 000, 12 bytes ``` \@+ - 1 +@\ ``` [Try it online!](https://tio.run/##y85Jzcz7/z/GQZtLQZfLkEvbIeb///8GBgYA "Klein – Try It Online") **Reversed** ``` \@+ 1 - +@\ ``` [Try it online!](https://tio.run/##y85Jzcz7/z/GQZvLkEtXgUvbIeb///8GBgYA "Klein – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 31 bytes ``` tnirP//1-eniL$-- $Line++//Print ``` Try it: * [forward](https://tio.run/##y00syUjNTSzJTE78/78kL7MoQF/fUDc1L9NHRVeXS8UnMy9VW1tfP6AoM6/k/38A) * [2x forward](https://tio.run/##y00syUjNTSzJTE78/78kL7MoQF/fUDc1L9NHRVeXS8UnMy9VW1tfP6AoM6@EgPT//wA) * [backward](https://tio.run/##y00syUjNTSzJTE78/78kL7MoQF9fWzs1L9NHhUtXV8UnMy9V11BfP6AoM6/k/38A) * [2x backward](https://tio.run/##y00syUjNTSzJTE78/78kL7MoQF9fWzs1L9NHhUtXV8UnMy9V11BfP6AoM6@EgPT//wA) * [forward, backward](https://tio.run/##LckxCgAgCAXQvXO0yUe6R0NXkBByyCG8v0H01rcllm4Jm5IZbmcwN6hbr0Cp3VyJmMcxj99ErwvwGu135gU) * [forward, 2x backward](https://tio.run/##y00syUjNTSzJTE78/78kL7MoQF/fUDc1L9NHRVeXS8UnMy9VW1tfP6AoM68EKq2tDZbm0tUFS@saEif9/z8A) A full program. `$Line` has an initial value of `1`. In a notebook, it would increment for each input expression, but this doesn't apply outside the REPL. [Answer] # JavaScript, ~~131~~ ~~121~~ 122 bytes * -10 thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) * +1 I forgot that the newline would also be reversed, so another one needed to be added ``` clearTimeout(this.a);a=setTimeout(console.log,0,b=-~this.b)//)b.siht-~=b,0,gol.elosnoc(tuoemiTtes=a;)a.siht(tuoemiTraelc; ``` (notice the leading and trailing newlines. the stacksnippets removes some of the leading and trailing newlines for the entire snippet, but it still works with/without the first and last newlines) Try It Right Here! (TryItOnline has an error where `clearTimeout` is not defined, but `clearTimeout` is a valid JavaScript function.) aB ``` clearTimeout(this.a);a=setTimeout(console.log,0,b=-~this.b)//)b.siht-~=b,0,gol.elosnoc(tuoemiTtes=a;)a.siht(tuoemiTraelc ``` aBaB ``` clearTimeout(this.a);a=setTimeout(console.log,0,b=-~this.b)//)b.siht-~=b,0,gol.elosnoc(tuoemiTtes=a;)a.siht(tuoemiTraelc clearTimeout(this.a);a=setTimeout(console.log,0,b=-~this.b)//)b.siht-~=b,0,gol.elosnoc(tuoemiTtes=a;)a.siht(tuoemiTraelc ``` Ba ``` clearTimeout(this.a);a=setTimeout(console.log,0,b=~-this.b)//)b.siht~-=b,0,gol.elosnoc(tuoemiTtes=a;)a.siht(tuoemiTraelc ``` BaBa ``` clearTimeout(this.a);a=setTimeout(console.log,0,b=~-this.b)//)b.siht~-=b,0,gol.elosnoc(tuoemiTtes=a;)a.siht(tuoemiTraelc clearTimeout(this.a);a=setTimeout(console.log,0,b=~-this.b)//)b.siht~-=b,0,gol.elosnoc(tuoemiTtes=a;)a.siht(tuoemiTraelc ``` aBBa ``` clearTimeout(this.a);a=setTimeout(console.log,0,b=-~this.b)//)b.siht-~=b,0,gol.elosnoc(tuoemiTtes=a;)a.siht(tuoemiTraelc clearTimeout(this.a);a=setTimeout(console.log,0,b=~-this.b)//)b.siht~-=b,0,gol.elosnoc(tuoemiTtes=a;)a.siht(tuoemiTraelc ``` aBBaBa ``` clearTimeout(this.a);a=setTimeout(console.log,0,b=-~this.b)//)b.siht-~=b,0,gol.elosnoc(tuoemiTtes=a;)a.siht(tuoemiTraelc clearTimeout(this.a);a=setTimeout(console.log,0,b=~-this.b)//)b.siht~-=b,0,gol.elosnoc(tuoemiTtes=a;)a.siht(tuoemiTraelc clearTimeout(this.a);a=setTimeout(console.log,0,b=~-this.b)//)b.siht~-=b,0,gol.elosnoc(tuoemiTtes=a;)a.siht(tuoemiTraelc ``` [Answer] # Python 3, 112 bytes ``` import os#1=-KO_R.so os.system('cls')#)5-KO_R.so(tnirp print(os.R_OK-3)#)'slc'(metsys.so os.R_OK+=1#so tropmi ``` very ugly, but works. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 104 bytes ``` var i=-~i,y=-~y;setTimeout(_=>--i||console.log(y))//))y(gol.elosnoc||i-->=_(tuoemiTtes;y-~=y,i~-=i rav ``` [Try it online!](https://tio.run/##bY1BCoMwEEX3nsJlQk08gMRlT9BdKTqxg4xopiRRCASvbu2mUCh8Pvz3Fn@CDcLg6RWV4yceYEtT9kexgS/JqJ2qdHZqAsYbLchrFJ1plaKcB3aBZ9QzjyJJWddSJjHyrHHm4HjImZRqTSfiyrjQLWJoktpNqmhXhkoPW3H0TWHhvLxrrcE@tMcNfUAh9cTk@lNfVzdEYifASiF/9sXCH/TJ1x1v "JavaScript (Node.js) – Try It Online") Using V8(`print`) or browser(`alert`) saves some bytes [Answer] # Ruby, 60 bytes Note trailing newline: ``` a||=0;a+=1;at_exit{p a;exit!}#}!tixe;a p{tixe_ta;1=-a;0=||a ``` [Try it online!](https://tio.run/##KypNqvz/P7GmxtbAOlHb1tA6sSQ@tSKzpLpAIdEaxFCsVa5VLMmsSLVOVCioBjHiSxKtDW11E60NbGtqErn@/wcA "Ruby – Try It Online") Reversed version (leading newline): ``` a||=0;a-=1;at_exit{p a;exit!}#}!tixe;a p{tixe_ta;1=+a;0=||a ``` [Try it reversed!](https://tio.run/##KypNqvz/nyuxpsbWwDpR19bQOrEkPrUis6S6QCHRGsRQrFWuVSzJrEi1TlQoqAYx4ksSrQ1ttROtDWxrahL//wcA "Ruby – Try It Online") `at_exit` specifies a block to be executed upon `exit`, `SystemExit` exception, or uncatchable error. `exit!` specifically bypasses these, giving the ability to skip all but the first registered block. [Answer] # [><>](https://esolangs.org/wiki/Fish), 19 bytes ## Forwards ``` l\ v ;l-n n+l; v \l ``` [Try it online!](https://tio.run/##S8sszvj/PydGoYzLOkc3jytPO8eaq0whJuf/fwA "><> – Try It Online") ## Backwards ``` l\ v ;l+n n-l; v \l ``` [Try it online!](https://tio.run/##S8sszvj/PydGoYzLOkc7jytPN8eaq0whJuf/fwA "><> – Try It Online") Works a lot like [my klein solution](https://codegolf.stackexchange.com/a/216515/56656), but it has to deal with the finickiness of ><>. ]
[Question] [ I have come across a [question](https://codereview.stackexchange.com/q/107221) on the Code Review site that seems interesting. I think OP is doing it wrong, but cannot be sure... So let's solve it for him! (write a program, not a function/procedure) ## Input (stdin or similar): An integer `x` in decimal notation. It is greater than 1 and less than 2^31. ## Output (stdout or similar): An integer `y` in decimal notation. The product `x * y` in decimal representation must contain only digits 0 and 1. It must be the minimal such number greater than 0. Note: output is not limited - if the minimal `y` is around 10^100, your program must output all of its 100 digits (I don't know whether there is a reasonable limit, like 2^64, on `y` - didn't solve it). Your program should finish in a reasonable time (1 second? 1 hour? - something like that) for all `x` in range. ### Bonus: If your program doesn't have a limit on the size of the input (except RAM), and has polynomial complexity, multiply the byte count of your program by `0.8` and round down. --- Example: Input `2`; output `5`, because 2 \* 5 = 10 Example: Input `21`; output `481`, because 21 \* 481 = 10101 --- Disclaimer: I am not responsible for the question on the Code Review site. In case of any discrepancy, only the description above should be regarded as proper spec. [**OEIS A079339**](http://oeis.org/A079339) [Answer] # Python 2, efficient solution, 99 ``` n=input() d={n:0} k=1 while min(d):[d.setdefault((x+k)%n,d[x]+k)for x in set(d)];k*=10 print d[0]/n ``` Thanks Sp3000 for some golfing tips. I challenge everybody else to post (in their own answers) how long it takes to get the result for input `72` or `99` :) If those are really fast, try something like `79992` next (still <1 sec here). **Explanation:** I thought this wasn't necessary (since the code is fairly readable), but I got a request, so here it goes: The first idea is that a binary-looking number is a sum of 1 or more different powers of 10. Therefore, we can try to add various powers of 10 in different ways until we get remainder 0. If we do that naively, it's the same as generating all binary-looking numbers and testing them. But a lot of remainders will be the same. A better way is to record only the smallest number that gave a certain remainder, and successively add greater powers of 10 to numbers we recorded. That's what the program does. `d` is a dictionary/map where keys are remainders and values are binary-looking numbers with that remainder. The initial `n:0` is a special case: it's supposed to be `0:0` so we can start adding powers to it, but the algorithm stops when finding key 0, so I used `n` instead, which is guaranteed to have the same effect and not interfere with the other values. Then we start adding powers of 10 (stored in `k`) to all existing numbers and recording the remainders. We add `k` to the remainder: `(x+k)%n` and to the number: `d[x]+k`, and record it only if it's a new remainder: `d.setdefault(…)`, then go to the next power: `k*=10` and repeat until we get key 0: `while min(d)` At the end, `d[0]` gives the binary-looking number that has remainder 0 mod `n`, so we divide it by `n` to get the solution. Note: the program can be made more efficient by avoiding large numbers (recording exponents rather than powers of 10, and calculating remainders of powers from previous values), but it's code golf, so... In fact, here, I wrote a faster version: ``` n=input() d={n:0} k=1 b=0 while 0not in d: for x in list(d):d.setdefault((x+k)%n,b) k=(k*10)%n;b+=1 x=10**d[0] while x%n:x+=10**d[n-x%n] print x/n ``` [Answer] ## Python 2, 47 bytes ``` n=a=input() while'1'<max(str(a)):a+=n print a/n ``` Tracks the input number `n` and the current multiple `a`. When `a` looks like binary, output the ratio `a/n`. To check that a number is made of `0`'s and `1`'s, we compare the maximum char in its string representation to `'1'`. Uses `str(a)` instead of ``a`` to avoid longs ending in `L`. Unfortunately, `'L'` is bigger than `'1'`. [Answer] # Perl, 27 bytes ``` #!perl -p 1while($_*++$\)=~/[2-9]/}{ ``` Counting the shebang as one, input is taken from stdin. **Sample Usage** ``` $ echo 2 | perl dec-bin.pl 5 $ echo 21 | perl dec-bin.pl 481 $ echo 98 | perl dec-bin.pl 112245 ``` --- # Perl, 25 bytes ``` #!perl -p eval'0b'.++$\*$_||redo}{ ``` A two byte improvement by [@skmrx](https://codegolf.stackexchange.com/questions/60942/60981#comment146985_60981). Rather than checking against a regex, this instead attempts to evaluate the product as a binary literal. Upon failure, it moves on to the next. Typically the `oct` function would be used for this purpose, but it silently trims invalid digits, which isn't useful in this challenge. --- # Perl, 40 bytes ``` #!perl -p 1while($b=sprintf"%b",++$i)%$_;$_=$b/$_ ``` A far more efficient solution. We iterate over binary representations, interpret them as base 10, and then check for divisibility. Runtimes for all values under 100 are negligible. **Sample Usage** ``` $ echo 72|perl dec-bin.pl 1543209875 $ echo 99|perl dec-bin.pl 1122334455667789 ``` [Answer] # Javascript, 43 bytes This ended up way shorter than I thought. It basically increments `y` up 1 until `y * (input number) = (binary-looking number)`. Obviously quite inefficient. ``` for(x=prompt(y=0);!+('0b'+x*++y););alert(y) ``` --- # Javascript (more efficient solution), 53 bytes This one increments `y` in binary until `y / (input number) = (number without a remainder)`. Then it outputs `(number without a remainder)`. ``` for(x=prompt(y=1);(z=y.toString(2))%x;y++);alert(z/x) ``` --- # Javascript (even more efficient solution), 76 bytes This one combines both of the previous methods described above. It checks increments `y` until either `y * (input number) = (binary-looking number)` (meaning that the output is `y`) OR `y / (input number) = (number without a remainder)` (meaning that the output is `(number without a remainder)`). ``` for(x=prompt(y=a=0);!a;a=+('0b'+x*++y)?y:(z=y.toString(2))%x?0:z/x);alert(a) ``` [Answer] # Haskell, ~~72~~ ~~70~~ ~~64~~ ~~60~~ 58 bytes ``` main=do x<-readLn;print$[y|y<-[1..],all(<'2')$show$x*y]!!0 ``` Edit: @Jan Dvorak helped me saving 4 bytes. Edit: @BlackCap saved 2 bytes by switching to `do` notation. Thanks! [Answer] # Pyth, 9 bytes ``` f!-`*TQ10 ``` [Demonstration](https://pyth.herokuapp.com/?code=f%21-%60%2aTQ10&input=21&debug=0) For each multiple, convert to a string, subtract out the digits in `10` (using Pyth's handy int to str cast in this case) and then logically negate the result, terminating the seach only when the correct multiple is found. ### Bonus solution, 10 bytes: ``` f.xi`*TQ2Z ``` This solution actually checks if the string representation of the number can be treated as a binary number (`i ... 2`) and terminates when an error is not thrown on this attempt. [Answer] # Python 2, ~~67~~ ~~65~~ ~~63~~ 60 bytes ``` a=input();b=1 while set(`a*b`)&set('23456789'):b+=1 print b ``` Thanks to [Status](https://codegolf.stackexchange.com/users/34315/status) for 2 bytes and [Shebang](https://codegolf.stackexchange.com/users/38417/shebang) for 5 bytes! [Answer] # JavaScript (ES6) 222 ~~250~~ Using arbitrary precision math (operating on strings of decimal digits) ~~This can be golfed a little more~~(done), but I like the fact that it is not limited to JS standard numbers (17 decimal digits of precision) and that it is fast. Test running the snippet below in an EcmaScript 6 compliant browser. Time is acceptable up to 9998 - don't try 9999 and be patient with 999. ``` // As a complete program with I/O via popup for(n=+prompt(a=[0],q=[t=1]);t;){for(c=1,t=i=0;i<a.length;i++)a[i]=a[i]&c?0:a[i]|c?(c=0,t+=q[i],1):c=0;c&&(a[i]=c,t+=q[i]=q[i-1]*10%n);t%=n}a.reverse().map(a=>(z+=[a],d=z/n|0,z%=n,r||d?r+=d:0),r='',z=0);alert([r,a.join``]) // As a testable function f=n=>{ for(a=[0],q=[t=1];t;) { for(c=1,t=i=0;i<a.length;i++) a[i]=a[i]&c?0:a[i]|c?(c=0,t+=q[i],1):c=0 c&&(a[i]=c,t+=q[i]=q[i-1]*10%n); t%=n } a.reverse().map(a=>(z+=[a],d=z/n|0,z%=n,r||d?r+=d:0),r='',z=0) return [r,a.join``] } // Test and timing out = x => O.innerHTML += x + '\n' setTimeout(_=>{ ;[1,2,10, 21, 23, 98, 72, 9, 99, 999] .forEach((test,i) => { var t0 = ~new Date var result = f(test) out('n='+test+' '+result+' time(ms) ' + (t0-~new Date)) })},100) ``` ``` <pre id=O>Timing test cases ... </pre> ``` **More readable** This is the first version, with modulus and long division as separated functions. ``` // function M - Modulus with arbitrary precision - a is a string of decimal digits M = (a, b, q = 1, t = 0, j = a.length) => { while (j--) + a[j] ? t += q : 0, q = (q * 10) % b; return t % b } // function D - Long division with arbitrary precision - a is a string of decimal digits D = (a, b, r = '', z = 0) => [...a].map(a => (z += a, d = z / b | 0, z %= b, r || d ? r += d : 0)) && r // Testable function f = n => { for (i = 0; ++i < 1e7 && (z = M(v = i.toString(2), n));); return z ? ['big'] : [D(v, n), v] } ``` [Answer] ## Perl, 45 bytes ``` do{$a++}while($a*($b||=<>))=~/[2-9]/;print$a; ``` [Answer] # Python ~~3~~ 2, ~~101~~ 76 Bytes **-25** bytes thanks to @aditsu almost as efficient as @aditsu's solution ``` 99 -> 0.436 Seconds 72 -> 0.007 Seconds ``` ``` b,m,n=1,1,input() while b%n: b=int("{0:b}".format(m)) m+=1 print b/n ``` Instead of trying to loop through the multiples in increasing order, I'm trying to loop through the products, which I'm generating in 'binary' form. [Answer] ## Pyth, 10 bytes ``` f<eS`*TQ`2 ``` [Run the code.](https://pyth.herokuapp.com/?code=f%3CeS%60%2ATQ%602&input=21&debug=0) A port of my [Python answer](https://codegolf.stackexchange.com/a/60975/20260), taking from [Maltysen](https://codegolf.stackexchange.com/a/60971/20260) the use of `f` to find the first positive number that meets a condition. [Answer] # PHP, 50 bytes ``` while(preg_match('/[^01]/',$argv[1]*++$y));echo$y; ``` **Some test cases** ``` 1 > 1 2 > 5 12 > 925 21 > 481 ``` [Answer] # CJam, ~~19~~ ~~17~~ 16 bytes ``` li:V!{)_V*sAs-}g ``` [Try it online](http://cjam.aditsu.net/#code=li%3AV!%7B)_V*sAs-%7Dg&input=21) Brute force solution, trying values sequentially until one meeting the condition is found. The latest version saves 2 bytes thanks to using `As` instead of `"01"` to build a string containing `0` and `1`, as suggested by @aditsu. The full proposed solution in the comment saves another byte, but it looks fairly different from mine, so I didn't want to post it under my name. And 1 more byte saved by @Dennis. Explanation: ``` li Get input and convert to int. :V Save it in variable V. ! Negate the value. Since we saved it in V, we don't need it on the stack anymore. But we need 0 on the stack as the start value for y. This conveniently accomplishes both with a single operator, since the input is guaranteed to be larger than 0. { Loop over y. ) Increment y. _ Copy it. V* Multiply with input in variable V. s Convert to string. As Push the string "10", as the number 10 converted to a string . - Remove 0 and 1 digits. This will result in an empty list if there were only 0 and 1 digits. The empty list is falsy, and will terminate the loop. }g End loop. ``` [Answer] # Java, 213 bytes ``` import java.math.*;class P{public static void main(String[]a){BigInteger b=new java.util.Scanner(System.in).nextBigInteger(),c,d=c=b.ONE;while(!(b.multiply(c)+"").matches("[01]+"))c=c.add(d);System.out.print(c);}} ``` Uses `BigInteger`s and as such has (for all reasonable intents and purposes) unbounded input size. Not sure about the complexity though, that depends on the growth rate of our function here. Thanks to geobits and ypnypn for saving a handful of bytes. [Answer] # C++11, many bytes, very fast, wow (1.5 s on 1999999998, 0.2 s on 1…10000) (Golfed Python version below.) We start with a concept somewhat similar to aditsu’s solution, where we inductively build up a collection of modular remainders reachable in n steps. But instead of waiting until we find remainder 0, we check for two found remainders a and b such that a·10^n + b = 0. This meet-in-the-middle approach halves the depth of the search tree, so it’s much faster on large inputs and uses much less memory. Some benchmarks: ``` $ echo 99999999 | \time ./decbin 1111111122222222333333334444444455555555666666667777777788888889 0.18user 0.01system 0:00.20elapsed 99%CPU (0avgtext+0avgdata 69360maxresident)k 0inputs+0outputs (0major+16276minor)pagefaults 0swaps $ echo 999999999 | \time ./decbin 111111111222222222333333333444444444555555555666666666777777777888888889 1.22user 0.04system 0:01.27elapsed 100%CPU (0avgtext+0avgdata 434776maxresident)k 0inputs+0outputs (0major+37308minor)pagefaults 0swaps $ echo 2147483647 | \time ./decbin 4661316525084584315813 0.00user 0.00system 0:00.01elapsed 72%CPU (0avgtext+0avgdata 5960maxresident)k 0inputs+0outputs (0major+1084minor)pagefaults 0swaps $ echo 1999999998 | \time ./decbin 555555556111111111666666667222222222777777778333333333888888889444444445 1.42user 0.08system 0:01.50elapsed 100%CPU (0avgtext+0avgdata 544140maxresident)k 0inputs+0outputs (0major+38379minor)pagefaults 0swaps $ \time ./decbin 10000.out 0.19user 0.00system 0:00.20elapsed 100%CPU (0avgtext+0avgdata 3324maxresident)k 0inputs+264outputs (0major+160minor)pagefaults 0swaps ``` Code: ``` #include <algorithm> #include <boost/iterator/transform_iterator.hpp> #include <fstream> #include <list> #include <iostream> #include <string> #include <utility> #include <vector> using namespace boost; using namespace std; static inline bool cmp_first_partnered(pair<int, pair<int, int>> a, pair<int, pair<int, int>> b) { return a.first < b.first; } static inline bool eq_first_partnered(pair<int, pair<int, int>> a, pair<int, pair<int, int>> b) { return a.first == b.first; } static pair<int, int> retrace(int modulus, int place, pair<int, int> state, list<vector<int>>::iterator i, list<vector<int>>::iterator j, string &ret) { if (i == j) return state; state = retrace(modulus, (place * 10LL) % modulus, state, next(i), j, ret); int remainder = state.first; long long k = state.second * 10LL; if (!binary_search(i->cbegin(), i->cend(), remainder)) { remainder = ((long long)remainder + modulus - place) % modulus; k += 1; } int digit = k / modulus; if (digit != 0 || ret.size()) ret += '0' + digit; return make_pair(remainder, k % modulus); } static void mult(int modulus, int x, int y, vector<pair<int, pair<int, int>>>::iterator i, vector<pair<int, pair<int, int>>>::iterator j) { if (y - x == 1) { for (auto k = i; k != j; k++) k->first = (k->first * 10LL) % modulus; return; } int z = (x + y) / 2; vector<pair<int, pair<int, int>>>::iterator k = lower_bound( i, j, make_pair(int(((long long)modulus * z + 9) / 10), make_pair(0, 0))); mult(modulus, x, z, i, k); mult(modulus, z, y, k, j); inplace_merge(i, k, j, [](pair<int, pair<int, int>> a, pair<int, pair<int, int>> b) { return make_pair(a.first, a.second.second) < make_pair(b.first, b.second.second); }); } static string go(int modulus) { if (modulus == 1) return "1"; int sequence = 1; list<vector<int>> v = {{0}}; vector<pair<int, pair<int, int>>> partnered; int place = 1; while (true) { v.emplace_back(v.rbegin()->size() * 2); vector<int> &previous = *next(v.rbegin()), &current = *v.rbegin(); auto offset = [modulus, place, sequence](int a) { return (a + (long long)place) % modulus; }; auto old_mid = lower_bound(previous.cbegin(), previous.cend(), modulus - place), new_mid = lower_bound(previous.cbegin(), previous.cend(), place); current.resize( set_union(new_mid, previous.cend(), make_transform_iterator(previous.cbegin(), offset), make_transform_iterator(old_mid, offset), set_union(previous.cbegin(), new_mid, make_transform_iterator(old_mid, offset), make_transform_iterator(previous.cend(), offset), current.begin())) - current.begin()); int place2 = modulus - (long long)place * place % modulus; auto offset_partnered = [modulus, place, place2, sequence](pair<int, pair<int, int>> a) { return make_pair((a.first + (long long)place2) % modulus, make_pair((a.second.first + (long long)place) % modulus, sequence + a.second.second)); }; auto old_mid_partnered = lower_bound(partnered.cbegin(), partnered.cend(), make_pair(modulus - place2, make_pair(0, 0))), new_mid_partnered = lower_bound(partnered.cbegin(), partnered.cend(), make_pair(place2, make_pair(0, 0))); vector<pair<int, pair<int, int>>> next_partnered(partnered.size() * 2 + 1); auto i = set_union(partnered.cbegin(), new_mid_partnered, make_transform_iterator(old_mid_partnered, offset_partnered), make_transform_iterator(partnered.cend(), offset_partnered), next_partnered.begin(), cmp_first_partnered); if (new_mid_partnered == partnered.cend() || new_mid_partnered->first != place2) *i++ = make_pair(place2, make_pair(place, sequence)); next_partnered.resize( set_union(new_mid_partnered, partnered.cend(), make_transform_iterator(partnered.cbegin(), offset_partnered), make_transform_iterator(old_mid_partnered, offset_partnered), i, cmp_first_partnered) - next_partnered.begin()); partnered.swap(next_partnered); sequence += previous.size(); place = (place * 10LL) % modulus; mult(modulus, 0, 10, partnered.begin(), partnered.end()); partnered.resize( unique(partnered.begin(), partnered.end(), eq_first_partnered) - partnered.begin()); auto with_first = [](int a) { return make_pair(a, make_pair(a, 0)); }; vector<pair<int, pair<int, int>>> hits; set_intersection(partnered.cbegin(), partnered.cend(), make_transform_iterator(current.cbegin(), with_first), make_transform_iterator(current.cend(), with_first), back_inserter(hits), cmp_first_partnered); if (hits.size()) { pair<int, pair<int, int>> best = *min_element( hits.begin(), hits.end(), [](pair<int, pair<int, int>> a, pair<int, pair<int, int>> b) { return a.second.second < b.second.second; }); string ret = ""; pair<int, int> state = retrace(modulus, 1, make_pair(best.second.first, 0), v.begin(), prev(v.end()), ret); retrace(modulus, 1, make_pair(best.first, state.second), v.begin(), prev(v.end()), ret); return ret; } } } int main(int argc, const char *argv[]) { ios_base::sync_with_stdio(false); if (argc >= 2) { ofstream ofs(argv[1]); for (int modulus = 1; modulus <= 10000; modulus++) ofs << go(modulus) << '\n'; } else { int modulus; cin >> modulus; cout << go(modulus) << '\n'; } return 0; } ``` # Python, 280 bytes (8.6 seconds on 1999999998 with PyPy) ``` n=input() if n<2:print 1;exit() d={0:0} l=[] k=1 b=x=y=0 while 1: for a in[0]+l: m=(a+k)%n if m not in d:l.append(m);d[m]=b k=(k*10)%n;b+=1 for a in l: if(-k*a)%n in d: while(a-x)%n:x+=10**d[(a-x)%n] while(-y-k*a)%n:y+=10**d[(-y-k*a)%n] print(10**b*x+y)/n;exit() ``` [Answer] # Mathematica 115 bytes ``` p=Drop[Union[FromDigits/@Flatten[Table[Tuples[{0,1},{k}],{k,2,12}],1]],2]; i=Input[];FirstCase[p,x_/;Divisible[x,i]] ``` [Answer] # R, 45 bytes ``` x=scan();y=2;while(grepl("[2-9]",x*y))y=y+1;y ``` Usage: ``` > x=scan();y=2;while(grepl("[2-9]",x*y))y=y+1;y 1: 2 2: Read 1 item [1] 5 > x=scan();y=2;while(grepl("[2-9]",x*y))y=y+1;y 1: 21 2: Read 1 item [1] 481 > x=scan();y=2;while(grepl("[2-9]",x*y))y=y+1;y 1: 42 2: Read 1 item [1] 2405 ``` [Answer] **Java 156 bytes** ``` public class P{public static void main(String[]a){long x=Long.valueOf(a[0]),y;for(y=2;!(""+x*y).replaceAll("1|0","").isEmpty();y++);System.out.println(y);}} ``` Massive thanks to aditsu :) [Answer] # Pyth - ~~12~~ 11 bytes Uses filter with numeric arg to get first natural number that fulfills predicate, default is 1 which is what we want. Setwise diff to check if only zeros and ones. ``` f!-j*QT10U2 ``` [Test Suite](http://pyth.herokuapp.com/?code=f%21-j%2aQT10U2&test_suite=1&test_suite_input=2%0A21&debug=0). [Answer] # Java, ~~198~~ ~~193~~ 181 bytes Thanks to @aditsu for shaving off 5 bytes AND increasing the range of testable numbers! Note that some values loop negatively due to how Java parses integers. This could be circumvented by BigInteger, but the bonus was simply less valuable. I know that I'm not going to win, but I hope this inspires other, shorter, answers. ``` class A{public static void main(String[] a){for(long i=1;;i++){try{long b=Long.parseLong(a[0]);if(b*i<0)break;Long.parseLong(b*i+"",2);System.out.println(i);}catch(Exception e){}}}} ``` Ungofled: ``` class A { public static void main(String[] a){ for(long i=1;;i++){ // infinite loop starting at 1 try{ // if an error is thrown by attempting to parse as binary, restart while adding 1 to i long b=Long.parseLong(a[0]); // For later - it was shorter to declare than use twice if(b*i<0)break; // Break out of the program if we have looped. Long.parseLong(b*i+"",2); // Multiply out and see if it's passable as a binary number, otherwise, throw error and go back to the top of the loop System.out.println(b); // print it out } catch (Exception e) {} // do nothing on catch } } } ``` [Answer] # C, 107 101 bytes (105 99 bytes for 32-bits) There is a distinct lack of answers in C on code golf. Indeed, C is not the best choice for writing the smallest possible program, but it's not that bad: ``` main(d,b){char s[9];gets(s);for(b=atoi(s);sprintf(s,"%d",b*d),strspn(s,"01")[s];d++);printf("%d",d);} ``` You can do without the #includes, but then all the function definitions will be implicit. The main drawback is that this causes the assumption that all functions return ints. This is a problem on 64-bit machines for functions that actually return a pointer. If you are on a 32-bit machine, 2 bytes can be shaved off the above solution: ``` main(d,b){char s[9];for(b=atoi(gets(s));sprintf(s,"%d",b*d),strspn(s,"01")[s];d++);printf("%d",d);} ``` Somewhat more readable version: ``` int main() { char s[9]; gets(s); int d = 1; int b = atoi(s); for (; sprintf(s, "%d", b * d), strspn(s, "01")[s]; d++); printf("%d", d); } ``` [Answer] # C# time near 5 seconds (1 to 10000) As requested, here is a golfed C# program answering the original challenge. Input as command line argument, output to console. ``` using System;using System.Collections.Generic;using System.Numerics;using System.Linq; class P{static void Main(string[] a){int m,n=int.Parse(a[0]);var d=new Dictionary<int,long>();long b;int h; for(d[n]=0,b=h=1;;b*=2,h=(h*10)%n)foreach(int k in d.Keys.Reverse())if(!d.ContainsKey(m=(h+k)%n)){ var w=d[k]|b;if(m==0){Console.Write(BigInteger.Parse(Convert.ToString(w,2))/n);return;}d.Add(m,w);}}} ``` Then, as for the bounty: the bounty should go to aditsu, as I think his algorithm cannot be beaten in terms of perfomance. But anatolyg self-answer is amazing too. Here is my fast implementation in C#. I suppose that in C++ it could be faster (maybe 2x). Compiled and tested with Visual Studio 2010, .NET framework 4, 64 bits, redirecting output to nul. Time : 00:00:05.2604315 ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Numerics; using System.Diagnostics; class Program { static BigInteger Find(int n) { var d = new Dictionary<int, long>(); long kb; int km; d[n] = 0; for (kb = km = 1; ; kb *= 2, km = (km * 10) % n) { foreach (int key in d.Keys.Reverse()) { int m = (km + key) % n; if (!d.ContainsKey(m)) { long w = d[key] | kb; if (m == 0) { return BigInteger.Parse(Convert.ToString(w, 2)); } d.Add(m, w); } } } } static void Exec(int n, out string sq, out string sa) { var v = Find(n); sq = (v/n).ToString(); sa = v.ToString(); } static void Main(string[] args) { // string n = Console.ReadLine(); int limit = int.Parse(args[0]); string q ="", a = ""; Stopwatch x = new Stopwatch(); x.Start(); for (int n = 1; n <= limit; n++) { Exec(n, out q, out a); Console.WriteLine("{0} {1} {2}", n, q, a); } x.Stop(); Console.Error.WriteLine("{0}", x.Elapsed); } } ``` [Answer] ## C with GMP (621 bytes, fast) I've tried to be fast and short, but favoured fast. This implementation uses a slightly improved version of the number-theoretic speedup I mentioned in a comment on [aditsu's answer](https://codegolf.stackexchange.com/a/61003/194). Save as `pseudobinary.c` and compile with `gcc pseudobinary.c -lgmp -o pseudobinary`. Note that this allocates so much memory for large inputs that you will need to compile it for a 64-bit platform. ``` #include <gmp.h> int main(int y,char*z[]){int i,n,b,c,e,f,m,*j,*k,*l,*r,*h;char *d,*s;mpz_t B,I,Q;i=atoi(z[1]);n=i;for(b=0;n%10<1;++b)n/=10;for(;n%2<1;++b)n/=2;for(;n%5<1;++b)n/=5;if(n<2)--b;d=calloc(n,1);j=calloc(n,sizeof(int));r=calloc(99,sizeof(int));c=2;d[1]=1;*j=r[1]=e=1;l=j+1;for(s=0;!s;++c){r[c]=e=e*10%n;k=l;for(h=j;h<k;h++){f=*h;m=(e+f)%n;if(d[m]<1){*l++=m;if(m<1){s=malloc(99);memset(s,48,99);for(f=c;f;f=d[m=(m+n-r[f])%n])s[c-f]++;s[c]=0;h=k;}d[m]=c;}}}f=strlen(s);s[f]=48;s[f+b]=0;mpz_init_set_str(B,s,10);mpz_init_set_si(I,i);mpz_init(Q);mpz_divexact(Q,B,I);d=mpz_get_str(0,10,Q);printf("%s\n",d);return 0;} ``` ### Loop version for timing (751 bytes) ``` #include <gmp.h> char **v;int main(){int i,n,b,c,e,f,m,*j,*k,*l,*r,*h;char *d,*s;mpz_t B,I,Q;v=calloc(10001,sizeof(char*));v[1]=s=malloc(99);memset(s,48,99);*s=49;s[1]=0;for(i=0;++i<10001;){n=i;for(b=0;n%10<1;++b)n/=10;for(;n%2<1;++b)n/=2;for(;n%5<1;++b)n/=5;d=calloc(n,1);j=calloc(n,sizeof(int));r=calloc(99,sizeof(int));c=2;d[1]=1;*j=r[1]=e=1;l=j+1;for(;!v[n];++c){r[c]=e=e*10%n;k=l;for(h=j;h<k;h++){f=*h;m=(e+f)%n;if(d[m]<1){*l++=m;if(m<1){v[n]=s=malloc(99);memset(s,48,99);for(f=c;f;f=d[m=(m+n-r[f])%n])s[c-f]++;s[c]=0;h=k;}d[m]=c;}}}free(d);free(j);free(r);s=v[n];f=strlen(s);s[f]=48;s[f+b]=0;mpz_init_set_str(B,s,10);mpz_init_set_si(I,i);mpz_init(Q);mpz_divexact(Q,B,I);d=mpz_get_str(0,10,Q);printf("%s\n",d);free(d);s[f+b]=48;s[f]=0;}return 0;} ``` ### Ungolfed loop version ``` #include <gmp.h> #include <stdio.h> #include <stdlib.h> #include <string.h> char **cache; int main() { int i,n,shift,_kb,km,key,m,*ks,*ksi,*nksi,*res,*ii; char *d,*s; mpz_t B,I,Q; cache = calloc(10001,sizeof(char*)); if (!cache) { printf("Failed to malloc cache\n"); return 1; } cache[1]=s = malloc(99); memset(s,48,99); *s=49; s[1]=0; for (i=0;++i<10001;) { n=i; for(shift=0;n%10<1;++shift)n/=10; for(;n%2<1;++shift)n/=2; for(;n%5<1;++shift)n/=5; d = calloc(n,1); if (!d) { printf("Failed to malloc d\n"); return 1; } ks = calloc(n,sizeof(int)); if (!ks) { printf("Failed to malloc ks\n"); return 1; } res = calloc(99,sizeof(int)); if (!res) { printf("Failed to malloc res\n"); return 1; } _kb = 2; d[1] = 1; *ks = res[1] = km = 1; nksi = ks + 1; for(;!cache[n];++_kb) { res[_kb] = km = km*10%n; ksi = nksi; for (ii = ks; ii < ksi; ii++) { key = *ii; m = (km + key) % n; if (d[m] < 1) { *nksi++ = m; if (m < 1) { cache[n] = s = malloc(99); if (!s) { printf("Failed to malloc s\n"); return 1; } memset(s,48,99); for(key=_kb;key;key = d[m = (m + n - res[key]) % n])s[_kb-key]++; s[_kb]=0; ii = ksi; // break } d[m] = _kb; } } } free(d); free(ks); free(res); // Add shift * '0' s=cache[n]; key=strlen(s); s[key]=48; s[key+shift]=0; // convert to big integer, divide, print mpz_init_set_str(B,s,10); mpz_init_set_si(I,i); mpz_init(Q); mpz_divexact(Q,B,I); d = mpz_get_str(0,10,Q); if (!s) { printf("Failed to malloc quotient\n"); return 1; } printf("%s\n", d); free(d); // Remove shift * '0' s[key+shift]=48; s[key]=0; } return 0; } ``` [Answer] # C + GMP, 669 This is really fast for smallish numbers; it starts to choke when the result has more than 64 digits. ``` #include<gmp.h> #define B(x)(int)((x*(long)k)%n); int*M,*H,P[99],n,x,p,q=2,e=1,k=10,y,f,z;char*E,C[99];int b(int k,int t){int j=E[k],a=1<<(j-2);if(j<2){C[t]=49;return 1;}x=(int)((k+n-P[j]*(long)H[k]%n)%n);if(x)b(x,t);return a+b(H[k],t-a);}int main(){scanf("%d",&n);E=calloc(n+1,1);M=calloc(n+1,4);H=malloc(n*4);M[1]=E[1%n]=P[1]=1;while(!E[0]){P[++e]=k;p=q;for(x=0;++x<p;){y=B(M[x])if(E[n-y]){E[0]=e;H[0]=M[x];break;}}if(!E[x=0])while(++x<p){y=B(M[x])for(z=0;z<p;++z){f=y+M[z];if(f>=n)f-=n;if(!E[f]){E[f]=e;H[f]=M[x];M[q++]=f;}}}k=B(k)}memset(C,48,98);C[99]=0;x=b(0,97);mpz_t m,r;mpz_init(r);mpz_init_set_str(m,C+98-x,10);mpz_fdiv_q_ui(r,m,n);puts(mpz_get_str(C,10,r));} ``` Version that loops to 10000 (671 bytes): ``` #include<gmp.h> #define B(x)(int)((x*(long)k)%n); #define N 10001 int M[N],H[N],P[99],n=0,x,p,q,e,k,y,f,z;char E[N],C[99];int b(int k,int t){int j=E[k],a=1<<(j-2);if(j<2){C[t]=49;return 1;}x=(int)((k+n-P[j]*(long)H[k]%n)%n);if(x)b(x,t);return a+b(H[k],t-a);}int main(){while(++n<N){memset(E,M[0]=0,n);M[1]=E[1%n]=P[1]=e=1;q=2;k=10;while(!E[0]){P[++e]=k;p=q;for(x=0;++x<p;){y=B(M[x])if(E[n-y]){E[0]=e;H[0]=M[x];break;}}if(!E[x=0])while(++x<p){y=B(M[x])for(z=0;z<p;++z){f=y+M[z];if(f>=n)f-=n;if(!E[f]){E[f]=e;H[f]=M[x];M[q++]=f;}}}k=B(k)}memset(C,48,98);C[99]=0;x=b(0,97);mpz_t m,r;mpz_init(r);mpz_init_set_str(m,C+98-x,10);mpz_fdiv_q_ui(r,m,n);puts(mpz_get_str(C,10,r));}} ``` Here are some commands for testing my code as well as my competitors', and the results on my laptop: ``` ls -l *.c* -rw-r--r-- 1 aditsu aditsu 669 Oct 27 15:01 mult-aditsu-single.c -rw-r--r-- 1 aditsu aditsu 671 Oct 27 15:01 mult-aditsu.c -rw-r--r-- 1 aditsu aditsu 3546 Oct 27 15:01 mult-anatoly.c -rw-r--r-- 1 aditsu aditsu 6175 Oct 27 15:01 mult-anders.cpp -rw-r--r-- 1 aditsu aditsu 621 Oct 27 15:01 mult-peter-single.c -rw-r--r-- 1 aditsu aditsu 751 Oct 27 15:01 mult-peter.c gcc -w -march=native -O3 mult-aditsu-single.c -lgmp -o mult-aditsu-single gcc -w -march=native -O3 mult-aditsu.c -lgmp -o mult-aditsu gcc -w -march=native -O3 mult-peter-single.c -lgmp -o mult-peter-single gcc -w -march=native -O3 mult-peter.c -lgmp -o mult-peter gcc -w -march=native -O3 --std=c99 mult-anatoly.c -o mult-anatoly g++ --std=c++11 -march=native -O3 mult-anders.cpp -o mult-anders for i in {1..5}; do time ./mult-anders mult-anders.txt; done ./mult-anders mult-anders.txt 0.34s user 0.00s system 99% cpu 0.344 total ./mult-anders mult-anders.txt 0.36s user 0.00s system 99% cpu 0.358 total ./mult-anders mult-anders.txt 0.34s user 0.00s system 99% cpu 0.346 total ./mult-anders mult-anders.txt 0.35s user 0.00s system 99% cpu 0.347 total ./mult-anders mult-anders.txt 0.34s user 0.00s system 99% cpu 0.344 total for i in {1..5}; do ./mult-anatoly mult-anatoly.txt; done Time: 0.254416 Time: 0.253555 Time: 0.245734 Time: 0.243129 Time: 0.243345 for i in {1..5}; do time ./mult-peter > mult-peter.txt; done ./mult-peter > mult-peter.txt 0.14s user 0.00s system 99% cpu 0.137 total ./mult-peter > mult-peter.txt 0.15s user 0.00s system 97% cpu 0.153 total ./mult-peter > mult-peter.txt 0.15s user 0.00s system 99% cpu 0.149 total ./mult-peter > mult-peter.txt 0.15s user 0.00s system 99% cpu 0.150 total ./mult-peter > mult-peter.txt 0.14s user 0.00s system 99% cpu 0.138 total for i in {1..5}; do time ./mult-aditsu > mult-aditsu.txt; done ./mult-aditsu > mult-aditsu.txt 0.06s user 0.00s system 95% cpu 0.058 total ./mult-aditsu > mult-aditsu.txt 0.05s user 0.00s system 97% cpu 0.055 total ./mult-aditsu > mult-aditsu.txt 0.06s user 0.00s system 99% cpu 0.056 total ./mult-aditsu > mult-aditsu.txt 0.05s user 0.00s system 99% cpu 0.054 total ./mult-aditsu > mult-aditsu.txt 0.05s user 0.00s system 98% cpu 0.055 total md5sum *.txt 6eef8511d3bc5769b5d9218be2e00028 mult-aditsu.txt 6eef8511d3bc5769b5d9218be2e00028 mult-anatoly.txt 6eef8511d3bc5769b5d9218be2e00028 mult-anders.txt 6eef8511d3bc5769b5d9218be2e00028 mult-peter.txt ``` [Answer] # T-SQL, 164 156 155 154 159 bytes (-1 byte. Thanks Jonathan!) (-1 more because why do I have trailing spaces on lines? SMH) (+5 realized my golfing broke things) ``` create function b(@ int) returns int as begin declare @b varchar(max)='',@i int=@ while @>0SELECT @b=cast(@%2 as varchar)+@b,@/=2 return cast(@b as int)/@i end ``` I don't know why I keep coming back to these questions where I'm supposed to convert to Binary... T-SQL doesn't know how to do that right. In any case, here's a [SQLFiddle](http://sqlfiddle.com/#!6/9064e/1/0). Un-golfed: ``` create function binarySquare(@id int) returns int as BEGIN ``` Most of this stuff is required to write a function in T-SQL, as far as I'm aware. ``` declare @bin nvarchar(max) = '' ``` Create a blank string that we're going to store as our binary number. ``` declare @id2 int = @id ``` Save the input value for use at the end. It seems like there should be a way to use the original input even if we change the value, but I can't find one. ``` while @id>0 BEGIN SET @bin = cast(@id%2 as varchar(1)) + @bin ``` So we take our original input, MOD it with 2 to find the remainder, and that's going to be our next smallest digit. For example, 5%2 = 1 ``` SET @id = @id/2 ``` Then we take our number, and divide it in half. Because it's an `int` type, it rounds it down to the nearest whole number, so 5/2 = 2. END We then loop through this until the value is 0. So we end up with 5%2 = 1 5/2 = 2 2%2 = 0 2/2 = 1 1%2 = 1 1/2 = 0 which gives us our binary string value of 101. ``` declare @binNum int = (SELECT cast(@bin as int)) ``` We take our binary string and convert it back to an `int` again. ``` return @binNum/@id2 ``` We return our binary string `int` divided by our original value, per the origin of the question. ``` END ``` [Answer] # [Julia](https://julialang.org), 38 bytes (brute force approach) ``` ~n=(i=0;while"$((i+=1)n)"⊈"01"end;i) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6FjfV6vJsNTJtDazLMzJzUpVUNDQytW0NNfM0lR51dSgZGCql5qVYZ2pCVQeVFmfmpSsEFGXmlaRxRStoVCrYKtRVWCs4FICFNJRUjTIVDk9XUNU1NMgEyqlmxuQp6ShU6ChUAkmtSk1NhbT8IoUKhcw8BUMrI1OFWIjJMPcAAA) * -7 bytes (!!) thanks to MarcMush: rewrite with `⊈` instead of `maximum` * -1 byte thanks to MarcMush: increment `i` inside the loop evaluation [Answer] # [Pyth](https://pyth.readthedocs.io), 8 bytes ``` fq`;{`*Q ``` **[Try it here.](https://pyth.herokuapp.com/?code=fq%60%3B%7B%60%2aQ&input=21&debug=0)** --- # How? ``` fq`;{`*Q - Full program. f - First input where the condition is truthy over [1, ∞) *Q - The product of the input and the current number ` - Converted to String. { - Deduplicated. q - Is equal to? `; - The string representation of the innermost lambda variable, T, which is "10". - Output implicitly. ``` This pretty much relies on the fact that numbers do not have trailing zeros, and `1` always occurs before `0` in a positive integer only consisting of `0`s and `1`s. [Answer] # Ruby, 46 bytes I should really eliminate the while loop with an alternative loop. ``` n,k=gets,0;$_="#{n.to_i*k+=1}"while/[^01]/;p k ``` Edit: Thanks @manatwork for shaving off 1 byte! Edit2: Thanks @histocraft for the insane 9 bytes! Edit: Thanks @manatwork again for shaving off 7 bytes! [Answer] # Scala, 114 Bytes ``` val i=scala.io.StdIn.readInt;Stream.from(1).foreach{x=>if((i*x+"").map{_.asDigit}.max<2){print(x);System.exit(0)}} ``` Readable version ``` val i=scala.io.StdIn.readInt Stream.from(1).foreach{x => if((i*x+"").map{_.asDigit}.max<2) { print(x) System.exit(0) } } ``` [Answer] # gawk4 brute force, 28+2 = 30 bytes ``` {while(++n*$0~/[2-9]/);}$0=n ``` Needs to be called with the `-M` option for using big numbers. Of course this is ridiculously slow, using big numbers slows it down even more, but theoretically the input is not limited, and RAM usage is negligible. ### Usage example ( if you got time to waste `;)`) ``` echo 27 | awk -M '{while(++n*$0~/[2-9]/);}$0=n' ``` # gawk4 optimized, 69+2 = 71 bytes ``` {for(;!a[0];NR*=10)for(i in a)a[j=(s=a[i]+NR)%$0]?0:a[j]=s}$0=a[0]/$0 ``` Well, this ended up being a clone of aditsu's answer. After looking at [this question](https://math.stackexchange.com/questions/388165/how-to-find-the-smallest-number-with-just-0-and-1-which-is-divided-by-a-give) I was still figuring out how to code the subset-sum part, when I couldn't resist looking at the other answers here. In awk array elements have the (strange ?) behaviour that if you compare a non-existing element to something it is somehow initialized as empty before being compared (I'll admit that I'm not quite sure about what is happening there). So after checking `!a[0]` the `for(i in a)` loop starts even without initializing `a[$0]` to `0` as aditsu did. Of course the `-M` option has to be used for this too. Though it is rather fast it is still remarkably slower than Python. For `79992` this takes around 14 seconds on my 2GHz Core2Duo. And I wouldn't say it works for inputs up to 2^31, because in the worst case it has to build an array of big numbers (gawk4 uses GMP for this), which has the size of the input number. As a 'bonus' large arrays are very very slow in awk... ]
[Question] [ Given any unsigned 16 bit integer, convert its *decimal form* (i.e., base-10) number into a 4x4 ASCII grid of its bits, with the most-significant bit (MSB) at the top left, least-significant bit (LSB) at bottom right, read across and then down (like English text). ## Examples ### Input: 4242 ``` +---+---+---+---+ | | | | # | +---+---+---+---+ | | | | | +---+---+---+---+ | # | | | # | +---+---+---+---+ | | | # | | +---+---+---+---+ ``` ### Input: 33825 ``` +---+---+---+---+ | # | | | | +---+---+---+---+ | | # | | | +---+---+---+---+ | | | # | | +---+---+---+---+ | | | | # | +---+---+---+---+ ``` ## Specific Requirements 1. Input *must* be in decimal (base-10), however you may convert to binary any way you wish (including using language built-ins, if available). 2. Output table format must match *exactly*. This means you must use the specific ASCII characters (`-`, `+`, and `|`) for the table grid lines as shown, each cell's interior is 3 characters, and *true* bits are represented by `#` while *false* is represented by a space (). 3. Leading or trailing whitespace is *not permitted.* Final newline is *required*. 4. Bit order must match the examples as described. ## Allowances 1. Input must be a base-10 number on the command line, standard input, or user input, but *must not* be hard-coded into your source code. May the clearest shortest code win! :-) [Answer] # J, 26 bytes ``` (' ';' # '){~4 4$_16{.#: ``` An anonymous verb. Thankfully, J is very good at drawing boxes. Let's try it out: ``` f =. (' ';' # '){~4 4$_16{.#: f 4242 +---+---+---+---+ | | | | # | +---+---+---+---+ | | | | | +---+---+---+---+ | # | | | # | +---+---+---+---+ | | | # | | +---+---+---+---+ ``` As some commenters have mentioned, the way J draws boxes is system-dependent: on some platforms, this code will work under the default settings, but on others, the boxes will be drawn using Unicode line drawing characters. (The commands [`9!:6` and `9!:7`](http://www.jsoftware.com/jwiki/Vocabulary/Foreigns#m9) allow you to query and set the characters to draw boxed values with, respectively.) [Answer] # JavaScript (ES6), 102 ... or 96 using `return` instead of `console.log`. Test running the snippet below in an EcmaScript 6 compliant browser. ``` f=n=>{for(o=h=` +---+---+---+---+ `,z=16;z--;n/=2)o=(z&3?'':h+'|')+` ${' #'[n&1]} |`+o;console.log(o)} // TEST console.log=x=>O.innerHTML=x+O.innerHTML function test(n) { f(n); console.log(n); } ``` ``` <input id=I value=4680><button onclick='test(+I.value)'>-></button> <pre id=O></pre> ``` [Answer] # [Befunge](http://www.esolangs.org/wiki/Befunge)-93, 196 ~~218~~ bytes ``` &00p12*v>>4>"---+",v v < v*:*:*:< | :-1,,,< # >:*2/10p^ >"+",25*,10g| > #v^# $< @ 25*,^ >4" |",,v ,*<> v>"#",00g10g-00p 10g |`-1g01g00 <>48^ v>" ",10g >2/10p>"| ",,1-:#^_$>^ ``` ### To run the program... 1. Go to the [online interpreter](http://www.quirkster.com/iano/js/befunge.html). 2. Paste this code in the big text box. 3. Click `Show`. 4. Input the desired number in the `Input` box. 5. Click `Run`. (Or change `Slow` to something like 5 milliseconds and then click `Show`.) 6. Ta-da! Output for 4242: ``` +---+---+---+---+ | | | | # | +---+---+---+---+ | | | | | +---+---+---+---+ | # | | | # | +---+---+---+---+ | | | # | | +---+---+---+---+ ``` Output for 33825: ``` +---+---+---+---+ | # | | | | +---+---+---+---+ | | # | | | +---+---+---+---+ | | | # | | +---+---+---+---+ | | | | # | +---+---+---+---+ ``` ## Explanation Oh goodness, what have I got myself into? Well, here goes! (Irrelevant code is replaced with `.`s.) ### Part 1: Get input (store in 0,0) and calculate 32768 (store in 1,0). ``` &00p12*v> v*:*:*:< >:*2/10p^ ``` ### Part 2: Print out "+---+---+---+---". ``` >4>"---+",v | :-1,,,< ``` ### Part 3: Print "+" and a newline and check to see if (1,0) is 0 (i.e. we're done). If so, terminate. Otherwise, continue. ``` ........... v < | ....... # >"+",25*,10g| v.# $< @ >4" |",,v ... ``` ### Part 4: Get binary digits of input, updating (0,0) and (1,0) as we go along. Print the right things. I take advantage of Befunge's wrap-around behavior. ``` ..... >4" |",,v ,*<. v>"#",00g10g-00p 10g |`-1g01g00 <>48^ v>" ",10g >2/10p>"| ",,1-:#^_... ``` ### Part 5: Print a newline and go back to the part that prints "+---+---+---+---+". Wrap-around trick is used. ``` > #.^. .. . 25*,^ ......... ...> ................ ... ......... ..... ........ .................._$>^ ``` ### Ta-da! [Answer] # Julia, ~~156~~ 143 bytes ``` n->(p=println;l="+"*"---+"^4;for i=1:4 p(l,"\n| ",join([j>"0"?"#":" "for j=reshape(split(lpad(bin(n),16,0),""),4,4)[:,i]]," | ")," |")end;p(l)) ``` Ungolfed: ``` function f(n::Int) # Convert the input to binary, padded to 16 digits b = lpad(bin(n), 16, 0) # Split b into a 4x4 matrix m = reshape(split(b, ""), 4, 4) # Store the line separator for brevity l = "+" * "---+"^4 # Print each column of the matrix as a row for i = 1:4 println(l, "\n| ", join([j > "0" ? "#" : " " for j = m[:,i]], " | "), " |") end # Print the bottom of the table println(l) end ``` [Try it online](http://goo.gl/Z44JNU) [Answer] # Python 2, ~~157~~ ~~153~~ ~~151~~ 146 bytes ``` J=''.join;R='+---'*4;i=format(input(),'016b') print J(R+'+\n|'+J(' '+('#'if int(l)else' ')+' |'for l in i[n*4:-~n*4])+'\n'for n in range(4)),R+'+' ``` Thanks to Morgan Thrapp for saving 4 bytes, and to Jonathan Frech for saving 5. ## Usage ``` $ python test.py 33825 +---+---+---+---+ | # | | | | +---+---+---+---+ | | # | | | +---+---+---+---+ | | | # | | +---+---+---+---+ | | | | # | +---+---+---+---+ ``` [Answer] # GNU sed + dc, 116 Score includes +1 for `-r` flags to `sed`: ``` s/.*/dc -e2o&p/e : s/^.{,15}$/0&/;t s/./| & /g s/.{16}/\n+---+---+---+---+\n&|/g y/01/ #/ s/\n([-+]+)(.*)/\1\2\n\1/ ``` Test output: ``` $ { echo 4242 ; echo 33825 ; } | sed -rf 16bitgrid.sed +---+---+---+---+ | | | | # | +---+---+---+---+ | | | | | +---+---+---+---+ | # | | | # | +---+---+---+---+ | | | # | | +---+---+---+---+ +---+---+---+---+ | # | | | | +---+---+---+---+ | | # | | | +---+---+---+---+ | | | # | | +---+---+---+---+ | | | | # | +---+---+---+---+ $ ``` --- Alternatively: # Pure sed, 146 You might think it's cheating to use `sed`'s GNU extension to eval a `dc` command. In that case, we can do this a little differently, according to [this meta-answer](http://meta.codegolf.stackexchange.com/a/5349/11259). Of course the question clearly states that input *must* be in base 10, but here I'm attempting to claim that we can override that for `sed` answers and use unary (base 1) instead. ``` : s/11/</g s/<([ #]*)$/< \1/ s/1/#/ y/</1/ t :a s/^.{,15}$/0&/;ta s/./| & /g s/.{16}/\n+---+---+---+---+\n&|/g y/01/ #/ s/\n([-+]+)(.*)/\1\2\n\1/ ``` ### Test output Using `printf` to generate the necessary unary string: ``` $ printf "%33825s" | tr ' ' 1 | sed -rf 16bitgrid.sed +---+---+---+---+ | # | | | | +---+---+---+---+ | | # | | | +---+---+---+---+ | | | # | | +---+---+---+---+ | | | | # | +---+---+---+---+ $ ``` [Answer] # Ruby, ~~118~~ 114 ``` b="%016b"%gets l=?++"---+"*4 1.upto(16){|i|puts l if i%4==1 print"| #{b[i-1]==?0?' ':?#} " puts ?|if i%4<1} puts l ``` thanks for @w0lf for saving some characters. [Answer] # C++11, ~~193~~ ~~191~~ ~~190~~ ~~176~~ 172 bytes My first solution on codegolf ever, so do not blame me. ``` #include<iostream> int n,j,i=65536;int main(){std::cin>>n;for(;j<9;){for(int k:{0,0,0,0})if(j%2)printf("| %s",n&(i/=2)?"# ":" ");else printf("+---");puts(j++%2?"|":"+");}} ``` Ungolfed ``` #include <iostream> int n, i = 65536, j; int main() { std::cin >> n; for (; j < 9;) { for(int k:{0,0,0,0}) { if (j % 2) { printf("| %s", n & (i /= 2) ? "# " : " "); } else { printf("+---"); } } puts(j++ % 2 ? "|" : "+"); } } ``` Previous version ``` #include <iostream> using namespace std; int n, i = 65536, j; int main() { cin >> n; for (; j < 9;) { for(int k:{0,0,0,0}) { if (j % 2) { cout << "| " << (n & (i /= 2) ? "# " : " "); } else { cout << "+---"; } } cout << (j++ % 2 ? "|\n" : "+\n"); } } ``` [Answer] # Pyth, 37 bytes ``` Jj*3\-*5\+JVc4_m@" #".>Qd16jd.i*5\|NJ ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=Jj*3%5C-*5%5C%2BJVc4_m%40%22+%23%22.%3EQd16jd.i*5%5C|NJ&input=4242&test_suite_input=4242%0A33825&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=Jj*3%5C-*5%5C%2BJVc4_m%40%22+%23%22.%3EQd16jd.i*5%5C|NJ&input=4242&test_suite=1&test_suite_input=4242%0A33825&debug=0) ### Explanation: ``` Jj*3\-*5\+J *3\- the string "---" *5\+ the string "+++++" j join second by first string: "+---+---+---+---+" J save in J J print J Vc4_m@" #".>Qd16jd.i*5\|NJ m 16 map each d in [0, 1, ..., 15] to: .>Qd input number Q shifted to the right by d @" #" and take the ^th char in " #" (modulo 2) _ reverse this list of chars c4 split into 4 groups V for each group N in ^: *5\| the string "|||||" .i N interleave ^ with N jd join chars with spaces and print J print J ``` [Answer] # CJam, ~~43~~ 41 bytes ``` '+5*'-3**N+ri2bG0e[4/{" #"f='|5*.\S*N2$}/ ``` Definitely golfable, but it's a start I guess. Generates the top row, then for each 4 bits it creates an even row and copies the previous odd row. [Try it online](http://cjam.aditsu.net/#code='%2B5*'-3**N%2Bri2bG0e%5B4%2F%7B%22%20%23%22f%3D'%7C5*.%5CS*N2%24%7D%2F&input=12066). [Answer] # Python 2, ~~122~~ ~~121~~ 120 bytes ``` n=bin(4**8+input())[3:] i=0 exec"print'| %s |'%' | '.join(' #'[x>'0']for x in n[:4])*i or'+---'*4+'+';n=n[4*i:];i^=1;"*9 ``` -1 byte thanks to @xnor's neat `4**8+` trick. The main printing is done by looping 9 times, selecting the appropriate row for odd/even. [Answer] ## Python 2, 94 ``` n=input() s=();exec"s=(' #'[n%2],)+s;n/=2;"*16 a='+---'*4+'+\n' print(a+'| %s '*4+'|\n')*4%s+a ``` The idea is to take the pattern ``` +---+---+---+---+ | _ | _ | _ | _ | +---+---+---+---+ | _ | _ | _ | _ | +---+---+---+---+ | _ | _ | _ | _ | +---+---+---+---+ | _ | _ | _ | _ | +---+---+---+---+ ``` except with `%s` in place of blanks and perform tuple substitution. The tuple looks like ``` ('#', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#') ``` It is created by taking taking off digits from the input in binary and adding the corresponding symbol to the front of the tuple. An expression with explicit tuple gave equal length. ``` %tuple(' #'[c>'0']for c in bin(input()+4**8)[3:]) ``` Thanks to Sp3000 for 2 bytes. [Answer] # PowerShell, ~~203~~ ~~188~~ 182 Bytes ``` param($a)$l="+---+---+---+---+";$l;$b=([int64][convert]::ToString($a,2)).ToString(@(,"0"*16)-join'');@(1..16|%{if($b[$_-1]-eq'1'){"| # "}else{"| "};if($_%4-eq0){"|`n$l`n"}})-join'' ``` Edit - saved 15 bytes by changing the order that `|` are drawn, so we can dump the `.TrimEnd("|")` on the output and instead convert the for-loop into a subcode block that produces an array Edit2 - saved another 6 bytes by eliminating need for saving into the `$o` variable and just outputting with `-join''` directly. Ooooooooof. Drawing in PowerShell is *hard*. Working with binary digits in PowerShell is *hard*. Uses built-ins to `[convert]` the input integer to a string representation in binary, then re-cast back to an `[int64]` so we can re-call `.ToString()` in order to prepend/pad the appropriate number of zeroes. (Note that creating an array of strings and joining them `@(,"0"*16)-join''` is 1 character shorter than the literal string `"0000000000000000"`) Then, take a simple for-loop `1..16|%{...}` checking each digit to build up our output array, then finally `-join''` that back together. --- ### Previous, 188 ``` param($a)$l="+---+---+---+---+";$l;$b=([int64][convert]::ToString($a,2)).ToString(@(,"0"*16)-join'');$o=@(1..16|%{if($b[$_-1]-eq'1'){"| # "}else{"| "};if($_%4-eq0){"|`n$l`n"}});$o-join'' ``` --- [Answer] # Javascript (ES6), ~~216~~ 207 bytes Defines an anonymous function. ``` i=>(","+("0".repeat(16)+i.toString(2)).slice(-16).split``.map((v,l,a)=>l%4<1?"| "+a.slice(l,l+4).map(v=>v?"#":" ").join` | `+" |":"").filter(v=>!!v).join`,`+",").replace(/,/g, ` +---+---+---+---+ `).slice(1) ``` Thanks to ETHproductions for tips! [Answer] # CJam, 62 bytes ``` "+---| "4/{4*_c+N+}%4*_0=]sqi2bG0e[ee{~{_9*\4%5*-K+'#t0}&;}/ ``` [Try it online](http://cjam.aditsu.net/#code=%22%2B---%7C%20%20%20%224%2F%7B4*_c%2BN%2B%7D%254*_0%3D%5Dsqi2bG0e%5Bee%7B~%7B_9*%5C4%255*-K%2B'%23t0%7D%26%3B%7D%2F&input=4242). [Answer] # Pyth, 50 bytes ``` j.i*5]<3*5"+---"ms.i*5\|dc4mj@" #"qd\1*2\ .[Z16.BQ ``` Explanation will have to wait until another time, I'm posting this on my phone! [Answer] # Ruby, 102 ``` n=gets.to_i print j="+---"*4+"+ " 19.downto(0){|i|print i%5>0?"| #{((n>>i*4/5)%2*3+32).chr} ":"| "+j} ``` **Algorithm** Print a horizontal divider Loop 20 times (19..0) If loop number does not divide by 5, convert into a number in the range 16..0 by multiplying by 4/5. Print a space (ascii 32) or `#` (ascii 32+3=35) preceded by `|` and followed by a space. If loop number divides by 5, print a terminating |, newline, and a horizontal divider identical to the first. [Answer] # Perl, 103 bytes ``` $_=(($l='+---'x4 .'+ ').'| x 'x4 .'| ')x4 .$l;@n=(sprintf'%016b',<>)=~/./g;s/x/$n[$x++]?'#':$"/eg;print ``` Lots of string repetition to make a grid of `x`s, convert the input to binary and then `s///` the `x`s to `#` or `$"` () depending on the flag at the specified position (`$x`). [Answer] # PHP, 159 bytes `bingrid16.php`: ``` <?$r=10;while(--$r){if($r%2){echo str_repeat('+---',4).'+';}else{$c=9;echo'|';while(--$c){echo' '.($c%2?'|':($argv[1]&pow(2,$r*2+$c/2-5)?'#':' '));}}echo"\n";} ``` Usage: ``` php bingrid16.php 4242 ``` Nothing fancy, just brute-forced the rendering. I tried another angle using arrays instead of loops, but it was longer at 224 bytes: ``` <?=implode(array_map(function($r)use($argv){return($r%2?str_repeat('+---',4).'+':'|'.implode(array_map(function($c)use($r,$argv){return' '.($c%2?'|':($argv[1]&pow(2,$r*2+$c/2-5)?'#':' '));},range(8,1))))."\n";},range(9,1))); ``` [Answer] # [Perl 5](https://www.perl.org/), ~~85~~ 84 bytes ~~84~~ 83 bytes of code + `-p` flag *-1 byte after Dom reminded me to use a newline* ``` say$\='+'."---+"x4," | ",map y/01/ #/r.' | ',/./g for(sprintf"%016b",$_)=~/..../g}{ ``` [Try it online!](https://tio.run/##DcFBDoIwEADAu6/YLJhKaLttpNx4gj8wMZgIIVG6aTlIRJ/u6gzf0j2I5H4tz52qlUVjTI3PRuNuA9SPnmEl5wkKSlbBBkqTpRGGmA6Z0zQvA@6db6@oy0vVfcj@0fh@ibQhHJtv5GWKcxZzCtZ5J4Z/ "Perl 5 – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 47 bytes ``` b:L16-(0p)4ẇƛƛ‛ #$i`| % `$%;ṅ\|+;\+:3-4*pw5ẋf$Y ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=b%3AL16-%280p%294%E1%BA%87%C6%9B%C6%9B%E2%80%9B%20%23%24i%60%7C%20%25%20%60%24%25%3B%E1%B9%85%5C%7C%2B%3B%5C%2B%3A3-4*pw5%E1%BA%8Bf%24Y&inputs=4242&header=&footer=) A big mess [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), ~~40~~ 36 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) This'll need another pass once I'm properly caffeinated! ``` 5Æ17î-³i+ÃíUs'#iS)ùG ®û3 i|ÃòG)cf ú| ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=NcYxN%2b4ts2krw%2b1VcycjaVMp%2bUcgrvszIGl8w/JHKWNmIPp8&input=NDI0Mg) ``` 5Æ17î-³i+ÃíUs'#iS)ùG ®û3 i|ÃòG)cf ú| :Implicit input of integer U 5Æ :Map the range [0,5) 17î : Repeat the following to length 17 -³ : "-" repeated 3 times i+ : Prepend a "+" Ã :End map í :Interleave with Us : U converted to a string in the following base '#i : "#" prepended with S : A space ) : End base conversion ù : Left pad with spaces to length G : 16 ® : Map each character û3 : Centre pad with spaces to length 3 i| : Prepend a "|" Ã : End map òG : Partitions of length 16 ) :End interleave c :Flatten f :Filter out falsey elements (If the second array being interleaved is shorter than the first, it's padded with null) ú| :Left pad each with "|" to the length of the longest :Implicit output joined with newlines ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 31 bytes ``` \+3-4*\|?b16∆Z\#*2↳ʁ+4ẇṠv"fǏvǏ⁋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJcXCszLTQqXFx8P2IxNuKIhlpcXCMqMuKGs8qBKzThuofhuaB2XCJmx492x4/igYsiLCIiLCI0MjQyIl0=) ``` ? # Input b # To binary 16∆Z # Pad to length 16 with 0s \#* # That many #s, for each bit 2↳ʁ # Pad to length 2 with spaces and mirror \| + # Prepend | to each 4ẇṠ # Divide into rows and stringify each v"f # Interleave with... \+3- # "+---" 4* # Repeated four times Ǐ # Append the first line vǏ # For each line, append the firstt character ⁋ # Join the result by newlines ``` [Answer] # c99 263 bytes golfed: ``` main(int argc,char **argv){short i=atoi(argv[argc-1]);char *t="| # ", *f="| ",*a[16],**p=a,*b="+---+---+---+---+\r\n";while(p<a+16){if((i|0x8000)==i)(*(p++))=t;else(*(p++))=f;i<<=1;}for(p=a;p<a+16;p+=4)printf("%s%s%s%s%s|\n",b,*p,p[1],p[2],p[3]);printf("%s",b);} ``` ungolfed: ``` main(int argc, char **argv) { short i=atoi(argv[argc -1]); char *t ="| # ", *f="| ",*a[16],**p=a,*b="+---+---+---+---+\r\n"; while (p<a+16) { if((i|32768)==i) (*(p++))=t; else (*(p++))=f; i<<=1; } for (p=a;p<a+16;p+=4) printf("%s%s%s%s%s|\n",b,*p,p[1],p[2],p[3]); printf("%s",b); } ``` I just liked to present a bit shifting variant and felt this is the first time its appropriate (even its costing me some bytes, but C can't this challange in bytes even with a chance so I don't care) to use the argc/argv [Answer] # Ruby, 95 Nod to Mhmd for a concise String conversion, but I wanted to try using string methods instead of number methods. ``` ->i{puts g='+---'*4+?+;("%016b"%i).scan(/.{4}/){puts$&.gsub(/./){"| #{$&<?1?' ':?#} "}+"| "+g}} ``` [Answer] # Ruby, 93 A slightly shorter version using only numeric operations. ``` ->i{n=g='+---'*4+"+ ";15.downto(0){|m|n+="| #{[' ',?#][1&i>>m]} " n+="| "+g if m%4<1} puts n} ``` [Answer] ## C# 227 Bytes Golfed: ``` class B{public static string G(short v){string s="",b=System.Convert.ToString(v,2).PadLeft(16,'0');for(int i=9;i>0;){s+=i--%2!=0?"+---+---+---+---+\n":"| "+b[i*2+1]+" | "+b[i*2]+" | "+b[i*2-1]+" | "+b[i*2-2]+" |\n";}return s;}} ``` Indention: ``` class B { public static string G(short v) { string s="",b=System.Convert.ToString(v, 2).PadLeft(16,'0'); for(int i=9;i>0;) s+=i--%2!=0?"+---+---+---+---+\n":"| "+b[i*2+1]+" | "+b[i*2]+" | "+b[i*2-1]+" | "+b[i*2-2]+" |\n"; return s; } } ``` First time I'm trying something like this, tips would be welcome! [Answer] # Python 3, ~~145~~ 144 Bytes Inline: ``` a="|";b="+"+"---+"*4+"\n";r=0,1,2,3;(lambda x:print(b+b.join(a+a.join(" %s "%'# '[x&2**(i+j*4)<1]for i in r)+a+"\n"for j in r)+b))(int(input())) ``` With newlines: ``` a="|" b="+"+"---+"*4+"\n" r=0,1,2,3 lambda x:print(b+b.join(a+a.join(" %s "%'# '[x&2**(i+j*4)<1]for i in r)+a+"\n"for j in r)+b) x(int(input())) ``` Edit: Tanks @manatwork for saving 1 byte [Answer] # x86-16 machine code, IBM PC DOS, 80 bytes Binary: ``` 00000000: b805 09ba 2801 cd21 fec8 741b be3e 01b1 ....(..!..t..>.. 00000010: 04d1 e3c6 0420 7303 c604 2383 c604 e2f1 ..... s...#..... 00000020: ba3c 01cd 21eb dcc3 2b2d 2d2d 2b2d 2d2d .<..!...+---+--- 00000030: 2b2d 2d2d 2b2d 2d2d 2b0d 0a24 7c20 2020 +---+---+..$| 00000040: 7c20 2020 7c20 2020 7c20 2020 7c0d 0a24 | | | |..$ ``` Listing: ``` B8 0905 MOV AX, 0905H ; AH = DOS write string, AL = row counter ROW_LOOP: BA 0128 MOV DX, OFFSET SEP ; show separator row CD 21 INT 21H ; write to console FE C8 DEC AL ; displayed 5 separators? 74 1B JZ EXIT ; if so, exit BE 013E MOV SI, OFFSET ROW+2 ; start SI at location of first bit in row B1 04 MOV CL, 4 ; loop count 4 BIT_LOOP: D1 E3 SHL BX, 1 ; shift MSb into CF C6 04 20 MOV BYTE PTR[SI], ' ' ; reset to space char 73 03 JNC BIT_DONE ; if not CF, leave as a space C6 04 23 MOV BYTE PTR[SI], '#' ; otherwise change to a # BIT_DONE: 83 C6 04 ADD SI, 4 ; increment index 4 bytes E2 F1 LOOP BIT_LOOP ; keep looping through bits BA 013C MOV DX, OFFSET ROW ; show bit column row CD 21 INT 21H ; write to console EB DC JMP ROW_LOOP ; keep looping EXIT: C3 RET ; return to caller SEP DB '+---+---+---+---+',0DH,0AH,'$' ROW DB '| | | | |',0DH,0AH,'$' ``` Callable function, input in `BX` output to `STDOUT`. Example test program: [![enter image description here](https://i.stack.imgur.com/UJ2uq.png)](https://i.stack.imgur.com/UJ2uq.png) [Answer] # [Kotlin](https://kotlinlang.org), 192 bytes ``` {val v=it.toString(2).padStart(16,'0') fun p(){(0..3).map{print("+---")} println("+")} (0..3).map{p() v.subSequence(it*4,(it+1)*4).map{print("| ${if(it>'0')'#' else ' '} ")} println("|")} p()} ``` ## Beautified ``` { val v = it.toString(2).padStart(16, '0') fun p() { (0..3).map { print("+---") } println("+") } (0..3).map { p() v.subSequence(it *4, (it +1) *4).map {print("| ${if (it > '0') '#' else ' '} ")} println("|") } p() } ``` ## Test ``` var b:(Int) -> Unit = {val v=it.toString(2).padStart(16,'0') fun p(){(0..3).map{print("+---")} println("+")} (0..3).map{p() v.subSequence(it*4,(it+1)*4).map{print("| ${if(it>'0')'#' else ' '} ")} println("|")} p()} fun main(args: Array<String>) { b(255) } ``` ]
[Question] [ I call this sequence "the Jesus sequence", because it is the *sum of mod*.</pun> For this sequence, you take all the positive integers *m* less than the input *n*, and take the sum of *n* modulo each *m*. In other words: $$a\_n = \sum\_{m=1}^{n-1}{n\bmod m}$$ For example, take the term *14*: ``` 14 % 1 = 0 14 % 2 = 0 14 % 3 = 2 14 % 4 = 2 14 % 5 = 4 14 % 6 = 2 14 % 7 = 0 14 % 8 = 6 14 % 9 = 5 14 % 10 = 4 14 % 11 = 3 14 % 12 = 2 14 % 13 = 1 0+0+2+2+4+2+0+6+5+4+3+2+1=31 ``` Your goal here is to write a function that implements this sequence. You should take the sequence term (this will be a positive integer from 1 to 231) as the only input, and output the value of that term. This is [OEIS A004125](https://oeis.org/A004125). As always, [standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/62402) apply and the shortest answer in bytes wins! [Answer] # [Haskell](https://www.haskell.org/), 22 bytes ``` f x=sum$mod x<$>[1..x] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwra4NFclNz9FocJGxS7aUE@vIvZ/bmJmnoKtQnpqiXN@XklqXkmxgp2drUJBUWZeiYKeQhoQF6Umpvw3NAEA "Haskell – Try It Online") ### Explanation Yes. [Answer] # [Funky](https://github.com/TehFlaminTaco/Funky), 25 bytes ``` n=>fors=~-i=1i<n)s+=n%i++ ``` Just the Naïve answer, seems to work. [Try it online!](https://tio.run/##SyvNy678n2b7P8/WLi2/qNi2TjfT1jDTJk@zWNs2TzVTW/t/QVFmXolGmoahiabmfwA "Funky – Try It Online") # [Desmos](https://www.desmos.com/calculator), 25 bytes. ``` f(x)=\sum_{n=1}^xmod(x,n) ``` Paste into Desmos, then run it by calling `f`. When pasted into Desmos, the latex looks like this ![](https://a-ta.co/mathjax/%24!ZlxsZWZ0KHhccmlnaHQpPVxzdW1eeF97bj0xfVx0ZXh0e21vZH1cbGVmdCh4LG5ccmlnaHQp.svg) The graph however looks like ![](https://i.gyazo.com/b46a90eaa3fddd3269387480cce10856.png) Although it looks random and all over the place, that's the result of only supporting integers. # [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 9 bytes ``` x=x³x\%S+ ``` ## Explained ``` x=x³x\%S+ x= # Store the input in "x" x # Push the input to the stack. ³x\% # Define a function which gets n%x S # Create a stack from "x" with the previous function. Thus this gets the range from (1,x), and runs (i%x) on each element. + # Get the sum of this stack. ``` [Try it online!](https://tio.run/##Kyooyk/P0zX6/7/CtuLQ5ooY1WDt////G5oAAA "RProgN 2 – Try It Online") # [ReRegex](https://github.com/TehFlaminTaco/ReRegex), 71 bytes ``` #import math (_*)_a$/d<$1_>b$1a/(\d+)b/((?#input)%$1)+/\+a//u<#input >a ``` [Try it online!](https://tio.run/##K0otSk1Prfj/XzkztyC/qEQhN7Ekg0sjXkszPlFFP8VGxTDeLknFMFFfIyZFWzNJX0PDXjkzr6C0RFNVxVBTWz9GO1Ffv9QGIsZll/j/v6EJAA "ReRegex – Try It Online") # [ARBLE](https://github.com/TehFlaminTaco/ARBLE), 19 bytes ``` sum(range(1,a)|a%i) ``` [Try it online!](https://tio.run/##SyxKykn9/7@4NFejKDEvPVXDUCdRsyZRNVPz////hiYA "ARBLE – Try It Online") # [MaybeLater](https://github.com/TehFlaminTaco/MaybeLater), 56 bytes ``` whenf is*{n=0whenx is*{ifx>0{n=n+f%x x--}elseprintn}x=f} ``` [Try it online!](https://tio.run/##y02sTErNSSxJLfr/vzwjNS9NIbNYqzrP1gDEqQBzMtMq7AyAQnnaaaoVChW6urWpOcWpBUWZeSV5tRW2abX/0xRsFTSKUhNTEjV1Df4bmgAA "MaybeLater – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` L%O ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fR9X//39DEwA "05AB1E – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~28~~ ~~27~~ 23 bytes -4 bytes thanks to @daniero. ``` ->n{(1..n).sum{|i|n%i}} ``` [Try it online!](https://tio.run/##KypNqvyflmf7X9cur1rDUE8vT1OvuDS3uiazJk81s7b2f4FCWl60oUnsfwA "Ruby – Try It Online") ## Ruby, 28 bytes ``` f=->n{n>($.+=1)?n%$.+f[n]:0} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y6vOs9OQ0VP29ZQ0z5PFchIi86LtTKo/V@gkBZtaBL7HwA "Ruby – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` %RS ``` **Explanation** ``` %RS R Range(input) [1...n] % Input (implicit) modulo [1...n]->[n%1,n%2...n%n] S Sum of the above ``` [Try it online!](https://tio.run/##y0rNyan8/181KPj///@GJgA "Jelly – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 4 bytes ``` t:\s ``` [Try it online!](https://tio.run/##y00syfn/v8Qqpvj/f0MTAA "MATL – Try It Online") Explanation: ``` t % Duplicate input. Stack: {n, n} : % Range 1...n. Stack: {n, [1...n]} \ % Modulo. Stack: {[0,0,2,2,4,...]} s % Sum. Implicitly display result. ``` [Answer] # R, 20 bytes ``` sum((n=scan())%%1:n) ``` [Try it online!](https://tio.run/##K/r/v7g0V0Mjz7Y4OTFPQ1NTVdXQKk/zv6HJ//8A "R – Try It Online") [Answer] # [Ohm v2](https://github.com/nickbclifford/Ohm), 4 bytes ``` D@%Σ ``` [Try it online!](https://tio.run/##y8/INfr/38VB9dzi//8NTQA "Ohm v2 – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 5 bytes ``` +/⍳|⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wRt/Ue9m2sedS0Ccg@tALKNDAA "APL (Dyalog Unicode) – Try It Online") **How?** Monadic train - `+/` - sum `⊢` - `n` `|` - vectorized modulo `⍳` - the range of `n` [Answer] # [Python 2](https://docs.python.org/2/), 44 bytes ``` lambda n:sum(map(lambda x:x%(n-x),range(n))) ``` [Try it online!](https://tio.run/##LcgxCoAwDAXQ3VP8RUiggjoWvIlLRauCjaVWiKevg77xxSdvp/TFYxjL4cI0O4i97kDBRfpDrdYkjbJJTtaFhJmLPxMUu@C7rm3ZVgBi2iVDDTwplxc "Python 2 – Try It Online") EDIT: Changed range(0,n) to range(n) [Answer] # Rust, 27 characters ``` |n|(1..n).map(|i|n%i).sum() ``` Based on [Should rust anonymous functions fully specify parameter types?](https://codegolf.meta.stackexchange.com/questions/25156/should-rust-anonymous-functions-fully-specify-parameter-types) I assume that return type inference is also fine. [Try it online!](https://tio.run/##LctNCoMwEEDhtZ5iKhRmQALRrio9TJAUBpJR8rNKPHsaqOv3vZBjal8Bb1iQyjg4m2B3R8zBwgdalYpaKSHlzYmVqzyZVMweqQ3bnwcbs0tv4HXpyz2jflHvZ2BJTh44lWuab9rD1X4 "Rust – Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), 16 bytes ``` ~x=sum(x.%(1:x)) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/v67Ctrg0V6NCT1XD0KpCU/N/dEFRZl5JTp5GTkFiikamjpGmjpKVgpIOmFuXqWOsqamQll@kkKmQmadgaGVoGvsfAA "Julia 1.0 – Try It Online") [Answer] # JavaScript (ES6), 26 bytes ``` f=(n,k=n)=>n&&k%n+f(n-1,k) ``` ### Demo ``` f=(n,k=n)=>n&&k%n+f(n-1,k) for(n = 1; n < 30; n++) { console.log('a(' + n + ') = ' + f(n)) } ``` [Answer] # [Python 3](https://docs.python.org/3/), 37 bytes ``` lambda a:sum(a%k for k in range(1,a)) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHRqrg0VyNRNVshLb9IIVshM0@hKDEvPVXDUCdRU/M/SDARSdDAQNOKSwEICooy80o00pSqE2utFKrTNBI1a5U0/wMA "Python 3 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes ``` IΣEN﹪Iθ⊕ι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0V8M3sUDDM6@gtMSvNDcptUhDU8c3P6U0Jx@iolBTR1tbI1MTDKz//zc0@a9blgMA "Charcoal – Try It Online") Link is to the verbose version of the code: ``` Print(Cast(Sum(Map(InputNumber(),Modulo(Cast(q),++(i)))))); ``` [Answer] # [Standard ML (MLton)](http://www.mlton.org/), ~~53~~ 51 bytes ``` fn& =>let fun f 1a=a|f%a=f(% -1)(a+ &mod%)in f&0end ``` [Try it online!](https://tio.run/##TYsxC8IwFIT3/oqjkJIglUbdJN2dXUUJNE8K6YuYp5P/vcYu9qbv7vjyFNspSuL57SPIzcQNXB@DgF4MgvXOf0h5R1qhtUb7DZopDcqM5W66wMOiSsgCh8dzZEGCJkZ2fb7WF65NGU4sW0lnKf@9VKp@0q0YukLJotvjn3cr3q/YHtal68z8BQ "Standard ML (MLton) – Try It Online") **Ungolfed:** ``` fn n => let fun f 1 a = a | f x a = f (x-1) (a + n mod x) in f n 0 end ``` --- ### Previous 53 byte version: ``` fn n=>foldl op+0(List.tabulate(n-1,fn i=>n mod(i+1))) ``` [Try it online!](https://tio.run/##TYyxDgIhDIb3e4rmJsh5BtTNwG7i5mo0mDsMCZSLVF8f6y3S6fvb/2tJcUyRMtaPi@BN9QhorM9xipCXQYlzKLQl93hHR7PAUW@4EoxFSHkSYdBSylWmuRAYWF4BCTIIrhVjy62/Yi95cUL@ky/E9ydH3/2kOxuiA55V18c/7xreN6wPbVBK1i8 "Standard ML (MLton) – Try It Online") **Explanation:** `List.tabulate` takes an integer `x` and a function `f` and generates the list `[f 0, f 1, ..., f(x-1)]`. Given some number `n`, we call `List.tabulate` with `n-1` and the function `fn i=>n mod(i+1)` to avoid dividing by zero. The resulting list is summed with `foldl op+0`. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 45 bytes ``` n->{int m=n,s=0;for(;m-->1;)s+=n%m;return s;} ``` [Try it online!](https://tio.run/##bU49a8MwFNz9K46Awa4/SLsqNnTMEDqETqWD6o8g13oS0nPABP92V07bqR0eB3f37m6QV1kY29HQfq5KW@MYQ@DKidVYPojoD@fZdVL/K/UTNawMbaKdPkbVoBml9zhJRbhFwA/rWXKAq1EtdNCSMztFl7d3SHfx6d0KHIlfSbr5xXZOsnHoUa1U1DdFDF1R7qu96I1LhC6K@lGkPqso1sJ1PDmCF8sq7kGbZ/tRqLAXAQ542jDLfquA8@y506WZuLRhC/fJLm5R1IjbmHY5VI6@lNaO87MPwxKVpt/hS7Tdsn4B "Java (OpenJDK 8) – Try It Online") [Answer] # [Mathematica](https://www.wolfram.com/wolframscript/), 18 bytes ``` #~Mod~i~Sum~{i,#}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X7nONz@lLrMuuDS3rjpTR7lW7X9AUWZeSXRatKFJbOx/AA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~6~~ 5 bytes *Saved 1 byte thanks to @Shaggy* ``` Æ%XÃx ``` [Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=xiVYw3g=&input=MTQ=) ### How it works ``` Implicit: U = input number Æ Create the range [0, U), %XÃ mapping each item X to U%X. U%0 gives NaN. x Sum, ignoring non-numbers. Implicit: output result of last expression ``` [Answer] # [4](https://github.com/urielieli/py-four), 67 bytes **4** doesn't have any *modulo* built in. ``` 3.79960101002029980200300023049903204040310499040989804102020195984 ``` [Try it online!](https://tio.run/##HYo5DoBADAP7fUVWtAg5BxAX/Juaj4WAprBHmqjy7SQPaAODkdkDR5sjSLghGtffAsxOQr8Yyp0ZVXOMRaZc4r7Kc/fRjBc "4 – Try It Online") [Answer] # T-SQL, ~~80~~ 79 bytes *-1 byte thanks to @MickyT* ``` WITH c AS(SELECT @ i UNION ALL SELECT i-1FROM c WHERE i>1)SELECT SUM(@%i)FROM c ``` Receives input from an integer parameter named `@`, something like this: ``` DECLARE @ int = 14; ``` Uses a Common Table Expression to generate numbers from `1` to `n`. Then uses that cte to sum up the moduluses. Note: a cte needs a `;` between the previous statement and the cte. Most code I've seen puts the `;` right before the declaration, but in this case I can save a byte by having it in the input statement (since technically my code by itself is the only statement). [Try it (SEDE)](https://data.stackexchange.com/codegolf/query/edit/770634) --- The less "SQL-y" way is only 76 bytes. This time the input variable is `@i` instead of `@` (saves one byte). This one just does a `while` loop. ``` DECLARE @ int=2,@o int=0WHILE @<@i BEGIN SELECT @o+=@i%@,@+=1 END PRINT @o ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 3 bytes ``` ɽ%∑ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C9%BD%25%E2%88%91&inputs=14&header=&footer=) # [Vyxal](https://github.com/Lyxal/Vyxal) `s`, 2 bytes ``` ɽ% ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=s&code=%C9%BD%25&inputs=14&header=&footer=) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` ÎGIN%+ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//cJ@7p5@q9v//ZkYA "05AB1E – Try It Online") My first 05AB1E program ;) ~~Btw I got two 39s, 1 for JS6 and 1 for python, but I was too late~~ Explanation: ``` ÎGIN%+ Î # Push 0, then input, stack = [(accumulator = 0), I] G # For N in range(1, I), stack = [(accumulator)] IN # Push input, then N, stack = [(accumulator), I, N] % # Calculate I % N, stack = [(accumulator), I % N] + # Add the result of modulus to accumulator ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 5 bytes ``` s%LQS ``` --- ``` s%LQS - Full program, inputs N from stdin and prints sum to stdout s - output the sum of %LQ - the function (elem % N) mapped over S - the inclusive range from 1..N ``` [Try it online!](https://tio.run/##K6gsyfj/v1jVJzD4/39DEwA "Pyth – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 23 bytes ``` ->n{(1..n).sum{|i|n%i}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNQTy9PU6@4NLe6JrMmTzWztvY/SMzQRFMvN7GguqaipkAhLboitvY/AA "Ruby – Try It Online") [Answer] # Julia 0.4, 15 bytes ``` x->sum(x%[1:x]) ``` [Try it online!](https://tio.run/##yyrNyUz8n2b7v0LXrrg0V6NCNdrQqiJW839BUWZeSU6eRpqGoYmm5n8A "Julia 0.4 – Try It Online") [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 14 bytes ``` L,RAdx$p@BcB%s ``` [Try it online!](https://tio.run/##S0xJKSj4/99HJ8gxpUKlwMEp2Um1@P///4YmAA "Add++ – Try It Online") ## How it works ``` L, - Create a lambda function. - Example argument: [7] R - Range; STACK = [[1 2 3 4 5 6 7]] A - Argument; STACK = [[1 2 3 4 5 6 7] 7] d - Duplicate; STACK = [[1 2 3 4 5 6 7] 7 7] x - Repeat; STACK = [[1 2 3 4 5 6 7] 7 [7 7 7 7 7 7 7]] $p - Swap and pop; STACK = [[1 2 3 4 5 6 7] [7 7 7 7 7 7 7]] @ - Reverse; STACK = [[7 7 7 7 7 7 7] [1 2 3 4 5 6 7]] Bc - Zip; STACK = [[7 1] [7 2] [7 3] [7 4] [7 5] [7 6] [7 7]] B% - Modulo each; STACK = [0, 1, 1, 3, 2, 1, 0] s - Sum; STACK = [8] ``` [Answer] ## Windows Batch (CMD), 63 bytes ``` @set s=0 @for /l %%i in (1,1,%1)do @set/as+=%1%%%%i @echo %s% ``` Previous 64-byte version: ``` @set/ai=%2+1,s=%3+%1%%i @if %i% neq %1 %0 %1 %i% %s% @echo %s% ``` [Answer] # [PHP](https://php.net/), 61 bytes *-2 bytes for removing the closing tag* ``` <?php $z=fgets(STDIN);for($y=1;$y<$z;$y++){$x+=$z%$y;}echo$x; ``` [Try it online!](https://tio.run/##K8go@P/fxr4go0BBpco2LT21pFgjOMTF00/TOi2/SEOl0tbQWqXSRqUKSGpra1arVGjbqlSpqlRa16YmZ@SrVFj//29oAgA "PHP – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) `-mx`, 3 bytes ``` N%U ``` [Try it online!](https://tio.run/##y0osKPn/30819P9/QxMF3dwKAA "Japt – Try It Online") ]
[Question] [ Take a matrix of positive integers as input, and **make it explode!** --- The way you explode a matrix is by simply adding zeros around every element, including the outside borders. Input/output formats are optional as always! ### Test cases: ``` 1 ----- 0 0 0 0 1 0 0 0 0 -------------- 1 4 5 2 ----- 0 0 0 0 0 0 1 0 4 0 0 0 0 0 0 0 5 0 2 0 0 0 0 0 0 -------------- 1 4 7 ----- 0 0 0 0 0 0 0 0 1 0 4 0 7 0 0 0 0 0 0 0 0 -------------- 6 4 2 ----- 0 0 0 0 6 0 0 0 0 0 4 0 0 0 0 0 2 0 0 0 0 ``` [Answer] # [Operation Flashpoint](https://en.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language, 182 bytes ``` f={t=_this;c=count(t select 0);e=[0];i=0;while{i<c*2}do{e=e+[0];i=i+1};m=[e];i=0;while{i<count t}do{r=+e;j=0;while{j<c}do{r set[j*2+1,(t select i)select j];j=j+1};m=m+[r,e];i=i+1};m} ``` **Ungolfed:** ``` f= { // _this is the input matrix. Let's give it a shorter name to save bytes. t = _this; c = count (t select 0); // Create a row of c*2+1 zeros, where c is the number of columns in the // original matrix. e = [0]; i = 0; while {i < c*2} do { e = e + [0]; i = i + 1 }; m = [e]; // The exploded matrix, which starts with a row of zeros. i = 0; while {i < count t} do { // Make a copy of the row of zeros, and add to its every other column // the values from the corresponding row of the original matrix. r = +e; j = 0; while {j < c} do { r set [j*2+1, (t select i) select j]; j = j + 1 }; // Add the new row and a row of zeroes to the exploded matrix. m = m + [r, e]; i = i + 1 }; // The last expression is returned. m } ``` **Call with:** ``` hint format["%1\n\n%2\n\n%3\n\n%4", [[1]] call f, [[1, 4], [5, 2]] call f, [[1, 4, 7]] call f, [[6],[4],[2]] call f]; ``` **Output:** [![](https://i.stack.imgur.com/TY9Fu.jpg)](https://i.stack.imgur.com/TY9Fu.jpg) **In the spirit of the challenge:** [![](https://i.stack.imgur.com/Ut1xq.gif)](https://i.stack.imgur.com/Ut1xq.gif) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 byte thanks to Erik the Outgolfer (no need to use swapped arguments for a join) ``` j00,0jµ€Z$⁺ ``` **[Try it online!](https://tio.run/##y0rNyan8/z/LwEDHIOvQ1kdNa6JUHjXu@v//f3S0oY5JrE60qY5RbCwA "Jelly – Try It Online")** Or see a [test suite](https://tio.run/##y0rNyan8/z/LwEDHIOvQ1kdNa6JUHjXu@n90z@F2IMcbioEoEoizHjXuO7Tt0Lb//6O5FKKjDWNjdcC0jkmsTrSpjhGCr2MOZZsBZUCyQDmuWAA "Jelly – Try It Online"). A monadic link accepting and returning lists of lists. ### How? ``` j00,0jµ€Z$⁺ - Link: list of lists, m ⁺ - perform the link to the left twice in succession: $ - last two links as a monad µ€ - perform the chain to the left for €ach row in the current matrix: j0 - join with zeros [a,b,...,z] -> [a,0,b,0,...,0,z] 0,0 - zero paired with zero = [0,0] j - join [a,0,b,0,...,0,z] -> [0,a,0,b,0,...,0,z,0] Z - and then transpose the resulting matrix ``` [Answer] # [Haskell](https://www.haskell.org/), 38 bytes ``` a%l=a:(=<<)(:[a])l f l=(0%)<$>(0<$l)%l ``` [Try it online!](https://tio.run/##BcE7DoAgDADQ3VN0gKQkDP4mUrxI06GDRGIlRr0/vnfoe@5mvau3rAkzUcDEKsGGApZx9IHchiM5C976pbVBhvup7QMHBZinOEvkJa4i/Qc "Haskell – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` FTXdX*0JQt&( ``` Input is a matrix with `;` as row separator. [**Try it online!**](https://tio.run/##y00syfn/3y0kIiVCy8ArsERN4///aEMFE2sFUwWjWAA "MATL – Try It Online") ### Explanation ``` FT % Push [0 1] Xd % Matrix with that diagonal: gives [0 0; 0 1] X* % Implicit input. Kronecker product 0 % Push 0 JQt % Push 1+j (interpreted as "end+1" index) twice &( % Write a 0 at (end+1, end+1), extending the matrix. Implicit display ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 18 bytes ``` Ov"y ®î íZ c p0Ã"² ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=T3YieSCu7iDtWiBjIHAwwyKy&input=WwpbMSAyIDNdCls0IDUgNl0KWzcgOCA5XQpdIC1R) (Uses the `-Q` flag so the output is easier to understand.) Similar to the Jelly answer, but a whole lot longer... ### Explanation The outer part of the code is just a workaround to simulate Jelly's `⁺`: ``` " "² Repeat this string twice. Ov Evaluate it as Japt. ``` The code itself is: ``` y ® î íZ c p0à y mZ{Zî íZ c p0} Ungolfed y Transpose rows and columns. mZ{ } Map each row Z by this function: Zî Fill Z with (no argument = zeroes). íZ Pair each item in the result with the corresponding item in Z. c Flatten into a single array. p0 Append another 0. ``` Repeated twice, this process gives the desired output. The result is implicitly printed. [Answer] ## [Husk](https://github.com/barbuz/Husk), 12 bytes ``` ₁₁ Tm»o:0:;0 ``` Takes and returns a 2D integer array. [Try it online!](https://tio.run/##yygtzv7//1FTIxBxheQe2p1vZWBlbfD////oaEMdIx3jWJ1oEx1THbPYWAA "Husk – Try It Online") ## Explanation Same idea as in many other answers: add zeroes to each row and transpose, twice. The row operation is implemented with a fold. ``` ₁₁ Main function: apply first helper function twice Tm»o:0:;0 First helper function. m Map over rows: » Fold over row: o Composition of : prepend new value and :0 prepend zero, ;0 starting from [0]. This inserts 0s between and around elements. T Then transpose. ``` [Answer] ## Mathematica, 39 bytes ``` r=Riffle[#,0,{1,-1,2}]&/@Thread@#&;r@*r ``` [Try it at the Wolfram sandbox!](https://sandbox.open.wolframcloud.com/) Call it like "`r=Riffle[#,0,{1,-1,2}]&/@Thread@#&;r@*r@{{1,2},{3,4}}`". Like many other answers, this works by transposing and riffling zeros in each row then doing the same thing again. Inspired by Jonathan Allan's [Jelly answer](https://codegolf.stackexchange.com/a/128270/66104) specifically, but only because I happened to see that answer first. [Answer] # Dyalog APL, 24 bytes *4 bytes saved thanks to @ZacharyT* *5 bytes saved thanks to @KritixiLithos* ``` {{⍵↑⍨-1+⍴⍵}⊃⍪/,/2 2∘↑¨⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24Tq6ke9Wx@1TXzUu0LXUMFQ@1HvFqBA7aOu5ke9q/R19I0UjB51zAAqOLQCJA7UpGDIpW6rzgWkFYwUjKFsoGJkLkgXyKDNJlABYwUTiIAlAA) [Answer] # Octave, 41 bytes ``` @(M)resize(kron(M,[0 0;0 1]),2*size(M)+1) ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQcNXsyi1OLMqVSO7KD9Pw1cn2kDBwNpAwTBWU8dICyzhq6ltqPk/Ma9YI1pPT4/LUMGIy1TBLFbzPwA "Octave – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~104 101 97 93~~ 86 bytes * @Zachary T saved 3 bytes: unused variable `w` removed and one unwanted space * @Zachary T saved yet another 4 bytes: `[a,b]` as just `a,b` while appending to a list * @nore saved 4 bytes: use of slicing * @Zachary T and @ovs helped saving 7 bytes: squeezing the statements in for loop ``` def f(a): m=[(2*len(a[0])+1)*[0]] for i in a:r=m[0][:];r[1::2]=i;m+=r,m[0] return m ``` [Try it online!](https://tio.run/##FY27DsMgDADn@is8QsJQ6CMSEV9ieUAqUZEKiSw69Ospme50yx2/9t7rrfdX2nBTUXvAEki56ZOqinRlPVs9DTLgtgtmzBWjl1BGI8@rkPXecchrmYOYMwNKal@pWHoMBBeyxpkHm2GLuZsnA8MhuTZ1HnX/Aw "Python 3 – Try It Online") [Answer] # Python 3, 118 bytes ``` def a(b): z='00'*len(b[0])+'0' r=z+'\n' for c in b: e='0' for d in c:e+=str(d)+'0' r+=e+'\n'+z+'\n' return r ``` First time golfing! Not the best, but I'm quite proud if I can say so myself! * -17 bytes from Wheat comments * -4 bytes from inlining the second for loop [Answer] # [Python 2](https://docs.python.org/2/), 64 bytes ``` lambda l:map(g,*map(g,*l)) g=lambda*l:sum([[x,0]for x in l],[0]) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHHKjexQCNdRwtK5WhqcqXbQiS1cqyKS3M1oqMrdAxi0/KLFCoUMvMUcmJ1og1iNf/n2EZHG@oY6RgD@SY6pjpmsbFcBUWZeSUKaRo5mv8B "Python 2 – Try It Online") The function `g` intersperses the input between zeroes. The main function transposes the input while applying `g`, then does so again. Maybe there's a way to avoid the repetition in the main function. [Answer] ## R, 65 bytes Thanks to Jarko Dubbeldam and Giuseppe for very valuable comments! Code ``` f=function(x){a=dim(x);y=array(0,2*a+1);y[2*1:a[1],2*1:a[2]]=x;y} ``` Input for the function must be a matrix or two dimensional array. Test ``` f(matrix(1)) f(matrix(c(1,5,4,2),2)) f(matrix(c(1,4,7),1)) f(matrix(c(6,4,2))) ``` Output ``` > f(matrix(1)) [,1] [,2] [,3] [1,] 0 0 0 [2,] 0 1 0 [3,] 0 0 0 > f(matrix(c(1,5,4,2),2)) [,1] [,2] [,3] [,4] [,5] [1,] 0 0 0 0 0 [2,] 0 1 0 4 0 [3,] 0 0 0 0 0 [4,] 0 5 0 2 0 [5,] 0 0 0 0 0 > f(matrix(c(1,4,7),1)) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [1,] 0 0 0 0 0 0 0 [2,] 0 1 0 4 0 7 0 [3,] 0 0 0 0 0 0 0 > f(matrix(c(6,4,2))) [,1] [,2] [,3] [1,] 0 0 0 [2,] 0 6 0 [3,] 0 0 0 [4,] 0 4 0 [5,] 0 0 0 [6,] 0 2 0 [7,] 0 0 0 ``` [Answer] # Mathematica, 55 bytes ``` (a=ArrayFlatten)@{o={0,0},{0,a@Map[{{#,0},o}&,#,{2}]}}& ``` [Answer] # [PHP](https://php.net/), 98 bytes Input as 2D array, Output as string ``` <?foreach($_GET as$v)echo$r=str_pad(0,(count($v)*2+1)*2-1," 0")," 0 ".join(" 0 ",$v)." 0 ";echo$r; ``` [Try it online!](https://tio.run/##JYyxCsIwGIT3PEU4MqQaS1J0isVJfAG3EEqIldShCW319eOPLsfH3ceVVOr5UlJhYrhd771zMFA4wiuHE1EH72195mUMMcmfxMMqPs0YUxZLv27LUMJDaiVjfs@bpGnX7Q3FwShwjUaBaY72ladZUsGhyGmJGOz/xdb6BQ "PHP – Try It Online") # [PHP](https://php.net/), 116 bytes Input and Output as 2D array ``` <?foreach($_GET as$v){$r[]=array_fill(0,count($v)*2+1,0);$r[]=str_split("0".join(0,$v)."0");}$r[]=$r[0];print_r($r); ``` [Try it online!](https://tio.run/##HcrBCgIhGATge08RPx60ZHGXOtnSKXqBbiIiS8u6iMqvBRE9u8lehhnmS0uql2ta0o6Y@@0xKgU9cDiB5grOrQ2gtaxzxKedFrqhvc3kzb4ElR4tov2Y2XlPBZ/iKxTavsNw7LlgciO5oMnJu0JBQLdGFxptqGuTyd9mWggtE7pQDFKCTNb6Bw "PHP – Try It Online") [Answer] ## Clojure, 91 bytes ``` #(for[h[(/ 2)]i(range(- h)(count %)h)](for[j(range(- h)(count(% 0))h)](get(get % i[])j 0))) ``` Iterates over ranges in half-steps. [Answer] # [Perl 6](http://perl6.org/), 33 bytes ``` {map {0,|$_,0},0 xx$_,|$_,0 xx$_} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OjexQKHaQKdGJV7HoFbHQKGiAsgC88DM2v/WCsWJlQppGho2hgomdjoKNqYKRnaamv8B "Perl 6 – Try It Online") [Answer] ## JavaScript (ES6), ~~73~~ 72 bytes ``` a=>(g=a=>(r=[b],a.map(v=>r.push(v,b)),b=0,r))(a,b=a[0].map(_=>0)).map(g) ``` ### Formatted and commented Inserting zeros horizontally and vertically are very similar operations. The idea here is to use the same function **g()** for both steps. ``` a => // a = input array (g = a => // g = function that takes an array 'a', ( // builds a new array 'r' where r = [b], // 'b' is inserted at the beginning a.map(v => r.push(v, b)), // and every two positions, b = 0, // sets b = 0 for the next calls r // and returns this new array ))(a, b = a[0].map(_ => 0)) // we first call 'g' on 'a' with b = row of zeros .map(g) // we then call 'g' on each row of the new array with b = 0 ``` ### Test cases ``` let f = a=>(g=a=>(r=[b],a.map(v=>r.push(v,b)),b=0,r))(a,b=a[0].map(_=>0)).map(g) console.log(JSON.stringify(f([ [1] ]))) console.log(JSON.stringify(f([ [1, 4], [5, 2] ]))) console.log(JSON.stringify(f([ [1, 4, 7] ]))) console.log(JSON.stringify(f([ [6], [4], [2] ]))) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 49 bytes ``` A⪪θ;αA””βF⁺¹×²L§α⁰A⁺β⁰βA⁺β¶βFα«βA0δFιA⁺δ⁺κ⁰δ⁺䶻β ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9noWPVq06t8P63EYQs2EuEJ3b9H7PskeNuw7tPDz9EJC95tDycxsfNW4AKWjcdW4TkAlSAuEc2gZWfm7jodVgQYNzW0DcnVD5LSBiF0gHmLXl0LZDu89t@v/f0MTc2szECAA "Charcoal – Try It Online") The input is a single string separating the rows with a semicolon. [Answer] # C++17 + Modules, 192 bytes Input as rows of strings from *cin*, Output to *cout* ``` import std.core;int main(){using namespace std;int i;auto&x=cout;string s;while(getline(cin,s)){for(int j=i=s.length()*2+1;j--;)x<<0;x<<'\n';for(auto c:s)x<<'0'<<c;x<<"0\n";}for(;i--;)x<<'0';} ``` [Answer] ## [C#](http://csharppad.com/gist/dabea5dee31d5aeab869e01f65b95f7a), 146 bytes --- ### Data * **Input** `Int32[,]` `m` The matrix to be exploded * **Output** `Int32[,]` The exploded matrix --- [Answer] # Java 8, ~~183~~ ~~166~~ ~~162~~ ~~129~~ 119 bytes ``` m->{int a=m.length,b=m[0].length,i=a*b,r[][]=new int[a-~a][b-~b];for(;i-->0;)r[i/b*2+1][i%b*2+1]=m[i/b][i%b];return r;} ``` Input and output as a `int[][]`. -33 bytes by creating a port of [*@auhmaan*'s C# answer](https://codegolf.stackexchange.com/a/128616/52210). -10 bytes thanks to *@ceilingcat*. **Explanation:** [Try it here.](https://tio.run/##tVDLboMwELznK/ZSCVLjJlEfB4tI/YDmkt6QD2twUlMwyJhUEXJ@nRoo6qWReolkSzuz3tkZ53jCqKqlzrPPXpV1ZSzknqOtVQV9NQbPDVukBTYNvKHS3QJAaSvNAVMJuwGORMITDmkwVxgy33H@@tNYtCqFHWiIoS@jbeefAcYlLaQ@2g8i4jJZ8RmpGJeCmEEn1vJrVMfogjwR0UVwdqhMwFQUbVcsNIl6EMvN/Zon6m4qvJbnRsyZkbY1GgxzPZvM1K0ovJkfT6dKZVD6XMHeGqWPo/Up1P7cWFnSqrW09i1b6GD6DppJWb9X00CgaRrMLr3jrls7F4Zj/D81rnf@p04eHemeyObWW8jLTTc8@xRDkt8cbuH6bw) ``` m->{ // Method with integer-matrix as both parameter & return int a=m.length, // Set `a` to the input-height b=m[0].length, // Set `b` to the input-width i=a*b, // Index integer, starting at `a*b` r[][]=new int[a-~a][b-~b]; // Result integer-matrix with dimensions a*a+1 by b*b+1 for(;i-->0;) // Loop `i` in the range (a*b, 0] (so over each cell): r[i/b*2+1][i%b*2+1]= // Fill the current cell of the result-matrix: m[i/b][i%b]; // With the correct input-integers return r;} // Return result integer-matrix ``` [Answer] # Dyalog APL, 24 bytes ``` {{⍵↑⍨¯1-⍴⍵}⊃⍪/,/2 2∘↑¨⍵} ``` Any improvements are welcome and wanted! [Answer] # [Python 2](https://docs.python.org/2/), 92 bytes ``` n=input() a=[[0]*(2*len(n[0])+1)for i in[0]+2*n] for l,v in zip(a[1::2],n):l[1::2]=v print a ``` [Try it online!](https://tio.run/##JYm9CoAgEIB3n8JRzSGtSfBJjhscig7kkrCgXt6Mtu@n3HXb2bfGkbicVWmRIsCIRnmTF1bcWQ9Or/shSdKngzeM4gvZXj3Jh4pK4ELwaFmH/GO8RDmIq0ytATjbJ0x2RnwB "Python 2 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/) + [Numpy](http://www.numpy.org/), 87 bytes ``` from numpy import* def f(a):b=zeros((2*len(a)+1,2*len(a[0])+1));b[1::2,1::2]=a;return b ``` [Try it online!](https://tio.run/##LYzLCsMgFETX9StcanoXTfoIGPwSuQulSgP1wa1ZpD9vDXQznDkMU/b6yunaWqAcedpi2fkaS6Y6sKcPPAgrldNfT/kjxDS8fermPMIfzQV7k3JxZlRqgiNQ24V83Shx16w27GT6Hu4InWa4wQMZskJrquL4l@0H "Python 3 – Try It Online") [Answer] ## JavaScript (ES6), ~~80~~ 78 bytes ``` a=>[...a,...a,a[0]].map((b,i)=>[...b,...b,0].map((_,j)=>i&j&1&&a[i>>1][j>>1])) ``` [Answer] # Pyth, 13 bytes ``` uCm+0s,R0dG2Q ``` [Demonstration](https://pyth.herokuapp.com/?code=uCm%2B0s%2CR0dG2Q&input=%5B%5B1%2C+2%5D%2C+%5B3%2C+4%5D%5D&debug=0) Another 13: ``` uC.iL+0m0dG2Q ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 22 bytes Prompts for matrix, returns enclosed matrix. ``` {⍺⍀⍵\a}/⍴∘0 1¨1+2×⍴a←⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdtaIgJz8l9X/1o95dj3obHvVujUms1X/Uu@VRxwwDBcNDKwy1jQ5PB/ITH7VNeNQ3FaTnv2ZyfkGlQnFiTglXdW1qXmJSTmqwo08IVyxQTVJ@hUJ@noJuWl6xbX4eF5cCGECt4XrUu8oQXahtooahgommhqmCkSaG8k6QDgUTBXNMg8yAwkYA "APL (Dyalog Unicode) – Try It Online") `a←⎕` prompt for matrix and assign to *a* `⍴` the dimensions of *a* (rows, columns) `2×` multiply by two `1+` add one `⍴∘0 1¨` use each to **r**eshape (cyclically) the numbers zero and one `{`…`}/` reduce by inserting the following anonymous function between the two numbers:  `⍵\a` expand\* the columns of *a* according to the right argument  `⍺⍀a` expand\* the rows of that according to the left argument \* 0 inserts a column/row of zeros, 1 inserts an original data column/row [Answer] # [J](http://jsoftware.com/), 24 bytes ``` 0,.0,[:,./^:2(0,.~,&0)"0 ``` [Try it online!](https://tio.run/##y/r/P03B1krBQEfPQCfaSkdPP87KSAPIq9NRM9BUMuDiSk3OyFdIUzBUMFZQAZImCub//wMA "J – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes ``` "vy0ý0.ø})"©.V€Sø®.Vø» ``` [Try it online!](https://tio.run/##MzBNTDJM/f9fqazS4PBeA73DO2o1lQ6t1At71LQm@PCOQ@v0woDk7v//o6MNY3WiTWNjAQ "05AB1E – Try It Online") --- Actually uses the same piece of code 2x, so I can store it as a string and use Eval for -10 bytes. ]
[Question] [ Write the shortest program which will take a string of numbers (of up to *at least* 20 length) as input, and display the output using the standard digital clock style numbers. For instance for input 81, a solution with ascii output would give: ``` _ |_| | |_| | ``` Graphical output is also acceptable, if it helps. [Answer] ## [Funciton](http://esolangs.org/wiki/Funciton) Not really a language suitable for golfing... but regardless, I tried to keep the code size as small as I could — quite a different challenge than in “usual” languages. This is **1555 characters** or **3110 bytes** (if encoded as UTF-16; UTF-8 is larger). Here’s a screenshot of the program running. It really works: ![Here’s a screenshot of the program running. It really works :)](https://i.stack.imgur.com/rhnV7.png) Since this looks ugly in StackExchange due to the extra line spacing, consider running the following code in your browser’s JavaScript console to fix that: `$('pre').css('line-height',1)` ``` ╓─╖ ╔╗┌─╖ ┌─╖ ║ʜ║ ║╟┤↔╟┐ ┌┤‼╟┐ ╙┬╜ ╚╝╘═╝│ │╘╤╝│ ╔═╗ ┌┴────┐ │┌┴╖ ┌┴╖ ║0║ ┌┴─┐ ┌┴─┐└┤ʜ╟─┤·╟┐ ╚╤╝┌┴╖┌┴╖┌┴╖┌┴╖╘╤╝ ╘╤╝│ ┌┘┌┤·╟┤ɦ╟┤·╟┤?╟ │ ┌┴╖│ │ │╘╤╝╘╤╝╘╤╝╘╤╝ └──┤‼╟┘ │┌┴╖│ ┌┴╖┌┘╔═╧╗ ╘═╝ └┤?╟┘┌┤?╟┘┌╢10║ ┌─────────┐ ╘╤╝ │╘╤╝┌┘╚══╝ ┌─┬┘╔══╗┌──╖┌┴╖ ╓─╖ ┘ └───┘╔════╗│┌┴┐║21╟┤>>╟┤·╟┐║ɦ║ ╔════════╗║1005╟┘└┬┘╚══╝╘═╤╝╘╤╝│╙┬╜ ┌─┐ ║14073768║╚════╝ ┌┴╖ ┌─╖ ┌┴╖┌┴╖└─┴─────────┘┌┴╖ ║7584800 ╟───────┤?╟─┤‼╟─┤ʜ╟┤·╟─────────────┤·╟┐╔═══════╗╔══╗ ╚════════╝ ╘╤╝ ╘╤╝ ╘╤╝╘╤╝ ╔══╗┌─╖┌┐╘╤╝│║2097151║║21╟┐ ╔═══════════════╗│ ┘ │ │ ║48╟┤−╟┤├─┤┌┘╚══╤════╝╚══╝│ ║140737555464224╟┘ ┌────┘┌┬┘ ╚══╝╘╤╝└┘┌┘│╓─╖ │┌┐┌─╖┌─╖┌┴─╖ ╚═══════════════╝ │ ┌───┘└─────────┐┌┴─╖ │┌┘║↔║ ├┤├┤‼╟┤↔╟┤>>║ ┌────────────┐┌────┐┌┴╖│┌────────────┐├┤<<║ ││ ╙┬╜┌┘└┘╘╤╝╘═╝╘╤═╝ │ ╔══╗╔═══╗├┘╓─╖ └┤·╟┘│ ╔══╗╔═══╗├┘╘╤═╝ │└─┐└─┤╔═╗┌┴╖ ┌──┘ │ ║95║║892║│┌╢‡╟┐ ╘╤╝ │ ║95║║877║│ ┌┘╔══╧═╗│ │║0╟┤?╟┬┘ │ ╚═╤╝╚═╤═╝││╙─╜│ │ │ ╚═╤╝╚═╤═╝│╔╧╗║2097║│ │╚═╝╘╤╝│ │╔══╗┌┴╖┌┐│ ││┌─╖│ ┌┴╖ │╔══╗┌┴╖┌┐│ │║1║║151 ║│ └──────┘ │║32╟┤?╟┤├┤ │└┤‼╟┘┌┤‡║ │║32╟┤?╟┤├┤ │╚═╝╚════╝│ │╚══╝╘╤╝└┘└──┴┐╘╤╝ │╘╤╝ │╚╤═╝╘╤╝└┘└──┴┐ ┌─┘ │ ┌┴╖ ┌┴╖┌─╖│ │ ┌┴╖│ ┌┴╖ ┌┴╖ ┌─╖┌┴╖ │ │‼╟─────┤·╟┤‼╟┘ │┌┤·╟┘ │‼╟─────┤·╟─┤‼╟┤‡║ └┐┌┐ ╘╤╝ ╘╤╝╘╤╝ ││╘╤╝┌┐ ╘╤╝ ╘╤╝ ╘╤╝╘╤╝ ├┤├┐┌┴╖╔══╗ └──┐┌┐ │└┐├─┤├┐┌┴╖╔══╗ ├──┐└ │ │└┘└┤?╟╢32║╔═══╗├┤│┌┴╖││ └┘└┤?╟╢32║╔═╧═╗│┌┐┌┴╖╔══╗ ╔╧══╗╘╤╝╚══╝║881╟┘│├┤?╟┘│ ╘╤╝╚══╝║325║└┤├┤?╟╢32║ ║927║╔╧══╗ ╚═══╝ └┘╘╤╝╔╧═══╗╔╧══╗ ╚═══╝ └┘╘╤╝╚══╝ ╚═══╝║124╟───────────┘ ║1019║║124╟───────────┘ ╚═══╝ ╚════╝╚═══╝ ``` It could probably be smaller if I hadn’t made a mistake due to which the output was back to front; I fixed that by adding an extra function to reverse the input. Otherwise I would probably have to rewrite all of it. I also made another mistake (swapping the operands in two calls to `‼`) which made it necessary to declare the extra `‡` function, but this one is so small it fits *inside* the main function and thus doesn’t add any characters! [Answer] ### wxpython, many characters ``` import wx, wx.gizmos as g class T(wx.Frame): def __init__(_): wx.Frame.__init__(_, None, size = (800, 60)) l = g.LEDNumberCtrl(_, -1) l.Value = raw_input() class M(wx.App): def OnInit(_): T().Show() return 1 M().MainLoop() ``` Test ``` echo -n 81 | python codegolf-997-wx.py ``` ![enter image description here](https://i.stack.imgur.com/0LUTJ.png) ps: not a serious entry, but looks like graphical output is also acceptable, so I just gave it a try :-) [Answer] ## J, 90, 78 68 chars [ **update:** using unicode (1 byte) encoding: ``` ,./(10 3 3$((90$3)#:256#.24x-~3&u:'%ė¨ÔW/~º»sy¡ăì<t÷²'){' _|'){~"./.Y NB. utf characters are: 37 279 168 212 87 47 126 186 187 115 121 161 259 236 60 116 247 178 ``` works as before: ] ``` ,./(10 3 3$((90$3)#:1219424106940570763878862820444729939648410x){' _|'){~"./. '58321' _ _ _ _ |_ |_| _| _| | _||_| _||_ | ``` The key is in the encoding of digits as base-3 integers. Zero, for example is: ``` : _ | | |_| ``` or `' _ | ||_|'`, which becomes 0102022123 = 2750. [Answer] ## Golfscript - 66 chars ``` "placeholder text for userscript which counts chars "; ``` `xxd`: (use `xxd -r` to revert) ``` 0000000: 332c 7b3a 533b 2e7b 3438 2d22 5e70 285d 3,{:S;.{48-"^p(] 0000010: 7025 d3c4 4ab1 7d4a b8dc 4469 ce41 2222 p%..J.}J..Di.A"" 0000020: f303 227b 6261 7365 7d2f 3330 2f53 3d33 .."{base}/30/S=3 0000030: 2f3d 7b22 5f20 7c22 3d7d 257d 256e 407d /={"_ |"=}%}%n@} 0000040: 2f3b /; ``` This follows most of the other answers in that there are no spaces between numbers and trailing spaces are kept in. A space between numbers can easily be added with `1+` before `{"_ |"=}%`. Packed into a base 3 number, and then as base 243 into a string. [Answer] ## APL (Dyalog) (45) ``` {3 3⍴' _|'[1+⍵⊤⍨9⍴3]}¨⎕UCS'ા8धगɯે૙ࣃଏ૽'[1+⍎¨⍞] ``` The string, `ા8धगɯે૙ࣃଏ૽`, are the unicode characters `2750 56 2343 2327 623 2759 2777 2243 2831 2813` (however, you should be able to just copy and paste it). They encode the numbers. The program reads a line from the keyboard. Explanation: * `1+⍎¨⍞`: read a line from the keyboard, parse each character as a digit, then add 1 to each number (APL arrays are 1-based by default). * `⎕UCS'ા8धगɯે૙ࣃଏ૽'[`...`]`: Select the characters belonging to the digits of the numbers you entered, and look up the Unicode values. * `{`...`}¨`: for each of these values, do: * `1+⍵⊤⍨9⍴3`: get the first 9 base-3 digits from the value as expressed in base-3, and add 1 (because the arrays ar 1-based). * `' _|'[`...`]`: select a space, horizontal line, or vertical line depending on these digits * `3 3⍴`: format as a 3-by-3 box. [Answer] # Mathematica 205 209 198 179 ``` i = IntegerDigits; t = Thread; r = Rule; z@n_ := Row@i@n /. t[r[Range[0, 9], Grid[Partition[ReplacePart[Characters@" _ |_||_|", t[r[#, ""]]], 3], Spacings -> 0] & /@ (i /@ {5, 24578, 49, 47, 278, 67, 6, 4578, , 78})]] ``` **Usage** ``` z@1234567890 ``` ![digits](https://i.stack.imgur.com/3sltt.png) [Answer] # JavaScript (145) ~~148~~ 145 Since JavaScript doesn’t really have standard input/output, this is written as a function that takes a string and returns the output as a string. ``` function r(n){for(i=o="",b=" |_\n|",L=n.length;i<3*L;)o+=b[(c="ǪĠòƲĸƚǚĢǺƺ".charCodeAt(n[i%L])>>(i++/L|0)*3)&1]+b[c&2]+b[c&4]+b[i%L?0:3];return o} ``` Spaced out: ``` function r(n) { for (i = o = "", b = " |_\n|", L = n.length; i < 3*L; ) o += b [ (c = "ǪĠòƲĸƚǚĢǺƺ".charCodeAt(n[i%L]) >> (i++/L|0)*3) & 1 ] + b [ c&2 ] + b [ c&4 ] + b [ i%L ? 0 : 3 ]; // space or newline return o } ``` Here’s how it works: * Every digit shape is encoded in a Unicode character consisting of 9 bits. * The first three bits are for the first row, etc. * In each group of three bits, the first specifies whether the first character is `|` or space, the second whether it’s `_` or space, and the third again `|` or space. * These three bits are retrieved as `c&1`, `c&2` and `c&4`, which are then used as indexes into the string `b`. * At each iteration, `i%L` is the “x-coordinate”, i.e. the digit within the input `n` * At each iteration, `i/L` is the “y-coordinate”, i.e. the row, but we need `|0` to make it an integer * Finally, the spaces between the digits and the newlines between the lines are *also* retrieved by indexing into `b`, re-using the space character *and* the otherwise unused position 3 in that string! :) [Answer] ## Ruby, 142 ``` ' _ _ _ _ _ _ _ _ | | | _| _||_||_ |_ ||_||_| |_| ||_ _| | _||_| ||_| _|'.lines{|l|puts x.chars.map{|i|l[i.to_i*3,3]}*''} ``` expects input in the variable `x`. examples: ``` x = '321' # _ _ # _| _| | # _||_ | x = '42' # _ # |_| _| # ||_ ``` [Answer] ## python3.8.10 : ~~148~~ 138 bytes Old (148): ``` a=input() N=0x375fa9176b3538d93ca41ea for i in 0,3,6:print(''.join(' |'[N&x<<i>0]+' _'[N&x<<i+1>0]+' |'[N&x<<i+2>0]for x in[1<<9*int(x)for x in a])) ``` New (138): ``` a=input() N=0x375fa9176b3538d93ca41ea for i in -1,2,5:print(''.join(' |_|'[(N&x<<i+k>0)*k]for x in[1<<9*int(x)for x in a]for k in(1,2,3))) ``` [try the code here](https://tio.run/##NYzRCoIwGIXvfYpdtc0snL9zLmaP4AtIxLKkNdhEDBb47kuD7g7nfN8ZP/PTO4hRN8aN75nQpG3yAIIPWjJR3YBDfZfQ65I9dDL4CRlkHDqwrMj4aZyMmwnGx5c3jmC0XBfckXYXlDJ7e85pai@bE1anY0rJdOMD/XdI/2a7RrI9AqU0RlZAyStRy/wL) [Answer] ## Golfscript - 97 chars ``` :*{32' _':$@'14'{?~!=}:&~32}%n*{:x' |':|\'1237'&$x'017'&|x'56'&}%n*{:x|\'134579'&$x'147'&|x'2'&}% ``` [Answer] # D: 295 Characters ``` import std.stdio;void main(string[]a){string[3]o;foreach(c;a[1]){int n=cast(int)(c)-48;auto e=" ";o[0]~=n!=1&&n!=4?" _ ":" ";o[1]~=!n||n>3&&n!=7?"|":e;o[1]~=n>1&&n!=7?"_":e;o[1]~=n<5||n>6?"|":e;o[2]~=!(n&1)&&n!=4?"|":e;o[2]~=!n||n>1&&n!=4&&n!=7?"_":e;o[2]~=n!=2?"|":e;}foreach(l;o)writeln(l);} ``` More Legibly: ``` import std.stdio; void main(string[] a) { string[3] o; foreach(c; a[1]) { int n = cast(int)(c) - 48; auto e = " "; o[0] ~= n != 1 && n != 4 ? " _ " : " "; o[1] ~= !n || n > 3 && n != 7 ? "|" : e; o[1] ~= n > 1 && n != 7 ? "_" : e; o[1] ~= n < 5 || n > 6 ? "|" : e; o[2] ~= !(n&1) && n != 4 ? "|" : e; o[2] ~= !n || n > 1 && n != 4 && n != 7 ? "_" : e; o[2] ~= n != 2 ? "|" : e; } foreach(l; o) writeln(l); } ``` [Answer] ### Windows PowerShell, 127 ``` $i="$input"[0..99] '☺ ☺☺ ☺☺☺☺☺','♠☻♥♥♦♣♣☻♦♦','♦☻♣♥☻♥♦☻♦♥'|%{$c=$_ ""+($i|%{('···0·_·0··|0·_|0|_|0|_·0|·|'-split0)[$c[$_-48]]})} ``` Since the strings contain some unpleasant-to-write characters, a hexdump for your convenience: ``` 000: 24 69 3D 22 24 69 6E 70 │ 75 74 22 5B 30 2E 2E 39 $i="$input"[0..9 010: 39 5D 0A 27 01 00 01 01 │ 00 01 01 01 01 01 27 2C 9]◙'☺ ☺☺ ☺☺☺☺☺', 020: 27 06 02 03 03 04 05 05 │ 02 04 04 27 2C 27 04 02 '♠☻♥♥♦♣♣☻♦♦','♦☻ 030: 05 03 02 03 04 02 04 03 │ 27 7C 25 7B 24 63 3D 24 ♣♥☻♥♦☻♦♥'|%{$c=$ 040: 5F 0A 22 22 2B 28 24 69 │ 7C 25 7B 28 27 20 20 20 _◙""+($i|%{(' 050: 30 20 5F 20 30 20 20 7C │ 30 20 5F 7C 30 7C 5F 7C 0 _ 0 |0 _|0|_| 060: 30 7C 5F 20 30 7C 20 7C │ 27 2D 73 70 6C 69 74 30 0|_ 0| |'-split0 070: 29 5B 24 63 5B 24 5F 2D │ 34 38 5D 5D 7D 29 7D )[$c[$_-48]]})} ``` [Answer] **Java Solution: ~~585~~ 570 Chars** I don't think I'll be attempting any more golfing in Java... ``` import java.util.*; public class CG997{public static void main(String[]args){ short[][]lets=new short[][]{{0,1,3,2,0,4,2,1,4},{0,0,3,0,0,4,0,0,4},{0,1,3,0,1, 4,2,1,3},{0,1,3,0,1,4,0,1,4},{0,0,3,2,1,4,0,0,4},{0,1,3,2,1,3,0,1,4},{0,1,3,2,1 ,3,2,1,4},{0,1,3,0,0,4,0,0,4},{0,1,3,2,1,4,2,1,4},{0,1,3,2,1,4,0,0,4}}; String[]syms=new String[]{" ","_","|"," ","| "}; String s=new Scanner(System.in).nextLine(); for(int o=0;o<3;o++){for(char c:s.toCharArray()){for(int i =0;i<3;i++) System.out.print(syms[lets[Short.parseShort(c+"")][i+o*3]]); }System.out.println();}}} ``` [Answer] # Bash, 11 characters ``` toilet "$i" ``` Yes I know, I'm cheating. You need to have toilet installed. [Answer] # gForth, ~~186~~ 175 chars New version: ``` : s query parse-word bounds s" D@DD@DDDDDb`ddfFF`fff`Fd`df`f`" bounds do cr 2dup do i c@ '0 - j + c@ 3 0 do dup 3 and s" _|" drop + 1 type 4 / loop drop loop 10 +loop bye ; s ``` This actually bothers to exit (+3 chars) as well :). Here is the more readable version, it does some bit-packing to reduce the LUT size by 1/3, but the resulting code is more complex so it's not much of a savings: ``` : 7s query parse-word bounds s" D@DD@DDDDDb`ddfFF`fff`Fd`df`f`" bounds do cr 2dup do i c@ '0 - j + c@ 3 0 do dup 3 and s" _|" drop + 1 type 4 / \ shorter than an rshift loop drop loop 10 +loop bye ; 7s ``` Old version: ``` : s query parse-word bounds s" _ _ _ _ _ _ _ _ | | | _| _||_||_ |_ ||_||_||_| ||_ _| | _||_| ||_| |" bounds do cr 2dup do i c@ '0 - 3 * j + 3 type loop 30 +loop ; s ``` This leaves the stack unbalanced and doesn't bother to exit the interpreter. Here is a cleaner more readable version ``` : 7s query parse-word bounds s" _ _ _ _ _ _ _ _ | | | _| _||_||_ |_ ||_||_||_| ||_ _| | _||_| ||_| |" bounds do cr 2dup do i c@ '0 - 3 * j + 3 type loop 30 +loop 2drop bye ; 7s ``` [Answer] # Java 8, ~~280~~ 274 bytes ``` interface M{static void main(String[]a){String x="",y=x,z=x;for(int c:a[0].getBytes()){c-=48;x+=" "+(c==4|c==1?" ":"_")+" ";y+=(c==7|c>0&c<4?" ":"|")+(c==7|c<2?" ":"_")+(c>4&c<7?" ":"|");z+=(c%2<1&c!=4?"|":" ")+(c%3==1?" ":"_")+(c==2?" ":"|");}System.out.print(x+"\n"+y+"\n"+z);}} ``` -6 bytes thanks to *@ceilingcat*. **Explanation:** [Try it here.](https://tio.run/##RY9Bb8IwDIX/ShYJlCpQtSVbGa2ZtPtOHAGhKAQUJlLUZihpy2/PAp3Yxbbee58tn/iVT6uL1Kf9t/dKG1kfuJDoq2sMN0qga6X26MyVJitTK31cb3nUDSOygPHEgZ20YItDVZPAI7Hg62QbH6X5dEY2JIo6MQU2LywFAcD6UNIPjBDCC4x2CBeOAgli3otlMhYlC2awehzRP7nMBmn3kJYshPJnqGjv@Cgr07F4gQD3972P5Gg2nHqiANk/d1u5xshzXP2Y@BL@McRSvNGYuqG1IXLz3qfZjL2@5fP35Bc) ``` interface M{ // Class static void main(String[]a){ // Mandatory main-method String x="", // String for row 1, starting empty y=x, // String for row 2, starting empty z=x; // String for row 3, starting empty for(int c:a[0].getBytes()){ // Loop over the bytes of the input c-=48; // Convert the byte to integer x+= // Append to row 1: c==4|c==1? // If the digit is a 1 or 4: " " // Append three spaces : // Else: " _ "; // Append a space + underscore + space instead y+= // Append to row 2: (c==7|c>0&c<4? // If the digit is 1, 2, 3, or 7: " " // Append a space : // Else: "|") // Append a pipe +(c==7|c<2? // +If the digit is 0, 1, or 7: " " // Append a space : // Else: "_") // Append an underscore +(c>4&c<7? // +If the digit is 5 or 6: " " // Append a space : // Else: "|"); // Append a pipe z+= // Append to row 3: (c%2<1&c!=4? // If the digit is 0, 2, 6 or 8: "|" // Append a pipe : // Else: " ") // Append a space +(c%3==1? // +If the digit is 1, 4, or 7: " " // Append a space : // Else: "_") // Append a pipe +(c==2? // +If the digit is 2: " " // Append a space : // Else: "|"); // Append a pipe } // End of loop System.out.print(x+"\n"+y+"\n"+z); // Print the three rows } // End of main-method } // End of class ``` As function this would be [**212 bytes**](https://tio.run/##RVBdb4IwFH33V9w10ZQgRJENZ6nLsuf5ssdtMV3FDafFtNWAwm/HixB9uU3Px705ZyOOwsv2idqs/mu5FcbAu0jVuQeQKpvotZAJLJovwIfVqfoFSeWf0J/fYByGeNXDYaywqYQFKOBQG29@7sQ5J2RY8Hx44jlbZ5riVpAz45ylx8Mpy10uOQ9LHOMXgkfIjMASCCtcThGMSjkfDWQcIolUSRy3g@OghZZXaB6iKLqJ2Kmx94N4PJAPHM1ls/eq7E/aUzcr58HdV@nEHrSC3CVfirhF@5xYVbMm5/7ws8WcXdxjlq5gh3XRNi12Ipyuq8LYZOdnB@vvkbJU@ZKScTAJH5@i6fOI@DZ7wxpftRYFdZyuyqqu75oL) instead. [Answer] # [JavaScript (V8)](https://v8.dev/), ~~118~~ 115 bytes -3 bytes: realised a cheaper way to loop through `|_|` ``` n=>[613550340,2132540234,1866373582].map(d=>n.replace(/./g,c=>(i=1<<c*3,g=s=>d&(i*=2)?s:' ')`|`+g`_`+g`|`)).join` ` ``` [Try it online!](https://tio.run/##Xc7PDoIgAIDxu0/RKaARCghSiT1Ia8nwz3AGTpsn353qWNffd/kGs5rFzm56HVcVOx29rm6SciEynmeYUc5EnjGeY6qk5AUXit3J00yw0ZUnczuNxrYwJWmPra7A9tjAry66avbQHTRD1@UMdgA7TcvSHjhCiAzB@Tqpow1@CWNLxtDDDgJFAUKX5E8z@hkRslCnb41v "JavaScript (V8) – Try It Online") Takes input as a string of digits, uses three magic numbers which represent the state of each segment for each digit; every three bits is a digit. Ungolfed and explained ``` n => [ // magic numbers // 9 8 7 6 5 4 3 2 1 0 613550340, // = 0b010_010_010_010_010_000_010_010_000_010_0 2132540234, // = 0b111_111_100_011_011_111_110_110_100_101_0 1866373582 // = 0b110_111_100_111_110_100_110_011_100_111_0 ].map(d => n.replace(/./g, c => ( i = 1 << c * 3, // initialise i to first bit of digit g = s => d & (i *= 2) ? s : ' ' // function to check bits )`|` + g`_` + g`|` // do function on each of '|_|' )).join` ``` [Answer] ## C# 369 Characters ``` static void Main(string[] a){var b = new[] {123,72,61,109,78,103,119,73,127,111};var g = new[]{" _ ","|","_","| ","|","_","| "};a[0].ToCharArray().SelectMany((x,w)=>g.Select((y,i)=>new{s=((b[x-48]>>i&1)==1)?y:new String(' ',y.Length),j=i,v=w})).GroupBy(z=>(z.j+2)/3).ToList().ForEach(q=>Console.WriteLine(String.Join("", q.OrderBy(l=>l.v).Select(k=>k.s).ToArray())));} ``` I could easily cut *a few* characters out. The point was more to abuse LINQ :) More whitespace version: ``` static void Main(string[] a) { var b = new[] {123, 72, 61, 109, 78, 103, 119, 73, 127, 111}; var g = new[] { " _ ", "|", "_", "| ", "|", "_", "| " }; a[0].ToCharArray().SelectMany( (x,w)=>g.Select( (y,i)=>new{s=((b[x-48]>>i&1)==1)?y:new String(' ',y.Length),j=i,v=w})) .GroupBy(z=>(z.j+2)/3).ToList().ForEach( q=>Console.WriteLine( String.Join("", q.OrderBy(l=>l.v).Select(k=>k.s).ToArray()))); } ``` [Answer] # Python, ~~218~~ ~~180~~ 176 `b=map(int,raw_input());a=map(int,bin(914290166014670372457936330)[2:]);c=' |_';p=lambda k:''.join(c[a[9*n+k]]+c[2*a[9*n+1+k]]+c[a[9*n+2+k]]for n in b)+'\n';print p(6)+p(0)+p(3)` With line breaks: ``` b=map(int,raw_input()) a=map(int,bin(914290166014670372457936330)[2:]) p=lambda k:''.join(' |'[a[9*n+k]]+' _'[a[9*n+1+k]]+' |'[a[9*n+2+k]]for n in b)+'\n' print p(6)+p(0)+p(3) ``` [Answer] ## Java, 2,095 ``` public class DigitalNumber { public static void main(String args[]){ char[][] panel = new char[3][120]; //A 20 digit panel! int digXIndex = 0;int digYIndex = 0; for (int i=0;i<args[0].length(); i++){ int dig=Integer.parseInt(""+args[0].charAt(i)); panel[digXIndex][digYIndex]=32; digYIndex++; if (dig!=1 && dig!=4) panel[digXIndex][digYIndex]='_'; else panel[digXIndex][digYIndex]=32; digYIndex++; panel[digXIndex][digYIndex]=32; digYIndex=3*i; digXIndex++; if (dig!=1 && dig!=2 && dig!=3 && dig!=7) panel[digXIndex][digYIndex]='|'; else panel[digXIndex][digYIndex]=32; digYIndex++; if (dig!=1 && dig!=0 && dig!=7) panel[digXIndex][digYIndex]='_'; else panel[digXIndex][digYIndex]=32; digYIndex++; if (dig!=6 && dig!=5) panel[digXIndex][digYIndex]='|'; else panel[digXIndex][digYIndex]=32; digYIndex=3*i; digXIndex++; if (dig!=6 && dig!=8 && dig!=2 && dig!=0) panel[digXIndex][digYIndex]=32; else panel[digXIndex][digYIndex]='|'; digYIndex++; if (dig!=7 && dig!=4 && dig!=1) panel[digXIndex][digYIndex]='_'; else panel[digXIndex][digYIndex]=32; digYIndex++; if (dig!=2) panel[digXIndex][digYIndex]='|'; else panel[digXIndex][digYIndex]=32; digXIndex=0; digYIndex+=(i*3)+1; } for (int i=0; i<3; i++){ for (int j=0; j<120; j++) if (panel[i][j]!=0) System.out.print((char)(panel[i][j])); else System.out.print(""); System.out.println(); } } } ``` SAMPLE I/O ``` java DigitalNumber 98765432109876543210 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ |_||_| ||_ |_ |_| _| _| || ||_||_| ||_ |_ |_| _| _| || | _||_| ||_| _| | _||_ ||_| _||_| ||_| _| | _||_ ||_| ``` [Answer] # PHP, ~~140~~ ~~136~~ ~~133~~ ~~131~~ ~~129~~ 128 bytes I could save ~~5~~ 7 more with extended ascii: one each for `"| _"` and the linebreak, three for `~"z/]{4lno~|"` (bitwise negation would turn everything to extended ascii characters = no special characters, and PHP doesn´t need quotes there), two for `-1` (it´s only there to keep the map in standard ascii). But for readability and compatibility, I stay with standard ascii. ``` for(;""<$c=$argv[1][$i++];)for($n=753754680;$n>>=3;)$r[$p++%3].="| _"[ord(~"z/]{4lno~|"[$c])-1>>$n%8&1?:$n&2];echo join(" ",$r); ``` **the bitmap** * Take LEDS `_`,`|_|`, `|_|` as bits `-6-`,`024`,`135` (bit number &2 is 0 for vertical LEDs) * Create bitmaps for numbers 0..9: `[123,48,94,124,53,109,111,112,127,125]` * Decrease by 1 to make them all printable ascii codes -> `"z/]{4lno~|"` * negate -> `~"z/]{4lno~|"` (allows ternary shorthand in character selection) **the template** * use `7` for the spaces -> `767`,`024`,`135` * regroup by columns instead of rows -> `701`,`623`,`745` (renders `$p=0` obsolete) * reverse -> `547326107` (read the map from right to left; allows arithmetic looping) * append zero -> `5473261070` (allows to combine shift with test in loop head) * read octal, convert to decimal -> `753754680` (two bytes shorter: one digit and the prefix) **breakdown** ``` for(;""<$c=$argv[1][$i++];) // loop through input characters for($n=753754680;$n>>=3;) // loop through template $r[$p++%3].="| _"[ // append character to row $p%3: ord(~"z/]{4lno~|"[$c])-1// decode bitmap >>$n%8&1 // test bit $n%8 (always 1 for bit 7) ? // if set: 1 (space) :$n&2 // else: 2 (underscore) for bits 2,3,6; 0 (pipe) else ]; echo join("\n",$r); // print result ``` [Answer] # Powershell, 114 bytes ``` param($a)6,3,0|%{$l=$_ -join($a|% t*y|%{(' 0 _ 0 _|0|_ 0| |0 |0|_|'-split0)[(+('f-SR5Z^mvr'["$_"])-shr$l)%8]})} ``` Test script: ``` $f = { param($a)6,3,0|%{$l=$_ -join($a|% t*y|%{(' 0 _ 0 _|0|_ 0| |0 |0|_|'-split0)[(+('f-SR5Z^mvr'["$_"])-shr$l)%8]})} } &$f "1234567890" &$f "81" ``` Output: ``` _ _ _ _ _ _ _ _ | _| _||_||_ |_ ||_||_|| | ||_ _| | _||_| ||_| _||_| _ |_| | |_| | ``` Main idea: Each standard digital clock style number contains 3 lines. Moreover, the first line contains only 2 options. A total of 6 options. Therefore, 7 bits are enough to encode each digit. ``` line str=@(' ', ' _ ', ' _|', '|_ ', '| |', ' |', '|_|') # line str binary dec ASCII - -------- --------- --- ----- 0 -> 1 4 6 -> 1 100 110 -> 102 -> 'f' 1 -> 0 5 5 -> 0 101 101 -> 45 -> '-' ... 8 -> 1 6 6 -> 1 110 110 -> 118 -> 'v' 9 -> 1 6 2 -> 1 110 010 -> 114 -> 'r' ``` So, the string `f-SR5Z^mvr` encodes all segments for all standard digital clock style numbers. Note: The order of the `line str` was specially selected so that all codes were in the interval `32..126`. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `jṠ`, 40 bytes ``` »*ż↵↲ṡŀ≬₍ṡfl₆ǎ8≠∇ƈH»`_ |`τ3/₀/ƛ£⁰ƛ¥nIi;ṅ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=j%E1%B9%A0&code=%C2%BB*%C5%BC%E2%86%B5%E2%86%B2%E1%B9%A1%C5%80%E2%89%AC%E2%82%8D%E1%B9%A1fl%E2%82%86%C7%8E8%E2%89%A0%E2%88%87%C6%88H%C2%BB%60_%20%7C%60%CF%843%2F%E2%82%80%2F%C6%9B%C2%A3%E2%81%B0%C6%9B%C2%A5nIi%3B%E1%B9%85&inputs=0123456789&header=&footer=) A mess. Uses base-3 compression. ``` »...» # Compressed integer containing all digits `_ |`τ # Decompress by custom base-3 3/ # Divide into 3 ₀/ # Divide each piece into 10 ƛ # Map this new list to... £ # Store to register ⁰ƛ ; # Map this new input to... ¥ # Push register nIi # Get correct value ṅ # Join # (Implicit) Join by newlines ``` [Answer] # Ocaml, 268 ``` let t=function|'1'|'4'->" "|_->" _ "let m=function|'0'->"| |"|'1'|'7'->" |"|'2'|'3'->" _|"|_->"|_|"|'5'|'6'->"|_ "let b=function|'0'|'8'->"|_|"|'1'|'4'|'7'->" |"|'2'->"|_ "|_->" _|"let f s=let g h=String.iter(fun c->print_string(h c))s;print_newline()ing t;g m;g b ``` Readable version ``` let t = function | '1' | '4' -> " " | _ -> " _ " let m = function | '0' -> "| |" | '1' | '7' -> " |" | '2' | '3' -> " _|" | _ -> "|_|" | '5' | '6' -> "|_ " let b = function | '0' | '8' -> "|_|" | '1' | '4' | '7' -> " |" | '2' -> "|_ " | _ -> " _|" let f s = let g h = String.iter (fun c -> print_string (h c)) s; print_newline () in g t; g m; g b ``` [Answer] ## Ghostscript ~~(270)~~ ~~(248)~~ (214) *Edit:* More substitutions. Removed space between digits. *Edit:* Even more substitutions. Main loop now looks like what it does! ``` /F{forall}def[48<~HUp;::1ncBInp~>{1 index 1 add}F pop/*{dup 2 idiv exch 2 mod 1 eq}/P{print}/#{( )P}/?{ifelse P}/O{{( )}?}/|{*{(|)}O}/_{*{(_)}O}>>begin[[[[ARGUMENTS{{load # _ #}F()=]2{{| _ |}F()=]}repeat]pop[[[[}F ``` Uses ghostscript's argument-processing feature: invoke with `gs -dNODISPLAY -- digit.ps 012 345 6789`. [Answer] ### Delphi || 453 (568 With format) Not even close enough to win but it was fun to do ^.^ ``` const asc: array[0..9] of array[0..2] of string = ((' _ ','| |','|_|'),(' ',' |',' |'),(' _ ',' _|','|_ '),(' _ ',' _|',' _|'),(' ','|_|',' |'),(' _ ','|_ ',' _|'),(' _ ','|_ ','|_|'),(' _ ',' |',' |'),(' _ ','|_|','|_|'),(' _ ','|_|',' _|'));var s,l:string;x,i:integer;begin Readln(s);s:=StringReplace(s,' ','',[rfReplaceAll]);for I := 0 to 2 do begin l:='';for x := 1 to length(s) do l := l + asc[StrToInt(s[x])][i];writeln(l);end;readln;end. ``` ### With format ``` const asc: array[0..9] of array[0..2] of string = ( (' _ ','| |','|_|'), (' ',' |',' |'), (' _ ',' _|','|_ '), (' _ ',' _|',' _|'), (' ','|_|',' |'), (' _ ','|_ ',' _|'), (' _ ','|_ ','|_|'), (' _ ',' |',' |'), (' _ ','|_|','|_|'), (' _ ','|_|',' _|')); var s,l:string; x,i:integer; begin Readln(s); s:=StringReplace(s,' ','',[rfReplaceAll]); for I := 0 to 2 do begin l:=''; for x := 1 to length(s) do l := l + asc[StrToInt(s[x])][i]; writeln(l); end; readln ``` end. [Answer] # [Perl 5](https://www.perl.org/) `-F`, 96 bytes ``` map{@m=/./g;say map{substr' _ _||_ | | ||_|',3*$m[$_],3}@F}1011011111,4522633566,6532526562 ``` [Try it online!](https://tio.run/##FYdBCsIwEEWvkkWhIGmbzHRGRYSuuvMEIqGCiGBsaOpCTK/umL7/Fu@H2/QkET@Eb@ePTd3cD3H4qPXH9zXOU6kyLpuSUylP5Uilxk3hz4W7aFy6frHGrmZ0SwCMSMyaCYGAiUHEWMCWeLvb/8YwP8ZXlOpEtbFGqv4P "Perl 5 – Try It Online") The string `_ _||_ | | ||_|` represents the possible "cross sections" of the digits (grabbed the idea from @mazzy's PowerShell solution). The numbers in the list `1011011111,4522633566,6532526562` represent indices into that string for the first, second, and third line of each of the digits 0-9. The index must be multiplied by 3 to get to the correct position. This loops over each character input (stored in the `@F` array by the `-F` option on the command line), finds the correct index into the string for that input, and then outputs the result. ### Old version: [Perl 5](https://www.perl.org/) `-n`, 102 bytes ``` for$b(' a ',dbe,fcg){say s%.%'$b=~y/'.(b,abcdf,dg,df,acf,ef,e,bcdf,Z,f)[$&]."/ /r=~y/a-z/___|/r"%geer} ``` [Try it online!](https://tio.run/##K0gtyjH9/z8tv0glSUNdIVFBXSclKVUnLTlds7o4sVKhWFVPVV0lybauUl9dTyNJJzEpOSVNJyVdB0gmJqfppAKRDlgsSidNM1pFLVZPSV9BvwikIVG3Sj8@Pr5Gv0hJNT01taj2/39DI2MTUzNzC0sDBOtffkFJZn5e8X9dX1M9A0OD/7p5AA "Perl 5 – Try It Online") Considers the characters of the display to be named like this: $$\begin{array}{|c|c|c|} \hline & a & \\ \hline d &b & e \\ \hline f & c & g \\ \hline \end{array}$$ The code iterates over strings representing each line of that table `(' a ',dbe,fcg)`. On each of those, it changes the elements turned off into spaces. This information is in the list `(b,abcdf,dg,df,acf,ef,e,bcdf,z,f)`. It uses the current element of the input (stored in `$_` by the commandline switch and extracted by the pattern match into `$&`) to index into that list. Finally, the letters a, b, and c are changed to underscores (`_`) and all other letters into pipes (`|`). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 36 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` •ʒïgȨ&Û≠∍›vâsŸ”_‡y•…| _ÅвJ3ôTäÅвø» ``` Outputs with additional single space between the output-digits. If this is not allowed, it'll be 1 byte longer by adding a `J` before the `»`. [Try it online.](https://tio.run/##AVYAqf9vc2FiaWX//@KAosqSw69nw4jCqCbDm@KJoOKIjeKAunbDonPFuOKAnV/igKF54oCi4oCmfCBfw4XQskozw7RUw6RJU8Oow7jCu///MTM1NzkyNDY4MA) **Explanation:** ``` •ʒïgȨ&Û≠∍›vâsŸ”_‡y• # Push compressed integer 5210925748351095970666976465591163407510385 …| _ # Push string "| _" Åв # Convert the integer to this custom base (basically convert it to # base-length - 3 in this case - and index each into the string) J # Join this list of characters to a single string: # " _ | ||_| | | _ _||_ _ _| _| |_| | _ |_ _| _ |_ |_| _ | | _ |_||_| _ |_| _|" 3ô # Split it into triplets Tä # Split that into 10 equal-sized parts Åв # Convert the (implicit) input-integer to this custom base ø # Zip/transpose; swapping rows/columns » # Join each inner list by spaces, and then each string by newlines # (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 `•ʒïgȨ&Û≠∍›vâsŸ”_‡y•` is `5210925748351095970666976465591163407510385`. [See this 05AB1E tip](https://codegolf.stackexchange.com/a/120966/52210) to understand how the ASCII-art string `" _ | ||_| | | _ _||_ _ _| _| |_| | _ |_ _| _ |_ |_| _ | | _ |_||_| _ |_| _|"` is compressed. [Answer] # [Factor](https://factorcode.org/) + `lcd`, 3 bytes ``` lcd ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQk5yikJmvYM3FpWRoZKH0H8j/X16UWZL6HwA "Factor – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 33 bytes ``` »@Ǐ+Ẇ₃e⋏UWṡ:≠7ẏŀz→=»`| _`τ₀/3/τ∩⁋ ``` Ports the 05AB1E answer. [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCu0DHjyvhuobigoNl4ouPVVfhuaE64omgN+G6j8WAeuKGkj3Cu2B8IF9gz4TigoAvMy/PhOKIqeKBiyIsIiIsIjEzNTc5MjQ2ODAiXQ==) ## How? ``` »@Ǐ+Ẇ₃e⋏UWṡ:≠7ẏŀz→=»`| _`τ₀/3/τ∩⁋ »@Ǐ+Ẇ₃e⋏UWṡ:≠7ẏŀz→=» # Push compressed integer 5210925748351095970666976465591163407510385 `| _` # Push string "| _" τ # Convert the integer to this custom base ₀/ # Split into ten pieces 3/ # Split each into three pieces τ # For each string, convert the (implicit) input to this custom base ∩ # Transpose ⁋ # Join on newlines ``` ]
[Question] [ Given an input integer `n`, draw a number snake, that is, a grid measuring `n x n` consisting of the numbers `1` through `n^2` that are wound around each other in the following fashion: Input `n = 3`: ``` 7 8 9 6 1 2 5 4 3 ``` Input `n = 4`: ``` 7 8 9 10 6 1 2 11 5 4 3 12 16 15 14 13 ``` Input `n = 5`: ``` 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13 ``` (Inspired by [this problem](https://projecteuler.net/problem=28) from Project Euler.) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes wins! [Answer] # [MATL](https://github.com/lmendo/MATL), 3 bytes ``` 1YL ``` [Try it online!](https://tio.run/##y00syfn/3zDS5/9/UwA "MATL – Try It Online") ### Explanation Built-in... ¯\\_(ツ)\_/¯ [Answer] # C#, ~~203~~ ~~202~~ ~~196~~ ~~193~~ 178 bytes ``` n=>{var r=new int[n,n];for(int o=n-2+n%2>>1,i=r[o,o]=1,c=2,w=o,h=o,b=1-2*(i%2),j;n>i++;){r[h,w+=b]=c++;for(j=0;j<i-1;++j)r[h+=b,w]=c++;for(j=0;j<i-1;++j)r[h,w-=b]=c++;}return r;} ``` *Saved a byte thanks to @StefanDelport.* *Saved 22 bytes thanks to @FelipeNardiBatista.* This works by the following observation of how the squares are built up: [![Image of square where n=5](https://i.stack.imgur.com/6Y5nn.png)](https://i.stack.imgur.com/6Y5nn.png) As you can see each bit is added on to the previous square. For even numbers we go right of where we were, down till were one lower than where the square was and then left to the end. Odd numbers are essentially the opposite, we go left one, up till were one above the current height and then right to the end. Full/Formatted version: ``` using System; using System.Linq; class P { static void Main() { Func<int, int[,]> f = n => { var r = new int[n, n]; for (int o = n - 2 + n % 2 >> 1, i = r[o, o] = 1, c = 2, w = o, h = o, b = 1 - 2 * (i % 2), j; n > i++;) { r[h, w += b] = c++; for (j = 0; j < i - 1; ++j) r[h += b, w] = c++; for (j = 0; j < i - 1; ++j) r[h, w -= b] = c++; } return r; }; Console.WriteLine(String.Join("\n", f(3).ToJagged().Select(line => String.Join(" ", line.Select(l => (l + "").PadLeft(2))))) + "\n"); Console.WriteLine(String.Join("\n", f(4).ToJagged().Select(line => String.Join(" ", line.Select(l => (l + "").PadLeft(2))))) + "\n"); Console.WriteLine(String.Join("\n", f(5).ToJagged().Select(line => String.Join(" ", line.Select(l => (l + "").PadLeft(2))))) + "\n"); Console.ReadLine(); } } public static class ArrayExtensions { public static T[][] ToJagged<T>(this T[,] value) { T[][] result = new T[value.GetLength(0)][]; for (int i = 0; i < value.GetLength(0); ++i) result[i] = new T[value.GetLength(1)]; for (int i = 0; i < value.GetLength(0); ++i) for (int j = 0; j < value.GetLength(1); ++j) result[i][j] = value[i, j]; return result; } } ``` [Answer] # Dyalog APL, ~~70~~ ~~56~~ ~~45~~ 41 bytes ``` ,⍨⍴∘(⍋+\)×⍨↑(⌈2÷⍨×⍨),(+⍨⍴1,⊢,¯1,-)(/⍨)2/⍳ ``` [Try it online!](http://tryapl.org/?a=%u236A%28%2C%u2368%u2374%u2218%28%u234B+%5C%29%D7%u2368%u2191%28%u23082%F7%u2368%D7%u2368%29%2C%28+%u2368%u23741%2C%u22A2%2C%AF1%2C-%29%28/%u2368%292/%u2373%29%A82+%u23734&run) **How?** ``` (+⍨⍴1,⊢,¯1,-)(/⍨)2/⍳ ``` calculates the differences between the indices; `1` and `¯1` for right and left, `¯⍵` and `⍵` for up and down. `1,⊢,¯1,-` comes as `1 ⍵ ¯1 ¯⍵`, `+⍨⍴` stretches this array to the length of `⍵×2`, so the final `2/⍳` can repeat each of them, with a repetition count increasing every second element: ``` (1,⊢,¯1,-) 4 1 4 ¯1 ¯4 (+⍨⍴1,⊢,¯1,-) 4 1 4 ¯1 ¯4 1 4 ¯1 ¯4 (2/⍳) 4 1 1 2 2 3 3 4 4 ((+⍨⍴1,⊢,¯1,-)(/⍨)2/⍳) 4 1 4 ¯1 ¯1 ¯4 ¯4 1 1 1 4 4 4 ¯1 ¯1 ¯1 ¯1 ¯4 ¯4 ¯4 ¯4 ``` then, ``` (⌈2÷⍨×⍨), ``` prepends the top-left element of the spiral, ``` ×⍨↑ ``` limit the first ⍵2 elements of this distances list, ``` +\ ``` performs cumulative sum, ``` ⍋ ``` grades up the indices (`⍵[i] = ⍵[⍵[i]]`), to translate the original matrix with the indices of every element, and finally ``` ,⍨⍴ ``` shapes as a `⍵×⍵` matrix. [Answer] # C, ~~321~~ ~~307~~ ~~295~~ ~~284~~ ~~283~~ 282 bytes *Thanks to both @Zachary T and @Jonathan Frech for golfing a byte!* ``` #define F for(b=a;b--;)l i,j,k,a,b,m;**l;f(n){n*=n;l=calloc(a=m=3*n,4);F[b]=calloc(m,4);for(l[i=j=n][j]=a=k=1;n>k;++a){F[i][++j]=++k;F[++i][j]=++k;++a;F[i][--j]=++k;F[--i][j]=++k;}for(i=0;i<m;++i,k&&puts(""))for(j=k=0;j<m;)(a=l[i][j++])>0&&a<=n&&printf("%*d ",(int)log10(n)+1,k=a);} ``` Allocates a two-dimensional array of zeroes, then starts filling it from somewhere in the middle. Lastly the values that are larger than zero but smaller than or equal to the square of the input are printed. [Try it online!](https://tio.run/##ZY/BbsMgDIbveYoo0yIIICVqd3LdY14iyoHQUpEAmdruFOXVl5lq3Q7lhL/vxzZGXYzZtrfT2bp4ztvczlc2oIZBKeA@c3KUk9RykAGqyoNlkS@xwggejfZ@NkxjwF0V5Z5D2w39E4cEUjffORwx9t3Yo8YJG4jHCYTQfGk713dCkBBiotdCuEcsVRSAh1fqzyv179fU22EN7hAo7ORUlp9f9xsrCs6TG2lWDSNZTjv61GoUoufHuiz1ASPFry7eLSveq1NeSEYF9/OlqemPopETag7rRjQP2kXGsyXL6Vi24/CcBL9o/4o@XlHT0HXdvo31@nLblA8/) **Formatted:** ``` #define F for(b=a; b--;)l i, j, k, a, b, m; **l; f(n) { n *= n; l = calloc(a=m=3*n, 4); F[b] = calloc(m, 4); for(l[i=j=n][j]=a=k=1; n>k; ++a) { F[i][++j] = ++k; F[++i][j] = ++k; ++a; F[i][--j] = ++k; F[--i][j] = ++k; } for(i=0; i<m; ++i, k&&puts("")) for(j=k=0; j<m;) (a=l[i][j++])>0 && a<=n && printf("%*d ", (int)log10(n)+1, k=a); } ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~32~~ 29 bytes ``` 1+×⍨-{⊖∘⌽⍣⍵⌽{⌽⍉,⌸⍵+≢⍵}⍣2⍣⍵⍪⍬} ``` [Try it online!](https://tio.run/##bZG9TsNAEIT7e4rpXCSWsns2wXkbK/iQhSWjhCay3EQI4ZBDUPBThwYhWiSERMWb7IuYDT/BQm7udufmmykuPS7Cg0ValIfhtEjn83zayuVNXsrZFbVuew4@7sQ/hpWsbuX8Xtbv4h/Ev@hQfS3NUNavKgyk2ehV6zP/WPyT@Oe6bU80p9oKzWamoxP/NglcmheBTqrP5OI0KI@C2pgMapDVcox9JCYbfm97IPBuixHBGguNvc66iDJIQKMOpyAYRB1YaVjQXx5pfAyKQNZE/1NZmxlswRE43jE8AnoKKQF6Skl9fcVjdLvj3279gdK5Tw "APL (Dyalog Classic) – Try It Online") Uses `⎕io←1`. Starts with a 0-by-1 matrix (`⍪⍬`). 2N times (`⍣2⍣⍵`) adds the height of the matrix (`≢⍵`) to each of its elements, puts `1 2...height` on its right (`,⌸`), and rotates (`⌽⍉`). When that's finished, corrects the orientation of the result (`⊖∘⌽⍣⍵⌽`) and reverses the numbers by subtracting them from N2+1 (`1+×⍨-`). [Answer] # [PHP](https://php.net/), 192 bytes ``` for($l=strlen($q=($a=$argn)**2)+$d=1,$x=$y=$a/2^$w=0;$i++<$q;${yx[$w%2]}+=$d&1?:-1,$i%$d?:$d+=$w++&1)$e[$x-!($a&1)][$y]=sprintf("%$l".d,$i);for(;$k<$a;print join($o)."\n")ksort($o=&$e[+$k++]); ``` [Try it online!](https://tio.run/##HY7djoJAFIPv9yncSSGMxz@4dDjhQVhMSEYFITAOJECMz84evWz7tamr3JpmrnI/KP29YxUnyqy33kdoeRh9e@0iPDlCyV9Ab7eJJliOd5gZi7jH5IKJTwY1UYqnwWuZc0xBUryJYcM4O@@FrgPY7Awr3kQUxhrXHPP@V6ZFFDmWggfn6268RSpAqw5WStp8vhg0KUrzTTePvpZPvT6ov07pZuj9KJJD2SM0RIU26/oP "PHP – Try It Online") Same way build a string instead of an array [PHP](https://php.net/), 217 bytes ``` for($l=strlen($q=($a=$argn)**2)+$d=1,$x=$y=($a/2^$w=0)-!($a&1),$s=str_pad(_,$q*$l);$i++<$q;${yx[$w%2]}+=$d&1?:-1,$i%$d?:$d+=$w++&1)$s=substr_replace($s,sprintf("%$l".d,$i),($x*$a+$y)*$l,$l);echo chunk_split($s,$a*$l); ``` [Try it online!](https://tio.run/##HY7djoIwEIXvfYqVHExL6w9cig0PslFSKSxkGywtBojx2bH1cmbO950xrVkvhWnNBtL@9SJKsyhfm4cl0MKNVtc9wSAIpPgGaJJklEGJlGMWWMLlmN0wiRPdb/2wSymHC2hppCIlx5BA0xwdYxcMOV7L/Ispzq5vJqB2aXHee1cXQxVnKL@bGPOS4Hjeg8bWRsuqJnDcGdv1Y0OiGDo6KI9RTjAnkAwL9T08VNVV@/ip2mf/XzqjuzGQkN8v1vUD "PHP – Try It Online") [Answer] # PHP, ~~185 176~~ 174 bytes ``` for(;$n++<$argn**2;${xy[$m&1]}+=$m&2?-1:1,$k++<$p?:$p+=$m++%2+$k=0)$r[+$y][+$x]=$n;ksort($r);foreach($r as$o){ksort($o);foreach($o as$i)printf(" %".strlen($n).d,$i);echo" ";} ``` Run as pipe with `-nR` or [test it online](http://sandbox.onlinephpfunctions.com/code/01f51bef6102edba9a92eddd782f62ffe40650f2). **breakdown** ``` for(;$n++<$argn**2; # loop $n from 1 to N squared ${xy[$m&1]}+=$m&2?-1:1, # 2. move cursor $k++<$p?: # 3. if $p+1 numbers have been printed in that direction: $p+=$m++%2+ # increment direction $m, every two directions increment $p $k=0 # reset $k )$r[+$y][+$x]=$n; # 1. paint current number at current coordinates ksort($r); # sort grid by indexes foreach($r as$o){ # and loop through it ksort($o); # sort row by indexes foreach($o as$i) # and loop through it printf(" %".strlen($n).d,$i); # print formatted number echo"\n"; # print newline } ``` [Answer] # Mathematica, 177 bytes ``` (n=#;i=j=Floor[(n+1)/2];c=1;d=0;v={{1,0},{0,-1},{-1,0},{0,1}};a=Table[j+n(i-1),{i,n},{j,n}];Do[Do[Do[a[[j,i]]=c++;{i,j}+=v[[d+1]], {k,l}];d=Mod[d+1,4],{p,0,1}],{l,n-1}];Grid@a)& ``` [Answer] # C++, ~~245~~ 228 bytes ``` void f(){for(int i=0,j=-1,v,x,y,a,b;i<n;i++,j=-1,cout<<endl)while(++j<n){x=(a=n%2)?j:n-j-1;y=a?i:n-i-1;v=(b=y<n-x)?n-1-2*(x<y?x:y):2*(x>y?x:y)-n;v=v*v+(b?n-y-(y>x?x:y*2-x):y+1-n+(x>y?x:2*y-x));cout<<setw(log10(n*n)+1)<<v<<' ';}} ``` [Try it online!](https://tio.run/##TZDdboMwDIXv/RSRprUJIROwX5EAz5ICbYPAoEIpUcWzs1Cmqb6wTj4fK7bzrhOnPF9eDOb1tSiJMm0/XErdpPDMGo2me0aNHs5v5xTg2hs8EdRN2Xc6L0k/FBLA4EBQLmNrCnKk7H5sL3RlJgn8KhGhP/qTb33tH6RRKA3nG87b66BUiUXNbmdTl5TzSiG7TwnVCb5GLKtiFJUIpU10Zpw2To8JPSRWoZhYhiIUkUcnZbMptixedbppgc45eiOnB2ezgtp0Wgte5Bpjy0OB/M8cedYxJrd5@nK40bo9hQFFDxkPmVKjUnuyl/O8rHs12iBlcAfi4jE5oblBkqYEyW7nUkoC9qhunjXcYeT/Y/2JKEXW3Tc6w7yEEME7fMAnfME3/EDwCw) The function calculates and prints the value of each number of the matrix depending on its *x, y* position by applying this logic: [![Snake values calculation depending on position](https://i.stack.imgur.com/WDPWe.jpg)](https://i.stack.imgur.com/WDPWe.jpg) **Formatted version**: ``` #include <iostream> #include <iomanip> #include <math.h> using namespace std; void f(int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int value = 0; // Invert x and y when n is even int x = n % 2 == 0 ? n - j - 1 : j; int y = n % 2 == 0 ? n - i - 1 : i; if (y < (n - x)) { // Left-top part of the matrix int padding = x < y ? x : y; value = n - 1 - padding * 2; value *= value; value += y >= x ? n - x - y : n + x - y - (y * 2); } else { // Right-bottom part of the matrix int padding = x > y ? n - x : n - y; value = n - padding * 2; value *= value; value += x > y ? y - padding + 1 : n + y - x - (padding * 2) + 1; } cout << setw(log10(n * n) + 1); cout << value << ' '; } cout << endl; } } int main() { int n; while (cin >> n && n > 0) { f(n); cout << endl; } } ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~249~~ 247 bytes I initialize an 2D array and find the starting point, which is the center for odd n or offset (-1,-1) for even n, then scale the fill/cursor pattern with the current 'ring' number. I feel like I'm missing a trick for interpreting the directions but I haven't come up with anything cheaper. ``` def f(n): M=[n*[0]for a in range(n)] x=y=n//2-1+n%2 M[x][y]=i=s=1 while 1: t=s*2 for d in'R'+'D'*(t-1)+'L'*t+'U'*t+'R'*t: if i==n*n:print(*M,sep='\n');return v=[1,-1][d in'LU'] if d in'UD':x+=v else:y+=v M[x][y]=i=i+1 s+=1 ``` [Try it online!](https://tio.run/##RU67boNAEOz5im2ivYeRc0RpSLZzaTeWqC5XIPsIJ1kLgrMDH56aHMhSmlnN7szs9HNsO35blqtvoBEsywxOZFnZV9d0A9QQGIaav326uQwmmon3@yIX/FJ8GpnUdnJ2dhRoJJPBTxtuHkyKgUijKtJcc64pB8@o8YBKxNxIjUdUUWO14TnhaoHQQCBixWU/BI5CnXaj7wm/GOXH4ON94FX2IGt2uXF2yz1W6J7mjVcHLCdNj3Xnb6Mv5yf57xp06gqjJrM0Yn0UuL9HIaVc3n@5yy/1pfV/ "Python 3 – Try It Online") -2 thanks to Zachary T! [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~(...)~~ 83 bytes Byte measured in UTF8, `\[LeftFloor]` (`⌊`) and `\[RightFloor]` (`⌋`) cost 3 bytes each. Mathematica doesn't have any special byte character set. ``` Table[Max[4x^2-Max[x+y,3x-y],4y y-{x+y,3y-x}]+1,{y,b+1-#,b=⌊#/2⌋},{x,b+1-#,b}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyQxKSc12jexItqkIs5IF8So0K7UMa7QrYzVMankqtStBvMrdStqY7UNdaordZK0DXWVdZJsH/V0KesbPerprtWproCJ1saq/Q8oyswrcQjJDy4BMtId3IsyUxzSok1j/wMA "Wolfram Language (Mathematica) – Try It Online") --- Uses the closed form for each of the 4 cases, then takes the maximum carefully to get the desired result. Returns a 2D array of integers. I'm not sure if this is allowed, and although [it has been asked in the comments](https://codegolf.stackexchange.com/questions/125966/wind-me-a-number-snake/154458#comment309960_125966), the OP didn't reply. [Answer] ## Clojure, 206 bytes ``` (defmacro F[s]`(if(~'r(+ ~'p ~'v ~s))~'v ~s)) #(loop[i 1 p(*(quot(dec %)2)(inc %))v 1 r{}](if(<(* % %)i)(partition %(map r(range i)))(recur(inc i)(+ p v)({1(F %)-1(F(- %))%(F -1)(- %)(F 1)}v)(assoc r p i)))) ``` I guess this is a decent start, builds the board in sequence to a hash-map and then partitions it into `n x n` lists. That `defmacro` ended up being quite long, but the code is still shorter with it than without. Is there a more succint syntax to describe it? Bulk of bytes calculate the starting point, and build the look-up logic of the next velocity `v`. Perhaps a nested `vec` would be better, but then you've got two indexes and velocities to keep track of. [Answer] # [J](http://jsoftware.com/), 41 bytes ``` (]|.@|:@[&0](|.@|:@,.*/@$+#\)@]^:[1:)2*<: ``` [Try it online!](https://tio.run/##y/r/P81WT0EjtkbPocbKIVrNIFYDwtTR09J3UNFWjtF0iI2zija00jTSsrH6n5qcka@QppCamJyhYKhgpGCsYKJg@h8A "J – Try It Online") Does the same thing as [ngn’s APL submission](https://codegolf.stackexchange.com/a/154468/74681) but starts with a 1-by-1 matrix and repeats 2×N−2 times. [Answer] # Python 165 (or 144) ``` from pylab import * def S(n): a=r_[[[1]]];r=rot90;i=2 while any(array(a.shape)<n): q=a.shape[0];a=vstack([range(i,i+q),r(a)]);i+=q if n%2==0:a=r(r(a)) print(a) ``` This creates a numpy array, then rotates it and adds a side until the correct size is reached. The question didn't specify if the same start point needs to be used for even and odd numbers, if that's not the case the line `if n%2==0:a=r(r(a))` can be removed, saving 21 bytes. [Answer] # [J](http://jsoftware.com/), 41 bytes ``` ,~$[:/:[:+/\_1|.1&,(]##@]$[,-@[)2}:@#1+i. ``` ## standard formatting ``` ,~ $ [: /: [: +/\ _1 |. 1&, (] # #@] $ [ , -@[) 2 }:@# 1 + i. ``` This approach is based off [*At Play With J Volutes*](https://www.jsoftware.com/papers/play132.htm) (Uriel's APL uses a similar technique). It's unexpected and elegant enough to justify a 2nd J answer, I thought. Essentially, we don't do anything procedural or even geometric. Instead, we arithmetically create a simple sequence that, when scan summed and graded up, gives the correct order of the spiraled number from left to right, top to bottom. We then shape that into a matrix and are done. I'll add a more detailed explanation when time permits, but the linked article explains it in depth. [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/depUoq30raKttPVj4g1r9AzVdDRilZUdYlWidXQdojWNaq0clA21M/X@a3KlJmfkK6QpmEAY6uowAdP/AA "J – Try It Online") [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 38 bytes ``` {(x,x)#<0,+\(,/-:\1,x)4!-1_&1+-1_&x#2} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700Oz4vPW_BgqWlJWm6Fjc10qyqNSp0KjSVbQx0tGM0dPR1rWIMgXwTRV3DeDVDbRBZoWxUC1WvW5xhlWBgpaGjpKSpo6SgpK-uol9jqKFbo6-vbKWurhmjYsVVnKGepm6irWhqDdEEswwA) [Answer] # [Python 3 (Stackless)](https://github.com/stackless-dev/stackless), ~~192~~ ~~188~~ ~~179~~ 150 bytes ``` lambda n:[list(map(v,list(range(t-n,t)),[y]*n))for t in[1+n//2]for y in range(n-t,-t,-1)] v=lambda x,y,r=0:y>=abs(x)and(3-2*r+4*y)*y+x+1or v(y,-x,r+1) ``` [Try it online!](https://tio.run/##RY7LCoMwFET3fkWWuXlgo6ULIf0R6yJWbaV6lSRI8vWptoXCLObAcJg1@ueCpXTe3F9T71wa9C1NZm47Q7Cqp9F5OpuVbuJTrcFHT71E4QFEHRuGAMNiiScj1opjnhfNwXFn8l2j9OKIgibb9M8dRBRWn6p41aZ1NIDBjpayYJafWQQWeeBq92w0ChmE5QrS4cW/9wJVRlY7oqcD3W@kNw "Python 3 (Stackless) – Try It Online") The algorithm here is to form a phasor for each coordinate in the grid, and then rotate it 90-degrees clockwise until the phasor lies between the upper diagonals. A simple formula can be used to calculate the value based on the coordinates and the number of clockwise rotations: $$ (2y+1)^2-(y-x)-2yr $$ Saved 4-bytes since 90-degree phasor rotation is easily done without complex numbers [Answer] # [R](https://www.r-project.org/), 183 bytes ``` x=scan() b=t(d<-1) while(2*x-1-d){m=max(b) y=(m+1):(m+sum(1:dim(b)[2]|1)) z=d%%4 if(z==1)b=cbind(b,y) if(z==2)b=rbind(b,rev(y)) if(z==3)b=cbind(rev(y),b) if(z==0)b=rbind(y,b) d=d+1} b ``` [Try it online!](https://tio.run/##PY5BbsIwEEX3PoWlCmmmkKgOsEHMSSoWdmy3lrBBTigOIWdPY0GyeYv3/x9NHD/4Pcorb2oZALkLXHJ7C3XrLoHbS@RGNs5E3pqmdeGHWZpTSNjn1bFYTFmW2KdhTPQ6xxS1oI@FQHb/dWcD1WcqRKGx9@RlAoWsI/BrgYeJzc2DOGjnJ/9dnZ4CkT1Ir1Y75iw8iAQqqpULGtSmw7esJhnfMpo/6HBOtkv95TdqTr6WTZelJr0WA1PjwCxMv1qoMrYZu4w9jv8 "R – Try It Online") Output is a matrix snake (or snake matrix, whatever). It's probably not the most efficient method, and it could likely be golfed, but I thought it was worth showing. I'm rather proud of this actually! The method builds the matrix from the inside out, always appending an additional number of integers equal to the number of columns in the matrix before appending. The pattern that follows is either binding by columns or by rows, while also reversing some values so they are appended in the correct order. # 193 bytes Exact same as above, but final `b` is ``` matrix(b,x) ``` [Try it online!](https://tio.run/##PY5BbsMgEEX3nAKpijTT2FZx0k0UThJ1AQZapEAqTBIc12d3QYm9eYv3549@mN/oPYhf2nfCA1LrqaDm6rtoL56aS6Ba9FYHGnUfrf8mhi8pJBxL61ivpmkaHNM0J/58RySPoI41Q3L/sWcN7XuqWa1wdNyJBBLJwMFtGR4y@6sDdlDWZX9qv/4YInlwtdnsiTXw4Jyh5J20XoGsBnzJNsvwkkHfYMAl2a3nT1/JJflYO0ORiqstm4gTMdg8qko4T8RAXm2gLdgV7As@cf4H "R – Try It Online") which gives slightly cleaner output, but I didn't see any special criteria for output, so the first answer should work if I'm not mistaken. ]
[Question] [ # Guidelines ## Task Write a method that takes an array of consecutive (increasing) letters as input and that returns the missing letter in the array (lists in some languages). --- ## Rules * This is code golf so the shortest answer in bytes wins! * You will always get a valid array * There will always be exactly one letter missing * The length of the array will always be at least 2. * The array will always contain letters in only one case (uppercase or lowercase) * You must output in the same case (uppercase or lowercase) that the input is * The array will always only go one letter a time (skipping the missing letter) * The array length will be between 2 and 25 * The first or last element of the array will never be missing --- # Examples `['a','b','c','d','f'] -> 'e'` `['O','Q','R','S'] -> 'P'` `['x','z'] -> 'y'` `['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','w','x','y','z'] -> 'v'` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 48 47 46 bytes, input as char array ``` s=>{for(int i=0;s[++i]==++s[0];);return s[0];} ``` [Try it online!](https://tio.run/##rc8xU4MwGAbgnV/xbcCBbXeki3dOelY7OHAMMQ00CokmoRV7/HZ8g1o7OPV87x5IOHj5wu0F10aMhPCGWUsro2vD2sA/OUxXH@uYk5x2Wm7olkkVWWekqouSmKltfHzv9wufdW@daGfXneKXfMtMUabk70uqKKdgtPnyUGkTSeVI5ovMFkkiyzxPElssyizOjHCdUTTthjEL/mq/0srqRswejXTiRioRVZESe/r64SFkYRo@AYcNVOEQxxnRfE7inL47dNzDA6y/u3zQtzqn7x09Hyc9P0Ff/x/nFdOZ07CGLUh4hhdooAUFGl7hDQxYcNDBHvyc/cmsmG93nG@YVsP4CQ "C# (.NET Core) – Try It Online") Explanation: the first element in the array is incremented as well as a pointer iterating the following elements. When both the first element and the current element are different, it returns the first element. # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 58 56 50 bytes, input as string ``` s=>{var c=s[0];while(s.IndexOf(++c)>=0);return c;} ``` [Try it online!](https://tio.run/##jc09a8NADAbg3b9CZLojrZP9ai@BQqEhX0OHkOEqy86BcwfS5avBv92JnZIuHfIOQrzoQSivGJhauAVrKwJzDhXbXdI1l352kWijQzgEV8DUOq8ksvPVegOWK9GPuz/RZXWWSLv0fe/x7Q5eALeWcyghg6SVLL8cLANmsh5vzHHralKSfviCTrNSDYeo82ysDVPcswc0TWuS/z5MgpdQU/rFLtKn86RKNbDfWJQDrQ3AaAT0tJstlqs769z8aXf6@VW9Oz9c029NewU "C# (.NET Core) – Try It Online") Previous 58-byte solution (referenced in the first comment): ``` s=>{for(int i=1;;i++)if(s[i]-s[0]>i)return(char)(s[i]-1);} ``` ### Algorithms using System.Linq The following algorithms must add `using System.Linq;` (18 bytes) to the byte count and therefore are longer. I quite liked this one (52+18 bytes): ``` s=>{int i=0;return(char)(s.First(c=>c-s[0]>i++)-1);} ``` And you also have a one-liner (45+18)-byte solution: ``` s=>(char)(s.Where((c,i)=>c-s[0]>i).First()-1) ``` And a very clever (37+18)-byte solution, courtesy of Ed'ka: ``` s=>s.Select(e=>++e).Except(s).First() ``` [Answer] ## [Alice](https://github.com/m-ender/alice), 10 bytes ``` /X. \ior@/ ``` [Try it online!](https://tio.run/##S8zJTE79/18/Qo8rJjO/yEH//3//wKBgAA "Alice – Try It Online") ### Explanation This is just a framework for linear programs that operate entirely in Ordinal (string processing) mode: ``` /... \.../ ``` The actual linear code is then: ``` i.rXo@ ``` Which does: ``` i Read all input. . Duplicate. r Range expansion. If adjacent letters don't have adjacent code points, the intermediate code points are filled in between them. E.g. "ae" would turn into "abcde". For the inputs in this challenge, this will simply insert the missing letter. X Symmetric set difference. Drops all the letters that appear in both strings, i.e. everything except the one that was inserted by the range expansion. o Output the result. @ Terminate the program. ``` [Answer] # [Haskell](https://www.haskell.org/), ~~33~~ 30 bytes ``` f a=until(`notElem`a)succ$a!!0 ``` [Try it online!](https://tio.run/##Zc07DsIwEATQnlNsJCQnUgoukJIaASVCinFsYuJPiG3xubwZEA2keM3saqbnYZDG5KyIN8lFbcrW@bg20ra8CkmIJS@KVbZcO2qo8wuicdIuUqnowDir2QkEdKDYsfr92CDdwg72s@sd6XOW/rfKT3PNztCDhgsMYMCCAw8jXGGCABES3OC99vgu5hc "Haskell – Try It Online") [Answer] # Ruby, 21 characters ``` ->a{[*a[0]..a[-1]]-a} ``` Returns a single element array, according to question owner's [comment](https://codegolf.stackexchange.com/questions/132771/find-the-missing-letter#comment325946_132771). Sample run: ``` irb(main):001:0> ->a{[*a[0]..a[-1]]-a}[['a','b','c','d','f']] => ["e"] ``` [Try it online!](https://tio.run/##Xc09CsJAGITh3lOk@yBkgzmAXkHUctnii7r@a0yyaBTPvr6KCLF4mhmYqUPZRZ@Mohnrw6Zqhy7P1ZrCOaPPWIW2Sby1opJJiQWW8OLc4NdOSKaYYd5rbiT3XvK/tPqsZbLGBlvssMcBR5xwRoULajRoEXDF@6n7vsUX "Ruby – Try It Online") [Answer] # Java 8, ~~70~~ ~~57~~ ~~56~~ ~~48~~ 46 bytes ``` a->{for(int i=0;++a[0]==a[++i];);return a[0];} ``` -14 (70 → 56) and -2 (48 → 46) bytes thanks to *@CarlosAlejo*. -8 (56 → 48) bytes thanks to *@Nevay*. **Explanation:** [Try it here.](https://tio.run/##lc6xboMwFAXQPV/xNkAkKLtF/6CJWkbE8GJMYgKGGpM0RXw7vUCHqlMj@ciyrft8S77xrmmVKfPrJCvuOnplbYYNkTZO2YKlosN8JJIXtiT9eUsz4kDgdgSszrHTkg5kKKaJdy9D0VgfE0jHexGGnO6zOOY0DHUmAmGV662h@VaMk1hntP2pwoyfUbdG51Sjip84q815@XHtkTw6p@qo6V3U4slVxjeR9I2609pt8NjbeieQkEPhjcHS91/pIxJv8A7JU8lPJL6eSvxtqpa2W@8MF9BQwhUqqMFAAy18gIUOHPRwh7nJ43ebcTNO3w) ``` a->{ // Method with char-array parameter and char return-type for(int i=0; // Start index-integer at 0 and loop as long as ++a[0] // the previous character + 1 (by modifying the character at index 0) ==a[++i]; // equals the next character (by raising the index by 1 before checking) ); // End of loop return a[0]; // Return the now modified character at index 0 in the array } // End of method ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 33 ~~35~~ ~~36~~ ~~48~~ ~~60~~ bytes All optimizations should be turned off and only on 32-bit GCC. ``` f(char*v){v=*v+++1-*v?*v-1:f(v);} ``` Take input as a string. [Try it online!](https://tio.run/##S9ZNT07@/z9NIzkjsUirTLO6zFarTFtb21BXq8xeq0zX0CpNo0zTuvZ/bmJmnoYmVzWXAhAUFGXmlaRpKKkmK4BRTJ6SDpBbUaWkCaITk5JTUtMhbP/AoGAlTU1rsL6i1JLSojwFA2uu2v8A "C (gcc) – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 5 bytes ``` -rhQe ``` [Try it online!](http://pyth.herokuapp.com/?code=-rhQe&input=%22abcdf%22&debug=0) [Answer] # [Python 3](https://docs.python.org/3/), ~~74~~ ~~62~~ ~~58~~ ~~44~~ 40 bytes *-12 bytes thanks to Erik the Outgolfer. -18 bytes thanks to Leaky Nun. -4 bytes thanks to musicman523.* Takes input as a bytestring. ``` lambda s:chr(*{*range(s[0],s[-1])}-{*s}) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYKjmjSEOrWqsoMS89VaM42iBWpzha1zBWs1a3Wqu4VvN/QVFmXolGmkaSuqOTs4ubuqbmfwA "Python 3 – Try It Online") Another cool solution: ``` lambda s:chr(*{*range(*s[::~-len(s)])}-{*s}) ``` [Answer] # Mathematica, 46 bytes ``` Min@Complement[CharacterRange@@#[[{1,-1}]],#]& ``` [Answer] # SWI Prolog, 124 bytes ``` m([H|T]):-n(H,N),c(T,N),!,m(T). n(I,N):-o(I,C),D is C+1,o(N,D). c([N|_],N). c(_,N):-print(N),!,fail. o(C,O):-char_code(C,O). ``` Examples: ``` ?- m(['a','b','c','d','f']). e false. ?- m(['O','Q','R','S']). 'P' false. ?- m(['x','z']). y false. ?- m(['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','w','x','y','z']). v false. ``` Little explanation: The `m` is the "main" procedure,the `n` produces next expected character in the list. The `c` does comparison - if expectation matches the next item, continue, else print out expected character and jump out of the window. [Answer] # JavaScript (ES6), 70 bytes Input as a character array ``` (a,p)=>a.some(c=>(q=p+1,p=c.charCodeAt(),p>q))&&String.fromCharCode(q) ``` *Less golfed* ``` a=>{ p = undefined; for(i = 0; c = a[i]; i++) { q = p+1 p = c.charCodeAt() if (p>q) return String.fromCharCode(q) } } ``` **Test** ``` F=(a,p)=>a.some(c=>(q=p+1,p=c.charCodeAt(),p>q))&&String.fromCharCode(q) function update() { var a0=A0.value.charCodeAt() var a1=A1.value.charCodeAt() if (a1>a0) { var r = [...Array(a1-a0+1)] .map((x,i)=>String.fromCharCode(a0+i)) .filter(x => x != AX.value) I.textContent = r.join('') + " => " + F(r) } else { I.textContent='' } } update() ``` ``` input { width: 1em } ``` ``` Range from <input id=A0 value='O' pattern='[a-zA-Z]' length=1 oninput='update()'> to <input id=A1 value='T' pattern='[a-zA-Z]' length=1 oninput='update()'> excluding <input id=AX value='Q' pattern='[a-zA-Z]' length=1 oninput='update()'> <pre id=I></pre> ``` [Answer] # PHP>=7.1, 46 bytes Take input as string ``` <?=trim(join(range(($a=$argn)[0],$a[-1])),$a); ``` [PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/5e8ddc120a13de8ea2ab8af28d99a31d462b409c) [Answer] # Excel, 110 + 2 = 112 bytes ``` =CHAR(CODE(LEFT(A1))-1+MATCH(0,IFERROR(FIND(CHAR(ROW(INDIRECT(CODE(LEFT(A1))&":"&CODE(RIGHT(A1))))),A1),0),0)) ``` Must be entered as an array formula (`Ctrl`+`Shift`+`Enter`) which adds curly brackets `{ }` on each end, adding two bytes. Input is as a string in `A1`, which is OK [per OP](https://codegolf.stackexchange.com/q/132771/#comment325946_132771). This is not the shortest answer by far (Excel rarely is) but I like seeing if it can be done. [Answer] # [Retina](https://github.com/m-ender/retina), ~~33~~ 25 bytes ``` $ ¶$_ T`p`_p`.*$ D`. !`.$ ``` [Try it online!](https://tio.run/##K0otycxL/P9fhevQNpV4rpCEgoT4ggQ9LRUulwQ9LsUEPZX///0DggA "Retina – Try It Online") Works with any range of ASCII characters. Edit: Saved 8 bytes thanks to @MartinEnder. Explanation: The first stage duplicates the input. The second decreases all of the characters in the copy by 1 code point. The third stage deletes all of the characters in the copy that still appear in the original. This just leaves the original input, the character that precedes the first character of the original input and the missing character. The last stage then just matches the missing character. [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` →S-(ḣ→ ``` [Try it online!](https://tio.run/##yygtzv7//1HbpGBdjYc7FgMZ////T0xKTkkDAA "Husk – Try It Online") This function takes a string (list of characters) as input, and returns a character as output. ### Explanation ``` →S-(ḣ→ ḣ→ Get the list of all characters from the null byte to the last character of the input S- Subtract the input from this list → Get the last element of the result ``` [Answer] ## C++14, standard library, generic container type (87 86 bytes) ``` [](auto a){return++*adjacent_find(begin(a),end(a),[](auto a,auto b){return a+1!=b;});} ``` Container type from namespace `::std` is assumed (e.g. `std::string`, `std::list` or `std::vector`. Otherwise `using namespace std;` or similar would be assumed. > > Thanks to @Ven, with a little bit of preprocessor hacking, you get get it **down to 82 bytes** (1 newline) > > > > ``` > #define x [](auto a,int b=0){return++ > x *adjacent_find(begin(a),end(a),x a!=b;});} > > ``` > > See it **`[Live On Coliru](http://coliru.stacked-crooked.com/a/3c65480891bb98dc)`** ## C++14 no standard library (still generic, 64 63 bytes) ``` [](auto& a){auto p=*begin(a);for(auto c:a)if(c!=p++)return--p;} ``` Again, need to help name lookup only if container type not from namespace `::std` (or associated with it) **`[Live On Coliru](http://coliru.stacked-crooked.com/a/e942356def26b422)`** for `std::string` e.g. **`[Live On Coliru](http://coliru.stacked-crooked.com/a/04483566b1dd8079)`** for `char const[]` e.g. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` O‘Ọḟ⁸Ḣ ``` [Try it online!](https://tio.run/##y0rNyan8/9//UcOMh7t7Hu6Y/6hxx8Mdi/4fbn/UtCby/3/1xKTklDR1HQV1/8CgYBBdUQUiQcKpaekZmVnZObl5@QWFRcUlpeUVlVXqAA "Jelly – Try It Online") ## How it works ``` O‘Ọḟ⁸Ḣ - Main link. Takes a string S on the left O - Convert to char codes ‘ - Increment each Ọ - Convert from char codes This yields the characters that directly follow each character in S Call this C ⁸ - Yield S ḟ - Remove the characters from C that are in S Ḣ - Return the first one ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes ``` Fγ¿¬∨∨‹ι⌊θ›ι⌈θ№θιι ``` [Try it online!](https://tio.run/##NYkxDoMwDAC/4tGWkhd07MDSln7BCoFagkQ4oeL3JiAh3XJ34ccaMs9mY1bAiUBGwE@u2OvJK5aC4uAtSZZtwZXIQaeRa9Sr8373Np55SxVXB9KU4KvSVOhhxiEO5v/my3wA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a string. Works with any almost contiguous sequence of ASCII characters. [Answer] # C#, 104 bytes ``` using System.Linq;a=>(char)Enumerable.Range(a.Min(),a.Max()-a.Min()).Except(a.Select(c=>(int)c)).First() ``` Full/Formatted version: ``` using System.Linq; namespace System { class P { static void Main() { Func<char[], char> f = a => (char)Enumerable.Range(a.Min(), a.Max() - a.Min()) .Except(a.Select(c=>(int)c)) .First(); Console.WriteLine(f(new[] { 'a', 'b', 'c', 'd', 'f' })); Console.ReadLine(); } } } ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 17 bytes ``` (⊃⎕AV/⍨∨\∧~)⎕AV∘∊ ``` [Try it online!](https://tio.run/##Xc07CsJQEIXh3lXYjUIka3AFooKVzY0x8XE18YXGwkaQS0CxEdyBWddsJP7e0uKDw2EOY3LbiQtjs7SuE709W1pe9fHqjkK9V@qqsbrPpe0bdW91JWdNMRJIhAliJNKg7ZH6GGDomxPp7NP/YupXgaSYYY4FlrBYYY0MOTbYYoc9Djji96HwX74 "APL (Dyalog Unicode) – Try It Online") `⎕AV∘∊` Boolean: each character in the **A**tomic **V**ector (character set) member of the argument? `(`…`)` apply the following tacit function:  `⊃` the first element of  `⎕AV` the **A**tomic **V**ector (the character set)  `/⍨` which  `∨\` follows the initial (member of the argument)  `∧` but  `~` is not (a member of the argument) [Answer] # [Python 3](https://docs.python.org/3/), 42 bytes ``` f=lambda a,*r:r[0]-a>1and chr(a+1)or f(*r) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIVFHq8iqKNogVjfRzjAxL0UhOaNII1HbUDO/SCFNQ6tI839BUWZeiQaQnaTuHxgUrK6p@R8A "Python 3 – Try It Online") Uses unpacked bytestring as input: `f(*b'OQRS')` [Answer] # [Rexx (Regina)](http://www.rexx.org/), 56 bytes ``` a=arg(1) say translate(xrange(left(a,1),right(a,1)),'',a) ``` [Try it online!](https://tio.run/##JcsxDoAgDADA3Ve4AQkLD/AxVSugiFowFj@PJG63HCFzrTAAWWlUl6D0mSCmABklN1mUAZcsQRulyVv3U2khNKja7jjNuFjn1y3s8TgvSvl@uLwf "Rexx (Regina) – Try It Online") Finally one that enables REXX to use its strong string-manipulation. [Answer] # [CJam](https://sourceforge.net/p/cjam), 6 bytes (full program) / 7 bytes (code block) ``` q),^W= ``` [Try it online!](https://tio.run/##S85KzP3/v1BTJy7c9v//gsKi4pKy8orKKgA "CJam – Try It Online") This is a full CJam program that reads the input string from standard input and prints the missing letter to standard output. CJam doesn't actually have "methods", which is what the challenge asks for, but the closest thing would probably be an executable code block, like this: ``` {),^W=} ``` [Try it online!](https://tio.run/##S85KzP2vVFBYVFxSVl5RWaX0v1pTJy7ctvZ/3X8A "CJam – Try It Online") This code block, when evaluated, takes the input as a string (i.e. an array of characters) on the stack, and returns the missing character also on the stack. --- **Explanation:** In the full program, `q` reads the input string and places it on the stack. `)` then pops off the last character of the input string, and the range operator `,` turns it into an array containing all characters with code points below it (including all letters before it in the alphabet). Thus, for example, if the input was `cdfgh`, then after `),` the stack would contain the strings `cdfg` (i.e. the input with the last letter removed) and `...abcdefg`, where `...` stands for a bunch of characters with ASCII codes below `a` (i.e. all characters below the removed last input letter). The symmetric set difference operator `^` then combines these strings into a single string that contains exactly those characters that appear in one of the strings, but not in both. It preserves the order in which the characters appear in the strings, so for the example input `cdfg`, the result after `),^` will be `...abe`, where `...` again stands for a bunch of characters with ASCII codes below `a`. Finally, `W=` just extracts the last character of this string, which is exactly the missing character `e` that we wanted to find (and discards the rest). When the program ends, the CJam interpreter implicitly prints out the contents of the stack. --- # Bonus: [GolfScript](http://www.golfscript.com/golfscript/), 6 bytes (full program) ``` ),^-1> ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/X1MnTtfQ7v//gsKi4pKy8orKKgA "GolfScript – Try It Online") It turns out that nearly the same code also works in GolfScript. We save one byte in the full program version due to GolfScript's implicit input, but lose one byte because, unlike CJam's `W`, GolfScript doesn't have a handy single-letter variable initialized to -1. Also, CJam has separate integer and character types (and strings are just arrays containing characters), whereas GolfScript only has a single integer type (and has a special string type that behaves somewhat differently from normal arrays). The result of all this is that, if we want the GolfScript interpreter to print out the actual missing letter instead of its ASCII code number, we need to return a single-character string instead of just the character itself. Fortunately, making that change here just requires replacing the indexing operator `=` with the array/string left truncation operator `>`. Of course, thanks to GolfScript's implicit I/O, the code above can also be used as a snippet that reads a string from the stack and returns a single-character string containing the missing letter. Or, rather, any snippet that takes a single string on the stack as an argument, and returns its output as a printable string on the stack, is also a full GolfScript program. [Answer] # Python 2 - 76 bytes Loses to existing python 2 solution but it's a slightly different approach so I thought I'd post it anyway: ``` lambda c:[chr(x)for x in range(ord(c[0]),ord(c[0]+26)if chr(x)not in c][0] ``` [Answer] ## JavaScript (ES6), 64 bytes Takes input as a string. ``` s=>(g=p=>(c=String.fromCharCode(n++))<s[p]?p?c:g(p):g(p+1))(n=0) ``` ### How? * Initialization: We start with ***n = 0*** and ***p = 0*** and call the recursive function ***g()***. ``` g = p => // given p (c = String.fromCharCode(n++)) < s[p] ? // if the next char. c is not equal to s[p]: p ? // if p is not equal to zero: c // step #3 : // else: g(p) // step #1 : // else: g(p + 1) // step #2 ``` * Step #1: We increment ***n*** until `c = String.fromCharCode(n)` is equal to the first character of the input string ***s[0]***. * Step #2: Now that we're synchronized, we increment both ***n*** and ***p*** at the same time until `c = String.fromCharCode(n)` is not equal to ***s[p]*** anymore. * Step #3: We return ***c***: the expected character which was not found. ### Test cases ``` let f = s=>(g=p=>(c=String.fromCharCode(n++))<s[p]?p?c:g(p):g(p+1))(n=0) console.log(f('abcdf')) // -> 'e' console.log(f('OQRS')) // -> 'P' console.log(f('xz')) // -> 'y' console.log(f('abcdefghijklmnopqrstuwxyz')) // -> 'v' ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 3 bytes ``` -¹… ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8b/uoZ2PGpb9//8/WikxKTklTUlHyT8wKBhIVVQBCZBYalp6RmZWdk5uXn5BYVFxSWl5RWWVUiwA "Husk – Try It Online") I'm slightly nervous about posting this, as it seems wierd to beat all other answers (including [one](https://codegolf.stackexchange.com/a/133042/95126) in [Husk](https://github.com/barbuz/Husk)) by such a significant margin... but it seems to work for the test cases, at least... **How?** ``` - # output elements that are different between: ¹ # 1. the input list, and … # 2. the input list, with all the gaps filled # with the missing character ranges ``` [Answer] # k, ~~17~~ 13 bytes -4 bytes [thanks to coltim](https://codegolf.stackexchange.com/questions/132771/find-the-missing-letter/132851?noredirect=1#comment506450_132851). ``` {*(`c$1+x)^x} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qWksjIVnFULtCM66i9n@auoZSYlJySpqStZJ/YFAwkKqoAhIgsdS09IzMrOyc3Lz8gsKi4pLS8orKKiXN/wA "K (oK) – Try It Online") Explanation: ``` { } /def func(x): # x should be a list of chars 1+x / above = [ord(c)+1 for c in x] (`c$ ) / above = [chr(i) for i in above] ^x / result = [e for e in above if e not in x] * / return result[0] ``` [Answer] # MATL, ~~8~~ 7 bytes *1 byte saved thanks to @Luis* ``` tdqf)Qc ``` Try it at [MATL Online](https://matl.io/?code=tdqf%29Qc&inputs=%27abcdefghijklmnopqrstuwxyz%27&version=20.2.0) **Explanation** ``` % Implicitly grab the input as a string t % Duplicate the string d % Compute the differences between successive characters q % Subtract 1 from each element f % Get the locations of all non-zero characters (1-based index) ) % Extract that character from the string Q % Add one to get the next character (the missing one) c % Convert to character and display ``` [Answer] # [Arturo](https://arturo-lang.io), 21 bytes ``` $->s[--@s\0..last<=s] ``` [Try it!](http://arturo-lang.io/playground?lZuQIF) ``` $->s[ ; a function taking an argument s <=s ; duplicate s last ; last letter in s .. ; range s\0 ; first letter in s @ ; reify range -- ; set difference (between the range and duplicated s) ] ; end function ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` .ịOr/Ọḟ ``` [Try it online!](https://tio.run/##y0rNyan8/1/v4e5u/yL9h7t7Hu6Y/////8Sk5JQ0AA "Jelly – Try It Online") ]
[Question] [ **Background** Here is a Halloween related challenge. As you may have seen from my last [challenge](https://codegolf.stackexchange.com/questions/93610/the-house-of-santa-claus) I quite like what I term as ascii art animations, that is not just draw a pattern but draw a pattern that progresses. This idea came to me after I was asked a couple of years ago to liven up a (rather dull) presentation by making random ascii bats fly across the screen on Halloween. Needless to say I duly obliged (I was being paid for it) but it made me think that there is more to life than random bats. Inspired by this I would like to propose this challenge. **Challenge** Make a bat fly around the moon. Here is a bat: ``` ^o^ ``` Here is the moon: ``` mmm mmmmmmm mmmmmmmmm mmmmmmm mmm ``` You must show every stage of the bats flight (see output). **Input** None **Output** ``` ^o^ mmm mmmmmmm mmmmmmmmm mmmmmmm mmm mmm^o^ mmmmmmm mmmmmmmmm mmmmmmm mmm mmm mmmmmmm^o^ mmmmmmmmm mmmmmmm mmm mmm mmmmmmm mmmmmmmmm^o^ mmmmmmm mmm mmm mmmmmmm mmmmmmmmm mmmmmmm^o^ mmm mmm mmmmmmm mmmmmmmmm mmmmmmm mmm^o^ mmm mmmmmmm mmmmmmmmm mmmmmmm mmm ^o^ mmm mmmmmmm mmmmmmmmm mmmmmmm ^o^mmm mmm mmmmmmm mmmmmmmmm ^o^mmmmmmm mmm mmm mmmmmmm ^o^mmmmmmmmm mmmmmmm mmm mmm ^o^mmmmmmm mmmmmmmmm mmmmmmm mmm ^o^mmm mmmmmmm mmmmmmmmm mmmmmmm mmm ^o^ mmm mmmmmmm mmmmmmmmm mmmmmmm mmm ``` **Rules** * No reading from external files or websites * You may submit a full program or a function * Extra spaces and/or newlines are fine by me * Standard loopholes banned as usual * The bat must finish back at the top of the moon * Please feel free to clear the screen between frames if you wish however this is not a requirement. Output as shown above is fine * As this is code golf, the winner will be the answer with the lowest byte count although any answer is welcome **Sample** Reference implementation in totally ungolfed Python 2 (620 bytes but just to prove that it can be done. May golf it later). ``` b='^o^' m=[' ', ' mmm ', ' mmmmmmm ', ' mmmmmmmmm ', ' mmmmmmm ', ' mmm ', ' '] p=[(9,12),(12,15),(14,17),(15,18),(14,17),(12,15),(9,12),(6,9),(4,7),(3,6),(4,7),(6,9),(9,12)] d=0 for z in range(7): x=map(str,m[z]) c="".join(x[:p[z][0]]) + b + "".join(x[p[z][1]:])+"\n" print "\n".join(m[:z]) + "\n" + c+"\n".join(m[z+1:]) for z in range(6)[::-1]: x=map(str,m[z]) c="".join(x[:p[z+6][0]]) + b + "".join(x[p[z+6][1]:])+"\n" print "\n".join(m[:z]) + "\n" + c+"\n".join(m[z+1:]) ``` **Result** Although @Jonathan obviously wins on byte count with Jelly, I am going to mark the Brainfuck answer from @Oyarsa as the accepted answer purely because I think that anyone who can actually do something like this in such a crazy language deserves +15 rep no matter how many bytes it takes. This is not because I have any problem with golfing languages. See my answer to a question regarding this on [meta](http://meta.codegolf.stackexchange.com/questions/10127/how-can-we-help-users-who-are-put-off-by-the-use-of-golfing-languages/10307?noredirect=1#comment33135_10307) if you have any doubts. Many thanks and respect to all who contributed in whatever language. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~69~~ ~~62~~ 60 bytes Saved 2 bytes thanks to *Adnan*. ``` 3ð×…^o^)U13FNV0379730vð5y>;ï-y_+×N(Y-12%_Xè'my×NY-12%_y&XèJ, ``` [Try it online!](http://05ab1e.tryitonline.net/#code=M8Oww5figKZeb14pVTEzRk5WMDM3OTczMHbDsDV5PjvDry15XyvDl04oWS0xMiVfWMOoJ215w5dOWS0xMiVfeSZYw6hKLA&input=) **Explanation** `3ð×…^o^)U` stores the list `[" ","^o^"]` in **X** for later use. `13FNV` loops over the 13 stages *[0 .. 12]* and stores the current iteration index in **Y**. `0379730v` loops over the rows of each stage, where **N** is the row index and **y** is the current number of *m's*. We start by adding `floor(5/(y+1))-(y==0)` spaces to each row with `ð5y>;ï-y_+×`. We then determine if there should be a bat or 3 spaces before the *m's*. If `(-N-Y)%12 == 0` is true we add a bat, else 3 spaces. This expression (`N(Y-12%_Xè`) will place bats in stages `0,6-12`. Then we place **y** *m's* with `'my×`. Now we determine if there should be a bat or 3 spaces after the *m's*. The code `NY-12%_y&Xè` will place a bat if `((N-Y)%12 == 0) and y!=0` is true, else 3 spaces. This will place the bats on stages `1-5`. Finally we join the whole row into a string and print with a newline: `J,`. [Answer] ## JavaScript (ES6), ~~109~~ ~~144~~ ~~140~~ 138 bytes ``` f=(k=13,b=y=>(y-k)%12?' ':'^o^')=>k--?[0,3,7,9,7,3,0].map((n,y)=>' '.repeat(5-n/2+!n)+b(y)+'m'.repeat(n)+b(n?-y:.1)).join` `+` `+f(k):'' console.log(f()); ``` ### Animated version ``` f=(k,b=y=>(y-k)%12?' ':'^o^')=>[0,3,7,9,7,3,0].map((n,y)=>' '.repeat(5-n/2+!n)+b(-y)+'m'.repeat(n)+b(n?y:.1)).join` ` var k =0; setInterval(function() { o.innerHTML = f(k++) }, 150); ``` ``` <pre id=o></pre> ``` [Answer] ## HTML+JS, ~~153~~ 149 bytes ``` n=setInterval(_=>o.innerText=`zzd zc3e b7f a9g l7h zk3i zzj`.replace(/\S/g,c=>parseInt(c,36)-n%12-10?`m`.repeat(c)||` `:`^o^`,n++),1e3) ``` ``` <pre id=o> ``` Edit: Saved a bunch of bytes thanks to @RickHitchcock. The boring version that just returns the 13 multiline strings in an array is ~~132~~ 131 bytes: ``` _=>[...Array(13)].map((_,n)=>`zza zl3b k7c j9d i7e zh3f zzg`.replace(/\S/g,c=>parseInt(c,36)-n%12-10?`m`.repeat(c)||` `:`^o^`)) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~76 69~~ 58 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ⁾ mṁ11ż“椿¬®µ‘ŒḄ¤Œṙs⁴Y _4¢ḣ;“^o^”;¢ṫ⁸¤ “½œ0CSbp\I7'ð½‘Ç€Y ``` **[TryItOnline](http://jelly.tryitonline.net/#code=4oG-IG3huYExMcW84oCcw6bCpMK_wqzCrsK14oCYxZLhuITCpMWS4bmZc-KBtFkKXzTCouG4ozvigJxeb17igJ07wqLhuavigbjCpArigJzCvcWTMENTYnBcSTcnw7DCveKAmMOH4oKsWQ&input=)** ### How? ``` ⁾ mṁ11ż“椿¬®µ‘ŒḄ¤Œṙs⁴Y - Link 1, make a moon (niladic) ⁾ m - literal " m" ṁ - reshape like 11 - 11 (interpreted as range(11)) -> " m m m m m " ¤ - nilad followed by links as a nilad “椿¬®µ‘ - code page indexes [22,3,11,7,8,9] ŒḄ - bounce -> [22,3,11,7,8,9,8,7,11,3,22] ż - zip -> [[22,' '],[3,'m'],[11,' '],...] Œṙ - run length decode -> " mmm mmmmmmm mmmmmmmmm mmmmmmm mmm " s - split into chunks of length ⁴ - l6 Y - join with line feeds _4¢ḣ;“^o^”;¢ṫ⁸¤ - Link 2, a moon with a bat placed: endIndex _4 - subtract 4 (startIndex) ¢ - call last link (1) as a nilad ḣ - ḣead to startIndex ; - concatenate “^o^” - literal "^o^" ; - concatenate ¤ - nilad followed by links as a nilad ¢ - call last link (1) as a nilad ṫ⁸ - tail from endIndex “½œ0CSbp\I7'ð½‘Ç€Y - Main link (niladic) “½œ0CSbp\I7'𽑠- code page indexes [10,30,48,67,83,98,112,92,73,55,39,24,10] - indices to the right of each bat in a constructed moon Ç€ - call last link (2) as a monad for each Y - join on line feeds ``` [Answer] # Python 2, ~~146 144~~ 138 bytes -2 bytes thanks to @Willem (use the variable `c` rather than looping through a `map`) ``` m='\n'.join(int(a)*' '+int(b)*'m'+3*' 'for a,b in zip('6643466','0379730')) for b in" -;L[hrbQ@2' ":c=ord(b)-23;print(m[:c-3]+'^o^'+m[c:]) ``` **[repl.it](https://repl.it/Dyla/2)** `'6643466'` is the number of spaces before the moon (with 6 on the empty first and last lines, since the bat will go there). `'0379730'` is the number of `'m'`s in the moon on each line. The `zip` unpacks these characters into `a` and `b` and makes the moon in the sky, `m`, with 3 trailing spaces on each line. The last line then traverses the positions of the bat within the moon, and is effectively: ``` for c in(9,22,36,53,68,81,91,75,58,41,27,16,9):print(m[:c-3]+'^o^'+m[c:]) ``` but the tuple of positions is encoded as the ordinals of printable characters, with an added 23 (since 9 is not printable). This comes out as `" -;L[hrbQ@2' "`, and `c=ord(b)-23` is used to extract the values. [Answer] # Brainfuck, 690 Bytes This is my first time golfing, so I'm sure there's still plenty of room for improvement ``` -[-[-<]>>+<]>-<<+++[>+++++++<-]>>>+>>-[<-->-------]<->++++++++>+>+++++>+>+++++>+>+++++++>+>+++++>+>+++++>+>++++++++>+>+>+>>+++[<++++++>-]<+>+>-->+>+>+[<]>[[<+>>-[>]+[[<]>+[>]<+[<]>>>-]<<[->>+<<]>-]>-[->>>>+<<<<]>++]>>>[[-]<]>>>>[>]>>+>+++++++<<<<[<]+<+<<+[[<]++++[>++++<-]>[<+[>]>[-<+>]<[<]>>-]>[>]++++++++++[>]>>>-[<]<<[<]<]<[<]>->-<<<[-]++++++<+<+++[>++++++<-]+<++++[>++++++++<-]---<-[>+<-----]++<----[>+<----]--<-[>+<---]<-[>++<-----]++++<-[>+<---]++<-[>+<-------]---<----[>+<----]<--[>+<++++++]<+++++[>+++++<-]++++++>[[[>]>[>]>>[-<<+>>]<<[<]<[<]>-]>[>]>[>]+++++++[>+++++++++<-]>-[->+>+>+<<<]++++[>>++++<<-]>>+<<<<[<]>[.>]>>[.>]<[<]>[-]>[-]>[-]<+[--<---[->]<]<[->+>+>+<<<]<<[[->>+<<]<]<] ``` [Try it online](http://brainfuck.tryitonline.net/#code=LVstWy08XT4-KzxdPi08PCsrK1s-KysrKysrKzwtXT4-Pis-Pi1bPC0tPi0tLS0tLS1dPC0-KysrKysrKys-Kz4rKysrKz4rPisrKysrPis-KysrKysrKz4rPisrKysrPis-KysrKys-Kz4rKysrKysrKz4rPis-Kz4-KysrWzwrKysrKys-LV08Kz4rPi0tPis-Kz4rWzxdWzxdPltbPCs-Pi1bPl0rW1s8XT4rWz5dPCtbPF0-Pj4tXTw8Wy0-Pis8PF0-LV0-LVstPj4-Pis8PDw8XT4rK10-Pj5bWy1dPF0-Pj4-Wz5dPj4rPisrKysrKys8PDw8WzxdKzwrPDwrW1s8XSsrKytbPisrKys8LV0-WzwrWz5dPlstPCs-XTxbPF0-Pi1dPls-XSsrKysrKysrKytbPl0-Pj4tWzxdPDxbPF08XTxbPF0-LT4tPDw8Wy1dKysrKysrPCs8KysrWz4rKysrKys8LV0rPCsrKytbPisrKysrKysrPC1dLS0tPC1bPis8LS0tLS1dKys8LS0tLVs-KzwtLS0tXS0tPC1bPis8LS0tXTwtWz4rKzwtLS0tLV0rKysrPC1bPis8LS0tXSsrPC1bPis8LS0tLS0tLV0tLS08LS0tLVs-KzwtLS0tXTwtLVs-KzwrKysrKytdPCsrKysrWz4rKysrKzwtXSsrKysrKz5bW1s-XT5bPl0-PlstPDwrPj5dPDxbPF08WzxdPi1dPls-XT5bPl0rKysrKysrWz4rKysrKysrKys8LV0-LVstPis-Kz4rPDw8XSsrKytbPj4rKysrPDwtXT4-Kzw8PDxbPF0-Wy4-XT4-Wy4-XTxbPF0-Wy1dPlstXT5bLV08K1stLTwtLS1bLT5dPF08Wy0-Kz4rPis8PDxdPDxbWy0-Pis8PF08XTxd&input=) Ungolfed some for readability: ``` -[-[-<]>>+<]>-<<+++[>+++++++<-]>>>+>>-[<-->-------]<->++++++++>+>+++++>+>+++++>+>+++++++>+>+++++>+>+++++>+>++++++++>+>+>+>>+++[<++++++>-]<+>+>-->+>+>+ Sets counters for creation of the m's and spaces [<]>[[<+>>-[>]+[[<]>+[>]<+[<]>>>-]<<[->>+<<]>-]>-[->>>>+<<<<]>++] Adds the first counter plus two of the character at the second counter to the end of the current set of cells removes the first two counters on the list then repeats until it encounters a 254 >>>[[-]<]>>>>[>]>>+>+++++++<<<<[<] Removes some excess cells then adds a 7 after the end of the set of cells +<+<<+[[<]++++[>++++<-]>[<+[>]>[-<+>]<[<]>>-]>[>]++++++++++[>]>>>-[<]<<[<]<] Adds a newline every 16 characters until 7 newlines are added <[<]>->-<<<[-]++++++<+<+++[>++++++<-]+<++++[>++++++++<-]---<-[>+<-----]++<----[>+<----]--<-[>+<---]<-[>++<-----]++++<-[>+<---]++<-[>+<-------]---<----[>+<----]<--[>+<++++++]<+++++[>+++++<-]++++++ Removes some excess cells then sets indices for the locations of bats >[[[>]>[>]>>[-<<+>>]<<[<]<[<]>-]>[>]>[>]+++++++[>+++++++++<-]>-[->+>+>+<<<]++++[>>++++<<-]>>+<<<<[<]>[.>]>>[.>]<[<]>[-]>[-]>[-]<+[--<---[->]<]<[->+>+>+<<<]<<[[->>+<<]<]<] Loops through the indices replacing the spaces at each index with a bat then printing the set of cells then changing the bat back to spaces ``` I wanted to use the fact that by adding a newline to the beginning, each stage can be read in both directions to get two different stages, but I couldn't find a good way to do so without generating the full six and a half stages at once. [Answer] # [Autovim](https://github.com/christianrondeau/autovim), ~~85~~ 81 bytes No animation, probably still golfable... Still, not bad for the new kid on the block! (autovim) ``` ñ9am␛ÿP2xÿP4xyjGpđp2o %ce 15 ®q=8j$p ®z=6␍"_d3hP ñğyG12PğÿPC^o^␛v^y6@q==o␛6@z==O ``` To run it: ``` autovim run ascii-bat.autovim -ni ``` ## Explanation In short, we draw the moon, copy and paste it 12 times, and use two macros: one to append the bat on the first 7 moons, the other to prepend the last 6. ``` " Draw the moon ñ " Normal mode 9am␛ " Write 9 `m` ÿP " Duplicate the line 2x " Delete two characters ÿP " Duplicate the line 4x " Delete 4 characters yj " Yank two lines Gp " Paste at the end of the file đp " inverts the current line with the previous 2o " Add two line breaks %ce 15 " Center our moon " Macros ®q=8j$p " Macro `q` jumps 8 lines, and pastes " at the end ®z=6␍"_d3hP " Macro `z` jumps 6 lines and replaces " the previous 3 characters by the default " Draw all 12 moons and add the bats " register's content ñ " Run in normal mode ğyG " Copy the moon we just drew 12P " Duplicate the moon 12 times ğÿP " Duplicate the top line (gets 3 centered `m`) C^o^␛ " Change the mmm by a bat v^y " Copy the bat we just drew 6@q " Add the first 6 bats == " Center the bat o␛ " Add a line under the bat 6@z " Add the 6 last bats == " Align the last bat in the center O " Add a line over the last moon ``` [Answer] ## PHP, 167 bytes I made a small program in PHP: ``` <?php foreach([0,3,7,9,7,3,0]as$l)$b.=str_pad(str_repeat('=',$l),15," ",2)."\n";foreach([6,25,43,60,75,89,102,83,65,48,33,19,6]as$x)echo substr_replace($b,'^o^',$x,3); ``` Here is a more verbose version: ``` // width of the moon $moonsizes = [0,3,7,9,7,3,0]; // position where to place the bat $positions = [6,25,43,60,75,89,102,83,65,48,33,19,6]; // prepare base moon painting foreach($moonsizes as $size){ $basepainting .= str_pad(str_repeat('=',$size),15," ",STR_PAD_BOTH)."\n"; } // loop frames and place bat foreach($positions as $position) { echo substr_replace($basepainting,'^o^',$position,3); } ``` This is my first codegolf, if you have any suggestion i'm happy to hear :) [Answer] ## Python 2, 112 bytes ``` b=[' ','^o^'] for k in range(91):r=k%7;print(b[k/7+r==12]*(r%6>0)+(r*(6-r)*8/5-5)*'m'+b[k/7%12==r]).center(15) ``` Print the picture. Each line has three parts * A potential bat on the left * Some number of `m`'s for the moon * A potential bat on the right These parts are concatenated and centered in a box of size 15 for spacing. To avoid the bats shifting the center, a missing bat is three spaces, the same length. For bats on top of or below the moon, the left bar slot is omitted and the right slot is occupied. There are 91 lines: a 7-line picture for each of 13 pictures. These are counted up via divmod: As `k` counts from `0` to `91`, `(k/7, k%7)` goes ``` (0, 0) (0, 1) (0, 2) (0, 3) (0, 4) (0, 5) (0, 6) (1, 0) (1, 1) .... (12, 5) (12, 6) ``` Taking the first value `k/7` to be the picture and the second value `r=k%7` as the row number within the picture, this counts up first by picture, then by row number within each picture, both 0-indexed. The number of `m`'s in the moon changes with row number `r=k%7` as `[0,3,7,9,7,3,0]`. Rather than indexing into this, a formula was shorter. A convenient degree of freedom is that the `0`'s can be any negative value, as this still gives the empty string when multiplied by `m`. Fiddling with a parabola and floor-dividing gave a formula `r*(6-r)*8/5-5`. Now, we look at selecting whether to draw a bat or empty space on either side. The array `b=[' ','^o^']` contains the options. The bat in row 0 on in picture 0 (on top), in row 1 in picture 1 (on the right), on to in row 6 in picture 6 (on top). So, it's easy to check whether it appears as the row and picture number as being equal, `k/7==r`. But we also need picture 12 to look like picture 0, so we take the picture number modulo 12 first. On the left it's similar. The bat appears on the left in rows `r=5,4,3,2,1` in pictures `7,8,9,10,11`. So, we check whether the row and picture number sum to 12. We also make sure to draw nothing rather than three spaces on rows `0` and `6` -- the right bat slot will draw the bat, and we must not mess up its centering. [Answer] ## C#, ~~615~~ ~~582~~ 337 bytes This is my first (still far too readable) attempt at one of these, so I'll gladly welcome any suggestions to shave off a few hundred bytes! Top of my list right now is a shorter way to create the moon array. ``` void M(){string[]m={""," mmm"," mmmmmmm"," mmmmmmmmm"," mmmmmmm"," mmm",""};var b="^o^";for(int x=0;x<13;x++){var a=(string[])m.Clone();int n=x>6?12-x:x;int[] j={0,1,3,6};a[n]=!a[n].Contains("m")?" "+b:x<=n?a[n]+b:new string(' ',j[Math.Abs(9-x)])+b+a[n].Replace(" ","");foreach(var c in a){Console.WriteLine(c);}}} ``` Ungolfed (includes loop!) ``` class Program { public static string[] moon = new string[] { " ", " mmm ", " mmmmmmm ", " mmmmmmmmm ", " mmmmmmm ", " mmm ", " " }; public static string bat = "^o^"; static void Main(string[] args) { while (true) { Fly(); } } static void Fly() { int times = (moon.Length * 2) - 1; for (int x = 0; x < times; x++) { string[] temp = (string[])moon.Clone(); //create a new array to maintain the original int index = x >= moon.Length ? times - x - 1 : x; if (!temp[index].Contains("m")) { temp[index] = new string(' ', 6) + bat + new string(' ', 6); } else if (x <= index) { int lastM = temp[index].LastIndexOf('m') + 1; temp[index] = temp[index].Insert(lastM, bat); } else { int firstM = temp[index].IndexOf('m'); char[] src = temp[index].ToCharArray(); int i = firstM - bat.Length; src[i] = bat[0]; src[i + 1] = bat[1]; src[i + 2] = bat[2]; temp[index] = new string(src); } for (int y = 0; y < temp.Length; y++) { Console.WriteLine(temp[y]); } Thread.Sleep(100); Console.Clear(); } } } ``` Edit: Took out 21 bytes by removing trailing spaces in the array declaration. Instead of a grid 15 characters wide, each row is only wide enough for the bat to fit. Removed another 12 for the unnecessary string[]args in `Main()` declaration. Edit 2: Rewrote most of the logic, taking out 245 bytes! Includes suggested changes from the comments. Thanks! From the comments, turned this into a function `M()` instead of the previous `Main()` method - so now, this needs to be called externally. [Answer] # Python 2, ~~299~~ ~~300~~ ~~290~~ 270 bytes Golfed down to 270 having gained a bit more golfing experience. Reference implementation golfed down by ~~321~~ ~~320~~ 330 bytes. Not pretty or elegant. Just uses brute force string and list slicing. Was fun to get the byte count down though but I think the approach was completely wrong to start with for a serious competitor. I don't expect this answer to be taken seriously so please no downvotes. I did say in the question that I would try to golf the reference implementation and this is exactly that. Just posted for fun. ``` c,e,n=' ','m','\n';f,g=c*9+e*3+c*9,c*7+e*7+c*7;h=9,12;i=12,15;j=6,9;k=13,17;l=4,7;m=c*21,f,g,c*6+e*9+c*6,g,f,c*21;p=h,i,k,(15,18),k,i,h,j,l,(3,6),l,j,h;w=0 for z in map(int,'0123456543210'):print n.join(m[:z])+n+m[z][:p[w][0]]+'^o^'+m[z][p[w][1]:]+n+n.join(m[z+1:]);w+=1 ``` [Try it online!](https://tio.run/nexus/python2#PYxRa4QwEITf@yt8izFDcY3GasgvsTkoctZ4lyjHgeCf97Yt9GGZ2dn95hxxRXIiExCR5zMJO@HbjUWnroVWrBiLln3LvrWz60CVDY4qUGMXZ9DZmyMNau3d1WhtZLgicAuThsmOScPbhJ@D3dyMgBtyakAfkl3AjAV35BpGsi6Y7e7Kt2l9ZEcWUha/tjykJ0RJla4b09S6olLIfntwnKX3ZQ0pj0N/eKmSisPhh34bdj@U3itxWS/iL/zNyPeev/6pQ1Hvpd2Vo/N8AQ "Python 2 – TIO Nexus") [Answer] ## Ruby, ~~164~~ 156 bytes ``` puts Zlib.inflate Base64.decode64 "eNqlkrUVAAEMQvtMcZP9DfLYvzo3qhNSxQ2GVRC1ad29ar1JXaoHbul16Yig+p6BCKqtFBFU+1IE1famoHrX/jZBvN8e8f5tiE94Ib4SBREwNKH5BNJy2QM=" ``` Very simple program. Can be worked on more. Please leave tips in the comments. [Answer] # [///](//esolangs.org/wiki////), 205 bytes ``` /*/\/\///B/^o^*9/ *M/mmm*N/MM*O/ *0/OO*n/ *1/O Nm0 *2/NM0 *3/0M9*4/1O2*7/13n*5/34/0B9570MB0 473O NmBO O2731ONMBO 75O NmBO 3n510MB0n 5130B9n51OBM9n5 BNm0 3n31B273 BNm0 O27OBM9470B90M0O 410MO ``` [Try it online!](//slashes.tryitonline.net#code=LyovXC9cLy8vQi9eb14qOS8gICAgICAgICAKKk0vbW1tKk4vTU0qTy8gICAqMC9PTypuLwoKKjEvTyBObTAKKjIvTk0wCiozLzBNOSo0LzFPMio3LzEzbio1LzM0LzBCOTU3ME1CMAo0NzNPIE5tQk8gCk8yNzMxT05NQk8KNzVPIE5tQk8gCjNuNTEwTUIwbgo1MTMwQjluNTFPQk05bjUgQk5tMCAKM24zMUIyNzMgQk5tMCAKTzI3T0JNOTQ3MEI5ME0wTwo0MTBNTw) Only if I didn't need tons of trailing spaces... [Answer] # Mumps, 223 Bytes This is using InterSystems Cache Mumps -- it allows braces around loops which make it handy for nested loops in a single line. ``` S X="09121415141209060403040609",R="097679",L="037973",S=-14 F Y=1:1:13 S S=S+2 F C=1:1:7 S F=$E(X,Y*2-1,Y*2),(M,T)="",$P(T," ",21)="" F A=1:1:$E(L,C){S M=M_"m"} S $E(T,$E(R,C))=M S:C=$S(Y<8:Y,1:Y-S) $E(T,F,F+2)="^o^" W T,! ``` Could probably be golfed more, and I may play with that when I have more time. Add another 9 bytes, and it'll be animated [[ due to the addition of the 'H 1 W # ' --> that halts for a second and clears the screen: ``` S X="09121415141209060403040609",R="097679",L="037973",S=-14 F Y=1:1:13 S S=S+2 H 1 W # F C=1:1:7 S F=$E(X,Y*2-1,Y*2),(M,T)="",$P(T," ",21)="" F A=1:1:$E(L,C){S M=M_"m"} S $E(T,$E(R,C))=M S:C=$S(Y<8:Y,1:Y-S) $E(T,F,F+2)="^o^" W T,! ``` Here's an ungolfed / explained version (of the animation version), with the correct 'do' statements and dot loops: ``` S X="09121415141209060403040609" S R="097679",L="037973",S=-14 ; Initialize Variablex F Y=1:1:13 D ; Set up our main loop of 13 cels . S S=S+2 ; set up secondary counter, for start char. . H 1 ; halt for 1 second . W # ; clear screen . F C=1:1:7 D ; set up our per-line loop . . S F=$E(X,Y*2-1,Y*2) ; set F to 2-digit "start of bat" . . S (M,T)="" ; set our "builder" lines to empty strings . . S $P(T," ",21)="" ; then reset our main 'line string' to 21 spaces. . . F A=1:1:$E(L,C){S M=M_"m"} ; make our 'moon' text. . . S $E(T,$E(R,C))=M ; and insert our 'moon' into the empty line . . S:C=$S(Y<8:Y,1:Y-S) $E(T,F,F+2)="^o^" ; find the start character for our 'bat' and insert. . . W T,! ; and write the line and a CR/LF. ``` I tried to do the "compress then Base-64 encode" jazz just to see what would happen, but the encoded string ended up a little longer than the program itself! That, and Cache's system calls for the compression and base64 encoding are quite long... for example, here's the system call to decode base64: *$System.Encryption.Base64Decode(STRING)* That method would 'bloat' the program to over 300 characters, I think... ]
[Question] [ Recamán's sequence ([A005132](http://oeis.org/A005132)) is a mathematical sequence, defined as such: ``` A(0) = 0 A(n) = A(n-1) - n if A(n-1) - n > 0 and is new, else A(n) = A(n-1) + n ``` A pretty LaTex version of the above (might be more readable): $$A(n) = \begin{cases}0 & \textrm{if } n = 0 \\ A(n-1) - n & \textrm{if } A(n-1) - n \textrm{ is positive and not already in the sequence} \\ % Seems more readable than %A(n-1) - n & \textrm{if } A(n-1) > n \wedge \not\exists m < n: A(m) = A(n-1)-n \\ A(n-1) + n & \textrm{otherwise} \end{cases}$$ The first few terms are `0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11` To clarify, `is new` means whether the number is already in the sequence. Given an integer `n`, via function argument or STDIN, return the first `n` terms of the Recamán sequence. --- This is a code-golf challenge, so **shortest code wins.** [Answer] # CJam, ~~34~~ 33 bytes ``` 0ali{_W=_I-__0<4$@#)|@I+@?+}fI1>` ``` [Try it online.](http://cjam.aditsu.net/) ### Example run ``` $ cjam <(echo '0ali{_W=_I-__0<4$@#)|@I+@?+}fI1>`') <<< 33 [0 1 3 6 2 7 13 20 12 21 11 22 10 23 9 24 8 25 43 62 42 63 41 18 42 17 43 16 44 15 45 14 46] ``` ### How it works ``` 0ali " Push S := [ 0 ] and read an integer N from STDIN. "; { }fI " For each I in [ 0 ... (N - 1) ]: "; _W= " X := S[-1]. "; _I- " Y := X - I "; _0< " A := (Y < 0) "; _ 4$@#) " B := (Y ∊ S) "; @I+ " Z := X + I "; | @? " C := (A || B) ? Z : Y "; + " S += [C] "; 1>` " Push str(S[1:]). "; ``` [Answer] # Hexagony, 212 bytes ``` ?\..$@.=.'">'_<>}/..&\_.._!\.\].\"&"&=(<_...>\[.+.<_$|_...{.|.....}'.../<..|&.....'/..".>$/{.<\.\$\>\._?...><?$$.\[._\_}$&..~.|"$\./..{&_$....$'.|_...$}|_.-..;_....'}".'...2.....$?&....3..=.<_.....?.-+{......}\</$.} ``` [Try it online!](https://tio.run/##JY5NCgIxDIXPYgmtIH4DCm7stN7DSHAhutKtMlOvPrY1i4QX3t/j9r7eX8/PsmQFOTESXAoWUxnAq4GtlAvqvPPjOtYH6cyGaDI3MDHTpoS6hgiz7zhUvSPJMBEVFU2K5aaOWYQzplakcr/MTpRKn7xJk0qgW0upZwtH64bF0TJ23V5yj9lTG/dSkNluJv5lNA5CWZbDDw) **Input:** a single, positive integer \$n\$ on `stdin`. **Output:** all terms of Recaman's sequence up to and including \$A(n)\$, separated by spaces (note that this means the program will print a total of \$n + 1\$ terms). # Expanded [![expanded](https://i.stack.imgur.com/blpJp.png)](https://i.stack.imgur.com/blpJp.png) # Explanation Apologies if this is confusing, but it's my first time with Hexagony, so rest assured that it confuses me too. Let \$n = 6\$. The instruction pointer (IP) starts out in the NW corner, moving along the black path. `?` reads \$n\$ from `stdin` and stores it in the current memory edge. Next, we copy \$n\$ three times while backing up the memory pointer. We also flip the memory pointer and decrement the edge it points to. ``` "&"&"&=( ``` The IP eventually wraps around to the upper left corner again, jumping over `\` and looping through the rest of the black path. This loop continues until the current edge is 0, at which point the graph looks like so: [![initialized](https://i.stack.imgur.com/EhxL7.png)](https://i.stack.imgur.com/EhxL7.png) This forms the skeleton of our memory layout. Each `vertical` edge now stores a value \$i\$ from 0 to 6; later, these same edges will store the terms \$A(i)\$ of the sequence as they are computed. Each `vertical` edge also has 4 contiguous edges that are used for later computations. Let's explain them now: * `head` is used for several purposes, but never to store anything permanently because it is frequently overwritten by other operations. * `tail` is generally used as a temporary variable, but it remains 0 for the last \$i\$ in the sequence, telling the program when to stop. * `prev` stores the value of \$A(i - 1)\$ * `copy` straightforwardly stores a copy of \$i\$ or, later, \$A(i)\$ Once the program is done initializing its memory graph, it branches off the black path and onto the red path near the NE corner. First, `!` prints the decimal representation of `vertical` to `stdout`. Next, we move the memory pointer to `tail` and test for zero: ``` '< ``` If it is zero, `@` terminates the program immediately; otherwise, we move to `head` and set it to 32 (an ASCII space): ``` }=}?32 ``` [![space](https://i.stack.imgur.com/WVgxC.png)](https://i.stack.imgur.com/WVgxC.png) `;` then prints this space to `stdout`. Finally, we copy `vertical` to the next `prev`: ``` "?&"& ``` [![cvp](https://i.stack.imgur.com/Bn2Jp.png)](https://i.stack.imgur.com/Bn2Jp.png) Now that the memory pointer is on the next term, we copy this term's `vertical` to *its* `copy` before moving to *its* `vertical`: ``` '&{= ``` [![cvc](https://i.stack.imgur.com/pNolo.png)](https://i.stack.imgur.com/pNolo.png) `-` computes `prev` - `copy`, which is really \$A(i - 1) - i\$, and stores it in `vertical`: [![subtraction](https://i.stack.imgur.com/Kr92R.png)](https://i.stack.imgur.com/Kr92R.png) If `vertical` is not positive, `<` deflects the IP onto the green path, where `+` instead computes `prev` + `copy` (\$A(i - 1) + i\$) and stores it in `vertical`: [![addition](https://i.stack.imgur.com/x0oiu.png)](https://i.stack.imgur.com/x0oiu.png) The IP then wraps around to the SW corner, eventually returning to the beginning of the red path and starting the cycle over again. However, if `vertical` is positive, we have to make sure it doesn't already exist in the sequence before printing it. In this case, the `<` in the SE corner branches to the SE, wrapping around and staying on the red path. First, we copy `vertical` to `head`: ``` "?& ``` This puts the memory pointer in a position so that successive loops can enter at the next `|` mirror. Next, we copy `head` to the previous term's `tail` and move to *its* `head`. ``` "?&' ``` `-` computes `vertical` - `tail` (\$A(i - 1) - A(i)\$) and stores it in `head`. Hexagony treats zero as a negative number, so we have to do some convoluted branching to test if `head` is exactly zero. All that's necessary to know is that if `head` is zero, we've found a duplicate term, and the program will branch onto the yellow path. Otherwise, it will return to the red path at the `{` instruction. If `head` is zero, we return to the latest term of the sequence with `[`, which executes the subroutine along the pink and blue paths, before `+` computes \$A(i - 1) + i\$) like above. We then return to the red path. If `head` is not zero, we check if the current term is zero: ``` {< ``` If it is, we call the subroutine and go back to the red path through a convoluted series of mirrors. If it isn't, we move to compare the next term, returning to the aforementioned `|` mirror. --- Images created using Timwi's [Hexagony Colorer](https://github.com/Timwi/HexagonyColorer) and [Esoteric IDE](https://github.com/Timwi/EsotericIDE). [Answer] ## Ruby, ~~71~~ 70 bytes ``` f=->n{a=[0];(n-1).times{|i|a+=[[b=a[-1]-i-1]-a!=[]&&b>0?b:b+2*i+2]};a} ``` A very "word-for-word" implementation of the definition. [Answer] # Haskell, 74 ``` l=0:0#1 a§v|a<0||a`elem`r v=v|1<2=0-v a#b=a+(a-b)§b:l!!b#(b+1) r=(`take`l) ``` Example usage: ``` λ> r 20 [0,1,3,6,2,7,13,20,12,21,11,22,10,23,9,24,8,25,43,62] ``` [Answer] ## Python 2, ~~78~~ ~~75~~ ~~73~~ 69 Bytes Kudos to xnor and flornquake Now almost 10 bytes shorter than the initial answer ``` m=p,=0, exec"p+=1;k=m[-1]-p;m+=k+2*p*(k*(k>0)in m),;"*input() print m ``` [Answer] # Golfscript (41 ~~45~~) Try it [online here](http://golfscript.apphb.com/?c=OzEwMAooLDEsXHs6fjEkPX4pLTpeMTxcLl4%2FKSEhQHxeXHt%2BKTIqK30qK30vYA%3D%3D): ``` (,1,\{:~1$=~)-:^1<\.^?)!!@|^\{~)2*+}*+}/ ``` ## Explanation This is for the original 45 bytes solution, but it's still pretty much the same: ``` (, # push array [0 .. n-1] [0]\ # push sequence elements as [0] and reverse stack { # foreach element in [0 .. n-1] do: :m; # store current element in m and discard .m= # get the previous sequence element m)-:^ # subtract the current index from it and store in ^ 0> # is that number greater than 0? \.^?)! # is that number new to our sequence? @& # logically and both checks {^} # if true, push ^ {^m)2*+} # otherwise, add the index twice and push if + # add new element to our sequence }/ ` # make output pretty ``` *Edit #1:* Thanks to Dennis for shaving off 4 bytes. [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 46 bytes ``` sn[z+z+d0r:a]sF0[pz-d1>Fd;a0<Fddd:azln!<M]dsMx ``` [Try it online!](https://tio.run/##S0n@b2rwvzgvukq7SjvFoMgqMbbYzSC6oEo3xdDOLcU60cDGLSUlxSqxKidP0cY3NqXYt@L/fwA "dc – Try It Online") This program takes input from an otherwise empty stack and outputs to stdout (newline delimited). I'm really proud of this one - it's beating everything that isn't a dedicated golfing language, and showcases three of my favorite dc golfing tricks: * Stack size used as an index variable * Refactoring "if A then B else C" into "unconditionally C, and if A then D" where C and D combine to make B * the little-used random access array feature to solve a uniqueness constraint # Explanation ``` sn Stores the input in register n [z+z+0r:a]sF Defines the macro F, which: z+z+ adds twice the stack size/index variable 0r:a resets the "uniqueness" flag to 0 in the array a In context, F is the "D" in my description above, changing A(z-1)-z to A(z-1)+z 0 The main loop starts with the previous sequence member on top of the stack and total stack depth equal to the next index. Pushing a zero accomplishes both of these things. [ Start of the main loop M p Print the previous sequence member, with newline (no pop) z- Calculate A(z-1)-z d1>F If that's nonpositive, (F)ix it to be A(z-1)+z d;a a is my array of flags to see if we've hit this value before 0<F If we have, (F)ix it! (nonzero = flag, since ;a is zero by default, and also zero if we just (F)ixed and therefore don't care about uniqueness right now) ddd Make one copy to keep and two to eat :a Flag this entry as "used" in the uniqueness array a zln!<M If our "index variable" is n or less, repeat! ]dsMx End of main loop - store it and execute ``` [Answer] ## JavaScript - ~~81 80 79~~ 70 Kudos to edc65 for helping me save 9 bytes ``` f=n=>{for(a=[x=i=0];++i<n;)a[i]=x+=x>i&a.indexOf(x-i)<0?-i:i;return a} ``` [Answer] ## JavaScript, ES6, ~~74~~ 69 characters Run the below code in latest Firefox's Web Console. ``` G=n=>(i=>{for(r=[t=0];++i<n;)r[i]=t+=i>t|~r.indexOf(t-i)?i:-i})(0)||r ``` Will try to golf it more later. Example usage: ``` G(11) -> 0,1,3,6,2,7,13,20,12,21,11 ``` [Answer] # MATLAB, ~~83~~ 78 Bytes Save the below as `f.m` (73 Bytes) ``` A=0;for i=1:n-1 b=A(i)-i;A(i+1)=b+2*i;if b>0&&~any(A==b) A(i+1)=b;end;end ``` Run from command window (5 bytes) ``` n=9;f ``` If the above is not legal, then it requires 90 bytes. ``` function A=f(n) A=0;for i=1:n-1 b=A(i)-i;A(i+1)=b+2*i;if b>0&&~any(A==b) A(i+1)=b;end;end ``` [Answer] # R: 96 characters Golfed: ``` A=function(s,n,m,i){if(m==n){return(s)}else{t=i-m;if(t%in%s||t<0){t=i+m};s=c(s,t);A(s,n,m+1,t)}} ``` Ungolfed: ``` A = function(s,n,m,i) { if(m==n){return(s)} else{ t=i-m if(t%in%s||t<0){t=i+m} s=c(s,t) A(s,n,m+1,t) } } ``` Sample Run: ``` > An(0,34,1) [1] 0 1 3 6 2 7 13 20 12 21 11 22 10 23 9 24 8 [18] 25 43 62 42 63 41 18 42 17 43 16 44 15 45 14 46 79 ``` [Answer] # JavaScript, 63 bytes ``` n=>(g=y=>n-x?g(a[++x]=a.includes(z=y-x)|z<0?+y+x:z):a)(a=[x=0]) ``` [Try it online](https://tio.run/##BcFtCoMwDADQ6yR0DTLYH1mUnUNlBr@ouFR0G23Z3bv3VvnKORxuf1v145RnzsoVLBy5UhvqBaQxJnQs5HTYPuN0QuJoA/7SvahNNKFMWAqCcBO46DAPXk@/TbT5BRoiehyHRLjesKOX7ADPi0OuZnCItHqnfas95j8) [Answer] # [Perl 6](http://perl6.org/), ~~62~~ 57 bytes ~~{(0,{$*-@*+@*\*2\*($*!>@*||$*-@*∈@*)given @*[\*-1]}...\*)[^$*]}~~ ``` {(0,{($!=@_[*-1])+@_-@_*2*($!>@_&&$!-@_∉@_)}...*)[^$_]} ``` *-5 bytes thanks to Jo King* [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WsNAp1pDRdHWIT5aS9cwVlPbIV7XIV7LSAsoaOcQr6amogjkP@rodIjXrNXT09PSjI5TiY@t/V@cWKmQpmFqoPkfAA "Perl 6 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 19 bytes ``` ¾ˆG¯¤N-DŠD0›*åN·*+ˆ ``` [Try it online!](https://tio.run/##ASkA1v8wNWFiMWX//8K@y4ZHwq/CpE4tRMWgRDDigLoqw6VOwrcqK8uG//81MA "05AB1E – Try It Online") **Explanation** ``` ¾ˆ # Initialize the global list with 0 G # for N in [1, input-1] do: ¯ # push the global list ¤N- # subtract N from the last item in the list D # duplicate Š # move the copy down 2 spots on the stack D # duplicate again 0› # check if it is positive * # multiply, turning negative results to zero å # is the result already present in the list? N·* # multiply by N*2 + # add to the result ˆ # add this to the list ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 53 bytes **Solution:** ``` {$[y>c:#x;o[x,(r;*|x+c)(r in x)|0>r:*|x-c;y];x]}[,0;] ``` [Try it online!](https://tio.run/##y9bNz/7/v1olutIu2Uq5wjo/ukJHo8haq6ZCO1lTo0ghM0@hQrPGwK7ICiikm2xdGWtdEVsbrWNgbWgY@/8/AA "K (oK) – Try It Online") **Explanation:** Recursive solution. ``` {$[y>c:#x;o[x,(r;*|x+c)(r in x)|0>r:*|x-c;y];x]}[,0;] / the solution { }[,0;] / lambda with first arg set as list containing 0 $[ ; ; ] / if[condition;true;false] #x / length of x c: / save as c y> / y greater than? (ie have we produced enough results?) x / return x if we are done o[ ;y] / recurse with new x and existing y x-c / subtract c from x *| / reverse first, aka last r: / save result as r 0> / 0 greater than? | / or ( ) / do together r in x / r in x? ( ; ) / use result to index into this 2-item list x+c / add c to x *| / reverse first, aka last r / result x, / append to x ``` [Answer] # [J](http://jsoftware.com/), 36 bytes ``` (,][`(+2*#)@.(e.+.0>[)~{:-#)^:(]`0:) ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NXRioxM0tI20lDUd9DRS9bT1DOyiNeuqrXSVNeOsNGITDKw0/2typSZn5CukKRga/AcA "J – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 65 bytes ``` n=a=0 v=[] exec'a+=[n,-n][a+n in v];print a;n-=1;v+=a,n;'*input() ``` [Try it online!](https://tio.run/##BcFBCoAgEAXQvadwZ6WCtpU5ibgYQsjNT8KkTj@9179xXthFQExBTcpF1bcehi1lOI@S2UI36FlSvxuG5gRPMU1L7JDM1tCfsawiMfw "Python 2 – Try It Online") Avoids negative numbers by adding them to the list of already visited numbers. [Answer] ## Java, 144 ``` int[]f(int n){int[]a=new int[n];a[0]=0;int i,j,k,m;for(i=0;i<n-1;){k=a[i++]-i;m=0;for(j=0;j<i;)if(k==a[j++])m=1;a[i]=m<1&k>0?k:k+2*i;}return a;} ``` [Answer] ### Powershell (103) ``` $n=Read-Host;$a=@(0);$n-=1;1..$n|%{$x=$a[-1]-$_;if($x-gt0-and!($a-like$x)){$a+=$x}else{$a+=$x+2*$_}};$a ``` Another 'word-for-word' implementation down here as well. Surprisingly readable for PowerShell, too. Sequence is stored in the array $a, and printed out one term per line. For $n=20 if we run the statement `$a-join","` we get ``` 0,1,3,6,2,7,13,20,12,21,11,22,10,23,9,24,8,25,43,62 ``` [Answer] ## Lua - ~~141 135 139~~ 135 ``` function s(n)a,b={1},{[0]=0}for i=1,n do k=b[i-1]-i c=k+i+i if(k>0)and(a[k]==nil)then b[i],a[k]=k,1 else b[i],a[c]=c,1 end end return b end ``` readable version: ``` function s(n) a,b={1},{[0]=0} for i=1,n do k=b[i-1]-i c=k+i+i if (k>0) and (a[k]==nil) then b[i],a[k]=k,1 else b[i],a[c]=c,1 end end return b end ``` I use 2 tables, the first one is called *a* and it is built so that a[i]=1 iff *i* has already appeared in the sequence, *nil* otherwise, while the second table actually holds the sequence [Answer] ## Python, 73 ``` def f(x,t=0): if x:t=f(x-1);t+=2*x*(t*(t>0)in map(f,range(x))) return t ``` Edit 1: Thanks to @xnor's tips on the other Python answer! (I just realised that both look very similar.) Edit 2: Thanks again, @xnor. [Answer] ## Groovy : 122 118 111 chars Golfed: ``` m=args[0] as int a=[0] (1..m-1).each{n->b=a[n-1];x=b-n;(x>0&!(x in a))?a[n]=x:(a[n]=b+n)} a.each{print "$it "} ``` Ungolfed: ``` m = args[0] as int a = [0] (1..m-1).each { n-> b = a[n-1] x = b-n ( x>0 & !(x in a) ) ? a[n] = x : (a[n] = b+n) } a.each{print "$it "} ``` Sample Run: ``` bash$ groovy Rec.groovy 14 0 1 3 6 2 7 13 20 12 21 11 22 10 23 ``` [Answer] ## Clojure : 174 chars Golfed: ``` (defn f[m a](let[n(count a)b(last a)x(- b n)y(if(and(> x 0)(not(.contains a x)))x(+ b n))](if(= m n)a(f m(conj a y)))))(println(f(read-string(first *command-line-args*))[0])) ``` Ungolfed: ``` (defn f[m a] (let [n (count a) b (last a) x (- b n) y (if (and (> x 0) (not (.contains a x))) x (+ b n)) ] (if (= m n) a (f m (conj a y))) ) ) (println (f (read-string (first *command-line-args*)) [0]) ) ``` Sample run: ``` bash$ java -jar clojure-1.6.0.jar rec.clj 14 [0 1 3 6 2 7 13 20 12 21 11 22 10 23] ``` [Answer] # Mathcad, 54 "bytes" [![enter image description here](https://i.stack.imgur.com/bY9ZM.jpg)](https://i.stack.imgur.com/bY9ZM.jpg) --- From user perspective, Mathcad is effectively a 2D whiteboard, with expressions evaluated from left-to-right,top-to-bottom. Mathcad does not support a conventional "text" input, but instead makes use of a combination of text and special keys / toolbar / menu items to insert an expression, text, plot or component. For example, type ":" to enter the definition operator (shown on screen as ":=") or "ctl-shft-#" to enter the for loop operator (inclusive of placeholders for the iteration variable, iteration values and one body expression). What you see in the image above is exactly what appears on the user interface and as "typed" in. For golfing purposes, the "byte" count is the equivalent number of keyboard operations required to enter an expression. [Answer] # [PHP](https://php.net/), 89 bytes ``` $f=function($n){for(;$i<$n;$s[$r[$i++]=$p=$m]=1)if($s[$m=$p-$i]|0>$m)$m=$p+$i;return$r;}; ``` [Try it online!](https://tio.run/##HcjLCsIwEEbhV@nih86QCnXlYhp9kJJVTeiAuRDblfrssbo5cL6yljbdylEEG/a0bJoTIfEr5EoCnZAEzxl1hhrjLIpFdPbMGujn8ZAT1L3HKyL/10Cl@m2vCVU@0vyy5k5jeeS7p37ohw6BLiOztC8 "PHP – Try It Online") Ungolfed: ``` $f = function ($n) { for (; $i < $n; $s[$r[$i++] = $p = $m] = 1) { if ($s[$m = $p - $i] | 0 > $m) { $m = $p + $i; } } return $r; }; ``` * `$r` for my result * `$s` for tracking seens * `$p` previous value * `$m` *m*ext value [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~116 111~~ 109 bytes ``` *f(n){int*a=calloc(4,n),i=0,j,k,m;for(;~i+n;a[i]=k+(m|k<1)*2*i)for(k=a[i++]-i,m=0,j=i;j--;)m=k-a[j]?m:1;n=a;} ``` [Try it online!](https://tio.run/##JY7NDoIwEITvPsVKYtLfBIgnl8YHIRyaGsxSWwjiCfHVsdXTZL7Z2V2n787tu@hZ5CvFRVjj7OMxOnZWkSsypRqUVwH7cWb4IRnRttQZL1l4@6biohbEc@hNCqTsNKmQW4Zw0Bp5MF7bduiu4VJhNBa3Pd2BYCkyvh4AshMWDPSsqoFjQnnfj1PCJSZpoKqTSgkccglgmtNAz6BQp1shj6QgP/bvbzC9licriuS2/Qs "C (gcc) – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 19 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` É╖C8½ΔL▄░▬L+≡ΩSa⌂¼╧ ``` [Run and debug it](https://staxlang.xyz/#p=90b74338abff4cdcb0164c2bf0ea53617faccf&i=3%0A100&a=1&m=2) Unpacked, ungolfed, and commented, it looks like this. It keeps the sequence so far on the stack, and remembers `A(n - 1)` in the X register. The iteration index is used for `n`. The first time through, it's 0, but in that iteration it generates the 0 without any special cases, so there's no need to adjust for the off-by-1 index. ``` 0X push 0 to main stack and store it in X register, which will store A(n - 1) z push an empty array that will be used to store the sequence ,D pop input from input stack, execute the rest of the program that many times xi-Y push (x-register - iteration-index) and store it in the Y register this is (A(n - 1) - n) 0> test if (A(n - 1) - n) is greater than 0 (a) ny# count number of times (A(n - 1) - n) occurs in the sequence so far (b) > test if (a) > (b) y (A(n - 1) - n) xi+ A(n - 1) + n ? if/else; choose between the two values based on the condition X store the result in the X register Q print without popping + append to sequence array ``` [Run and debug this one](https://staxlang.xyz/#c=0X+++++%09push+0+to+main+stack+and+store+it+in+X+register,+which+will+store+A%28n+-+1%29%0Az++++++%09push+an+empty+array+that+will+be+used+to+store+the+sequence%0A,D+++++%09pop+input+from+input+stack,+execute+the+rest+of+the+program+that+many+times%0A++xi-Y+%09push+%28x-register+-+iteration-index%29+and+store+it+in+the+Y+register%0A+++++++%09this+is+%28A%28n+-+1%29+-+n%29%0A++0%3E+++%09test+if+%28A%28n+-+1%29+-+n%29+is+greater+than+0+%28a%29%0A++ny%23++%09count+number+of+times+%28A%28n+-+1%29+-+n%29+occurs+in+the+sequence+so+far+%28b%29%0A++%3E++++%09test+if+%28a%29+%3E+%28b%29%0A++++y++%09%28A%28n+-+1%29+-+n%29%0A++++xi%2B%09A%28n+-+1%29+%2B+n%0A++%3F++++%09if%2Felse%3B++choose+between+the+two+values+based+on+the+condition%0A++X++++%09store+the+result+in+the+X+register%0A++Q++++%09print+without+popping%0A++%2B++++%09append+to+sequence+array&i=3%0A100&a=1&m=2) [Answer] ## Pyth, 31 bytes ``` VQ=+Y?Y?|>NeYhxY-eYN+eYN-eYNZ)Y ``` [Answer] # x86 machine code, 29 bytes ``` 00000034: 89 fe 31 c0 99 eb 11 29 d0 78 0a 60 89 f7 89 d1 ..1....).x.`.... 00000044: f2 af 61 75 03 8d 04 50 ab 42 e2 eb c3 ..au...P.B... ``` Commented assembly: ``` .intel_syntax noprefix .globl recaman // input: ECX: n, EDI: u32[n] // output: stored to EDI recaman: // Save the array pointer to ESI mov esi, edi // EAX (A(n)) = 0 xor eax, eax // EDX (n) = 0 cdq // Store first word jmp .Lstore .Lloop: // A(n - 1) - n sub eax, edx // if negative, do A(n - 1) + n js .Lneg_or_dup .Lnot_neg_or_dup: // We need to save both EDI and ECX, so we do a lazy PUSHA/POPA. pusha // EDI = start of array mov edi, esi // ECX = current output length mov ecx, edx // Search for A(n - 1) - n repnz scasd // restore registers popa // If the zero flag is set, we found a match. // If not, go directly to store jnz .Lstore .Lneg_or_dup: // Convert A(n - 1) - n to A(n - 1) + n by adding n * 2 // EAX = EAX + EDX * 2 lea eax, [eax + 2 * edx] .Lstore: // Store a u32 to EDI and autoincrement stosd // Increment length inc edx // Decrement counter and loop if non zero loop .Lloop // Return ret ``` [Try it online!](https://tio.run/##dVVtT9swEP6eX3HqtCmB8NIi7UMZSAiQVglpCDQNCaHI2E4alNiZ7ZQWxF9fd3bSJKbQD0lzb7577rkzraq9jNL1l1zQomYcflBtWC5Pg3cSYd6JVC6y0yDgS8OVgNH5KFjInIHilJREJJRxWoTodjRJDOwQpWLYfBVcZGYeHQdBkhBdJkl4MwrX0P720YwXiV4JQ5YgZKV4mi@DTp0V8rHYnNOJDw4wfFWbKVye301BxHB5MZtCfTS5Fw9DK1kbZ6aNVJyBkdYwaMNNh5a3ZMHBzDlg8mQFlbSJKedxO@sMS7lwb67zGDjLhxEuz@4gPAtFFMEJHHaapVSNC1nG9uG5XKCL8O0p@@vlZTOHNFfawLNUrNM9lVUD0ZUrLti/KqSsvJowGdiDcYSPHjtdPw7yYV4@eQqCZ8TkCx4Dk32A3UGAJ9325gptE6kSVld4upAm6QVeHn84hm3g1xbmR2nmthFABLMdjEFLeOb2RAIFeVnB9e/bn2cH17@uz/a7QFWt58RHb4bIaUOUabq23SZm26T9Np3foRetleLCtATZdqTb4NxyougcUuznh8AqXokXCzAlmg0dFXcdwneWaySV7kuSlVfRLHUUfOFKQlqQDHINmpvYgpPKGtEiUBJD5/vvvBD8GDIJLEdum2LloHa06LrmchvS5ZNmnUux4IjosEYbbsgFeFwBYbgnMhA74/dDcOKeu47dOzDp1AUnPfPu8Yk2E7RAnB@CNq/pNveJnet2dB1jSG1wOqniJXaw57WRPuyzjUm7gjod@rbs8Pp7wTf2FKG2w28Ps0Pl5kIK15e@GqtwgNp/w0A33NRqyAsTDNVuWcKzIlWFZ4S10NQup@iTpdcs18D7mnpD0TJ9WzYgvjcR91xXiP148vAx8Tf6772ekqJoivE3cdWA4J3VyQY5WRC6@ogxm43f7Pt1NLIXBK5cpHcuQnu5RMFr0HSruUdwwu/Hhw/HTljyEucidBfN4TJNcYPkL1ymVhJFjY1/OTnT8WGrs0Pc3VffljC14SN47WvAG8@k4egri2EUw7L1ewvegvU/amdTr/fKo8l/) The input is a pointer to an `int32_t` array of `n` elements in `edi`, with `n` being in `ecx`. The output will be stored into `edi`. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~56~~ 52 bytes -2 bytes thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king)! -2 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)! ``` ->n{v,*d=0;n.times{|i|d<<v+=v<i||d!=d-[v-i]?i:-i};d} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9cur7pMRyvF1sA6T68kMze1uLomsybFxqZM27bMJrOmJkXRNkU3ukw3M9Y@00o3s9Y6pfZ/gUJatKFh7H8A "Ruby – Try It Online") **Commented**: ``` ->n{ ... } # lambda function taking an integer v,*d=0 # initialize list of sequence values d and previous value v n.times{|i| ... } # run the following code for i = 0,1,...,n-1: v<i||d!=d-[v-i]?i:-i # i IF (v < i OR d != (d without v-i)) ELSE -i v+= # add this to v d<< # and append the new value of v to d d # return d ``` ]
[Question] [ An Egyptian fraction is a representation of a rational number using the sum of distinct unit fractions (a unit fraction is of the form \$ \frac 1 x \$ where \$ x \$ is a positive integer). For all**[1]** positive integers \$ n \ne 2 \$, there exists at least one Egyptian fraction of \$ n \$ distinct positive integers whose sum is \$ 1 \$. For example, for \$ n = 4 \$: $$ \frac 1 2 + \frac 1 4 + \frac 1 6 + \frac 1 {12} = 1 $$ Here is another possible output: $$ \frac 1 2 + \frac 1 3 + \frac 1 {10} + \frac 1 {15} = 1 $$ The number of possible outputs is given by [A006585](https://oeis.org/A006585) in the OEIS. **[1]**: I cannot find a direct proof of this, but I can find [a proven lower bound](https://mathweb.ucsd.edu/%7Eronspubs/80_11_number_theory.pdf) on A006585, which has this as an obvious consequence. If you can find (or write!) a better / more direct proof that a representation exists for all \$ n \ne 2 \$ I would love to hear it. ## Task Given \$ n \$, output a list of positive integers representing the denominators of *at least one* valid solution of length \$ n \$. You may alternatively output a list of rational numbers which are unit fractions, but only if they are an exact representation of the value (so not floating-point). ## Test cases I only list a few possible outputs. [Here is a Ruby program which can verify any solution](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWN00LSkuKNdJTS4r1igtyMks0lHQUlDT1chMLqmsyaxQMixT0FTL1SvLji2r1iktzFWxtgWKaEM1QMxbcVDOy0FEwMtFRMATShqZADGIbAbGBjoKljgJQ1FxHwQyiHAA). ``` n outputs 1 {1} 3 {2, 3, 6} 4 {2, 4, 6, 12} or {2, 3, 10, 15} or {2, 3, 9, 18} or {2, 4, 5, 20} or {2, 3, 8, 24} or {2, 3, 7, 42} or ... 5 {2, 4, 10, 12, 15} or {2, 4, 9, 12, 18} or {3, 4, 5, 6, 20} or {2, 5, 6, 12, 20} or {2, 4, 8, 12, 24} or {2, 4, 7, 14, 28} or ... 8 {4, 5, 6, 9, 10, 15, 18, 20} or {3, 5, 9, 10, 12, 15, 18, 20} or {3, 6, 8, 9, 10, 15, 18, 24} or {4, 5, 6, 8, 10, 15, 20, 24} or {3, 5, 8, 10, 12, 15, 20, 24} or {4, 5, 6, 8, 9, 18, 20, 24} or ... 15 {6, 8, 9, 11, 14, 15, 18, 20, 21, 22, 24, 28, 30, 33, 35} or {7, 8, 10, 11, 12, 14, 15, 18, 20, 22, 24, 28, 30, 33, 36} or {6, 8, 10, 11, 12, 15, 18, 20, 21, 22, 24, 28, 30, 33, 36} or {6, 8, 10, 11, 12, 14, 18, 20, 21, 22, 24, 28, 33, 35, 36} or {5, 8, 11, 12, 14, 15, 18, 20, 21, 22, 24, 28, 33, 35, 36} or {5, 8, 10, 11, 14, 15, 18, 21, 22, 24, 28, 30, 33, 35, 36} or ... ``` ## Rules * You may output the numbers in any order * If you choose to output all possible solutions, or a particular subset of them, you must not output duplicates. This includes lists which are the same under some permutation. * You may assume \$ n \$ is a positive integer, and is not \$ 2 \$ * Your code does not need to practically handle very high \$ n \$, but it must work in theory for all \$ n \$ for which a solution exists * 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/), 42 bytes ``` f=lambda n,x=1:1/n*[x]or[x+1]+f(n-1,x*-~x) ``` [Try it online!](https://tio.run/##Fc29DsIgGIXh3as4DgToj/Xr2IQraTpgEMXoR0M64OKtI2wn7/Cc/Xs8I8@lePO2n5uz4CEbWmjibs1bTGvuaeu94pGG3I2/rIuPCYzASJYfd0UD6KqXE4Kv@Www1409BT4ghYOREFWFRA95ecXAStIkXMsODXMNqxdalz8 "Python 2 – Try It Online") The key thing to observe is that `1/n = 1/(n+1) + 1/(n*(n+1))`. Therefore we can always obtain a solution with `n` fractions, by using a solution with `n-1` fractions, and "splitting" the last fraction in two. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes ``` ¡ɾṗ'Ė∑1=;t ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCocm+4bmXJ8SW4oiRMT07dCIsIiIsIjMiXQ==) Bruteforcer. \$O\left(2^{n!}\right)\$ time complexity, searches for fractions with reciprocals \$ n! \$ which seems to be enough. ``` ¡ # Factorial ɾṗ # All combinations of 1...n ' ; # Filtered by... Ė∑ # Sum of reciprocals 1= # is 1? t # Get the last one ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 32 bytes Using Sylvester's sequence A000058 ``` Nest[##&[#^2+#,1+#,##2]&,1,#-1]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773y@1uCRaWVktWjnOSFtZxxCIlZWNYtV0DHWUdQ1j1f4HFGXmlTho@WQWA8l0fYdqQx1jHRMdUx2z2v//AQ "Wolfram Language (Mathematica) – Try It Online") -8 bytes from @att [Answer] # [Factor](https://factorcode.org/), 48 bytes ``` [ 1 - 2 [ 3 dupn . sq - abs 1 + ] repeat 1 - . ] ``` [Try it online!](https://tio.run/##HcoxDoJAEEbhnlP8vYEETSjgAIbGxlgRihEG2bgO6@xQyOVXQvu@N9Fgi6bHvb1da3zIZrxYWMm7jcwtEvFmFfYIyma/oE4MTZZVqUOJHGd0uGBcg6BA/O6FnnGXE3ooByY7tgJ9Gsj79Ac "Factor – Try It Online") Port of @ZaMoC's [Mathematica answer](https://codegolf.stackexchange.com/a/241226/97916). It prints the first n terms of Sylvester's sequence, subtracting 1 from the last number. The old way that doesn't quite work: ``` [ [1,b] dup 1 rotate v* ] ``` [Answer] # [R](https://www.r-project.org/), ~~44~~ 38 bytes *-6 bytes thanks to Dominic van Essen* ``` function(n)2^(1:n)*.75^(n:1<3)-(n<2)/2 ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jT9MoTsPQKk9TS8/cNE4jz8rQxlhTVyPPxkhT3@i/RoVtmoaxpiYXV3FproahfoXmfwA "R – Try It Online") ## First Attempt ``` function(n){k<-1:n;2^k*.75^(k>n-2)-(n==1)/2} ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jT7M620bX0CrP2ihOI1tTS8/cFEjb5ekaaepq5NnaGmrqG9X@16iwTdMw0dTk4iouzdUw1K/Q/A8A "R – Try It Online") Port of my Excel answer. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~70 40~~ 34 bytes ``` ->n{a=1;(2..n).map{a*=q=1+a;q}<<a} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOtHW0FrDSE8vT1MvN7GgOlHLttDWUDvRurDWxiax9n@0oY6WsZ6eoUEsWLqmoqZAIS26Irb2PwA "Ruby – Try It Online") Based on dingledooper's python answer. Some bytes saved by following Kevin Cruijssen's advice. [Answer] # [R](https://www.r-project.org/), ~~55~~ 57 bytes *Edit: Thanks to Anders Kaseorg (and +2 bytes) for bug-spotting* ``` function(n){while(n<-n-1)T=c((k=T[1]+1)*T[1],k,T[-1]);+T} ``` [Try it online!](https://tio.run/##jY1BCsIwEEX3vYabGdugs1Vzi@xKKSFMbYiOJUkpRTx7tHoBV/8/Po8fi5Wer@uU/acM0brsH9JHniInlmw31GWY5TuA4HMZ/Y1BLkoUodEOIGjTUlcT7rdsQmNaRR2ea/MqYCUtHPUfN0BHxKrauZFdOFVpvgMdfjqWNw "R – Try It Online") Outputs one egyptian fractional representation of 1 using n fractions, constructed using [ZaMoC's](https://codegolf.stackexchange.com/a/241226/95126) & [dingledooper's](https://codegolf.stackexchange.com/a/241234/95126) approach. --- # [R](https://www.r-project.org/), 102 bytes ``` function(n,m=n){while(all(F<-apply(l<-combn(1:m,n),2,function(k)sum(prod(k)/k)-prod(k))))m=m+1;l[,!F]} ``` [Try it online!](https://tio.run/##hY5BCsIwFET3vYW4@R9TSl1JNdtewKVIiTG1pclPSFJKEc8eqxS3zuoNwwzjk3rMLvaCmtYLGXtLjVfOq6Aoio/lqR3pGwAxwwmfU9drBUJrqE@5cE7PoE@5tOZGUFaGEbI9@5UGDKMB5@19wWLAfMVFhptdedQXtqmvrwSCwqQ8/3cIDohZtpWdkkOVeTudRxOgLOI6gJje "R – Try It Online") A brute-force approach that outputs the egyptian fractional representation(s) with the lowest-valued top denominator, by trying all combinations of fractions up to successively increasing denominators. [Answer] # Excel, 47 bytes ``` =LET(x,SEQUENCE(A1),0.75^(x>A1-2)*2^x-(A1=1)/2) ``` [Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJngB37bnH6DTyorgt?e=vJmlht) Uses the fact that for \$ n>2\$: $$\sum\_{k=1} ^{n-2} \left(\frac 1 {2}\right) ^ k + \frac 4 {3}\left(\left(\frac 1 {2}\right)^{n-1} + \left(\frac 1 {2}\right)^n\right) = 1$$. [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), ~~106~~ ~~105~~ 98 bytes ``` (load library (d g(q((n x)(i(e n 1)x(g(s n 1)(c(*(a(h x)1)(h x))(c(a(h x)1)(t x (d f(q((n)(g n(q(1 ``` [Try it online!](https://tio.run/##PYwxDoAgEAR7X3HlYkfjf1AELyGoQAGvP4HCamdnky0cW@D8iCDcxlLgPZnUFljyeIFIVYFxUiStKjzyJBxYYXD1tZcRQ/2iUB0Pbj4oeIqdtMDRpuQD "tinylisp – Try It Online") Not sure there's a better way to ~~get `(1)` than `(c 1()`~~ (use `(q(1`) add two elements to a list than `(c X(c Y Z)`. Ports e.g., [Dominic van Essen's R answer](https://codegolf.stackexchange.com/a/241249/67312). Thanks to DLosc for -5 bytes. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes ``` FN⊞υ⊕∨Πυ¹⊞υ⊖⊟υIυ ``` [Try it online!](https://tio.run/##RcsxDoMwDEDRnVNktKUwMDBlbBeWkiukwVUqhQSZuNc3pVLF/N@PKXCsIau@KhuYyibtIeuTGBCNlz2BWDOVyLRSabTAzOC5LhIbCFozIKLr/vBOF/R1@4pf5XdpcAv7uaBTHbX/5AM "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses a formula for Sylvester's sequence taken from A000058. ``` FN ``` Loop `n` times... ``` ⊞υ⊕∨Πυ¹ ``` ... push the incremented product of the list to the list. (Note that the version of Charcoal on TIO can't take the product of an empty list, so I have to manually replace the result with `1`.) ``` ⊞υ⊖⊟υ ``` Decrement the last element of the list. ``` Iυ ``` Output the list. 14 bytes using the newer version of Charcoal on ATO that can take the product of an empty list: ``` FN⊞υ⊕Πυ⊞υ⊖⊟υIυ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjeT0_KLFDQ88wpKS_xKc5NSizQ0NRUCSoszNEp1FDzzkotSc1PzSlJTNAKK8lNKk0s0SjU1Na25YCpcUpFU5BfAZIsy80o0nBOLwcqtlxQnJRdDLdwUraRblqOko6CkmwkiTZVioTIA "Charcoal – Attempt This Online") Link is to verbose version of code. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes ``` ⁸P‘ṭƊ¡’0¦ ``` [Try it online!](https://tio.run/##AR4A4f9qZWxsef//4oG4UOKAmOG5rcaKwqHigJkwwqb//zQ "Jelly – Try It Online") Based on the Sylvester sequence. [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), ~~156~~ ~~97~~ 91 bytes *-59 bytes remove extra spaces and use pow function* *-6 bytes thanks to @DLosc* ``` (load library (d g(q((n m)(i m(c(/(*(s 4(l(s n 2)m))(pow 2 m))4)(g n(s m 1)))( q((n)(g n n ``` [Try it online!](https://tio.run/##Hcw7CoAwEITh3lNMOWvjEzyPGpRAsj5BPH1c0/zNN8zt9Q3@2lNi2EaH4KdzPN@CDisPUhGFHpEzK5a80DNYFa1EEe7bg9Ym0gtXqElEIwb/wZIPMkATFxNYu9wht6klfQ "tinylisp – Try It Online") ## First Attempt ``` (load library (d p(q((x n)(i n(* x(p x(s n 1)))1 (d g(q((n m)(i m(c(/(*(i(l m (s n 1))4 3)(p 2 m))4)(g n(s m 1)))( (d f(q((n)(g n n ``` [Try it online!](https://tio.run/##bYyxDoMwDER3vuLGM0ubwg/RIlCkxATSAb4@dSKx1ZZvuef39XoFn1MpDNs0I/j3MR1XxxmJO3lChR7KHieTXYbCiYiryFoRRaxI5IcP9vQMiLi5EYPY38sYGYWrmbLV1cBqWJqhFbZ/pwMKF3uB5dDSPaX8AA "tinylisp – Try It Online") Porting into tinylisp. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 34 bytes ``` n->[q-(i==n)|i<-[a=1..n],a*=q=1+a] ``` [Try it online!](https://tio.run/##FcdBCoMwEAXQq3xcJe2MELStC8eLhCxmowTKMEo3Qu8e2917rkflzdsKacZL3jlUEYvfOnNWSX1vhfQmu6S7lqbu7zMYeIEf1T4/dv90WIPFSMiJMBBGwoPwJLwIU4ntAg "Pari/GP – Try It Online") A port of [@ZaMoC's Mathematica answer](https://codegolf.stackexchange.com/a/241226/9288) and [@G B's Ruby answer](https://codegolf.stackexchange.com/a/241229/9288). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` $GD>DŠ*}) ``` -4 bytes porting [*@GB*'s Ruby answer](https://codegolf.stackexchange.com/a/241229/52210). [Try it online](https://tio.run/##yy9OTMpM/f9fxd3FzuXoAq1azf//TQE) or [verify the first \$n=10\$ test cases, excluding \$2\$](https://tio.run/##yy9OTMpM/R/iY@RdVmmvpPCobZKCkv1/w0p3FzuXowu0ajX/6/wHAA). Alternative 9-byter inspired by *@Neil*'s comment below, which is pretty similar as the current approach above: ``` $EPNIÊ+ˆ¯ ``` [Try it online](https://tio.run/##yy9OTMpM/f9fxTXAz/Nwl/bptkPr//83BQA) or [verify the first \$n=10\$ test cases, excluding \$2\$](https://tio.run/##yy9OTMpM/R/iY@RdVmmvpPCobZKCkv1/w0rXAL/Kw13ap9sOrf9fq3Noy38A). **Explanation:** ``` $ # Push 1 and the input-integer G # Loop input-1 amount of times: D # Duplicate the current integer > # Increase this copy by 1 D # Duplicate that as well Š # Tripleswap the stack from a,b,c to c,a,b * # Multiply the top two values }) # After the loop, wrap all values on the stack into a list # (after which the result is output implicitly) $ # Push 1 and the input-integer E # Loop `N` in the range [1,input]: P # Push the product of the stack / top # (which will be 1 in the first iteration) NIÊ # Check that `N` is NOT equal to the input # (0 if it's the final iteration, 1 otherwise) + # Add that to the product ˆ # Pop and add it to the global array ¯ # Push the global array for the next iteration # (after which the last pushed global array is output implicitly after # the loop) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~53~~ 52 bytes ``` f=(n,x=1)=>[,[x],[x*3,x*1.5]][n]||[x*=2,...f(n-1,x)] ``` [Try it online!](https://tio.run/##DcjBDoIwDADQ32mhNFbjac4fWXogyEwNWQ0QswP/Pjm8y/uMv3GbVvvuQ/HX3FqOUKhGwfhMlKqeuhvVTviumooexxnxSsycoQxCFbWF7CtYlGAPuYS@N5y8bL7MvPgbjDIYYmh/ "JavaScript (Node.js) – Try It Online") Making special \$1=\frac 13+\frac 1{1.5}\$ make it bit shorter [Answer] # [Python 2](https://docs.python.org/2/), 43 bytes *-10 bytes thanks to dingledooper* ``` lambda n:[4-(x>n-3)<<x>>1for x in range(n)] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKtpEV6PCLk/XWNPGpsLOzjAtv0ihQiEzT6EoMS89VSNPM/Y/SCgPIWSoo2BoqGmlUFCUmVeikKejkAZU9R8A "Python 2 – Try It Online") ## First Attempt, 53 bytes ``` f=lambda n:map(lambda x:2**x*(4-(x>n-3))/2, range(n)) ``` [Try it online!](https://tio.run/##LcpBCoAgEEbhq8zSEaOyVkLdZaKsIH9FWtjprUXL9/HScx8RtlY/XRKWVQguSFJ/FGe1LlqNjSozmoG5tYayYN8UmKuPmUAnfuoN9R07SvnETTDkv6u@ "Python 2 – Try It Online") Porting to Python. [Answer] # JavaScript, 48 bytes [Try it online](https://tio.run/##Dck7DoMwDADQ68QlseoiFtKkB0EZIj6RK2ojqCpunzK86b3zLx/jztvXiU5zrSVIiM5JpNdAFhGLEUj4yZs5QzxvD@jlGuxsm/qBUvWL7oYDeX7S3TcNw6hy6DrjqsWwvQD4@gc "JavaScript (Node.js) – Try It Online") ``` f=n=>--n>1?[1,...f(n)].map(x=>x*2):n?[1.5,3]:[1] ``` Original answer (49 bytes): ``` f=n=>[[1],,[2,3,6]][--n]||[2,...f(n).map(x=>x*2)] ``` [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 26 bytes [SBCS](https://github.com/abrudz/SBCS) ``` {1≡⍵:1⋄3≡⍵:2 3 6⋄2,2×∇⍵-1} ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=qzZ81LnwUe9WK8NH3S3GULaRgrGCGZBvpGN0ePqjjnagmK5hLQA&f=Szu0wlDBWMFEwRQA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f) A dfn submission which encodes the inductive proof posted in the comments: to get a solution for `n+1`, double each of the denominators and add `2` to the denominators. E.g. `2 3 6` solves `3` → `2 4 6 12` solves `4` → `2 4 8 12 24` solves `5` → ... [Answer] # [Scala](https://www.scala-lang.org/), 105 bytes Golfed version. [Try it online!](https://tio.run/##ZU87T8MwEN77Kz5ZHWzillq8U1wJFlSJAaliAoRMmhRD4iS2WxVF@e3BSSsWlrvT3fc6l6hcdeXHV5p4PCmrH6qlWfVLNCNgnWYolDZU2Y2LcWet@nlZeavN5o3FeDbaQw5IYKdyaFNt/aN2/bZvVHCccZxzXHBcclxxXHPccIgZGw2sP8Y0K22qkk80MJCL4QhUwcrnhjoyNnDbolBm7WLC/p1FcBw3GTVsWqiK7uWCiFMSRfupLw@BWfF9GChBBMJavJqjUBtq2/XPBoF4aTyTVMCXOKppuWh2ykLxWt7rTQBQIgibh8j0/XYyQDVr1Ims57UUkWrn9YTqLBClYQJp7lLMWMv6MGndtd0v) ``` def f(n:Int)=(1 to n).map(i=>{var a,q=BigInt("1");for(_<-1 to i){a*=q;q=1+a};q-(if(i==n)1 else 0)}).toSeq ``` Ungolfed version. [Try it online!](https://tio.run/##ZU9dS8MwFH3vrziEPSQumyt@FzvQFxn4IAyf5pC4tTPapl2Sjcnob@@SttYHA5fkntxz7jlmJTJR18XHV7KyeBFaPpUzNfcojgGwTlLkQioq9MZEeNBa/CzmVku1WbIIr0paxM0ksBcZpCp39lkaj/qLhhwXHJccVxzXHDcctxx3HOGEBQ2rZ4zTQidi9YkjFOJp8wmUbpXNFDVkoGB2eS7U2kSE/fsO3cbBMaWKjXNR0kM8JeE5GQ4PY1u0hln@3T4owRCEVXhTnVAV@OryOo0IM2VdPu9r8Sg3rlv2OWkIW6Dd48zKP7N7oSH41k22HErC3qlLB/qO@xEaumSdmj8CZzG2fesFQmdRdEgV/OIjUJm6Qhw7A24oyUyCSRfCJfWGmyxVUNcn) ``` object PariGpInScala { def main(args: Array[String]): Unit = { val inputList = List(1, 3, 4, 5, 6, 7, 8, 9, 10) inputList.foreach { n => println(s"$n summands:") println(s"1 = ${f(n).map(x=>"1/"++x.toString)mkString(" + ")} \n") } } def f(n: Int): List[BigInt] = { (1 to n).map { i => var a,q = BigInt("1") for (_ <- 1 to i) { a *= q q = 1 + a } q - (if (i == n) 1 else 0) }.toList } } ``` ]
[Question] [ Today while playing with my kids I noticed that an apparently simple toy in the park hid a challenge. [![Clock](https://i.stack.imgur.com/dl1Eu.jpg)](https://i.stack.imgur.com/dl1Eu.jpg) The wheel has a triangle that points to a number, but also has three circles that point to the numbers every 90 degrees from the first one. So: **Challenge (really simple)** Given an integer between 1 and 12 (the one pointed by the triangle) in any acceptable form, output also in any acceptable form and order the three numbers pointed by the circles (the ones every 90 degrees). **Test cases** ``` In Out 1 4, 7, 10 2 5, 8, 11 3 6, 9, 12 4 7, 10, 1 5 8, 11, 2 6 9, 12, 3 7 10, 1, 4 8 11, 2, 5 9 12, 3, 6 10 1, 4, 7 11 2, 5, 8 12 3, 6, 9 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest code for every language win! [Answer] # [Python 3](https://docs.python.org/3/), 33 bytes ``` lambda n:{*range(n%3,13,3)}-{n,0} ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPqlqrKDEvPVUjT9VYx9BYx1izVrc6T8eg9n9afpFCnkJmngJE3hAoq2lVUJSZV6KRp6OQppGnqfkfAA "Python 3 – Try It Online") --- # [Python 2](https://docs.python.org/2/), 35 bytes ``` lambda n:[(n+c)%12+1for c in 2,5,8] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKlojTztZU9XQSNswLb9IIVkhM0/BSMdUxyL2P4ifB@IXJealp2oY6hgaa1oVFGXmlSjk6SikaeRp/gcA "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 12Rṙ’m3Ḋ ``` A monadic link taking a number and returning a list of numbers. **[Try it online!](https://tio.run/##y0rNyan8/9/QKOjhzpmPGmbmGj/c0fUfJAAA "Jelly – Try It Online")** or see [all cases](https://tio.run/##y0rNyan8/9/QKOjhzpmPGmbmGj/c0QXiHt1zuP1R05qjkx7unAGkDQ4tA5LeQBz5HwA "Jelly – Try It Online"). ### How? ``` 12Rṙ’m3Ḋ - Link: number, n e.g. 5 12 - literal twelve 12 R - range [1,2,3,4,5,6,7,8,9,10,11,12] ’ - decrement n 4 ṙ - rotate left [5,6,7,8,9,10,11,12,1,2,3,4] 3 - literal three 3 m - modulo slice [5,8,11,2] Ḋ - dequeue [8,11,2] ``` [Answer] # [Python 2](https://docs.python.org/2/), 35 bytes ``` lambda n:(range(1,13)*2)[n+2:n+9:3] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPSqMoMS89VcNQx9BYU8tIMzpP28gqT9vSyjj2f1p@kUKmQmaeAkyJAlCNFZdCQVFmXolGmkampuZ/AA "Python 2 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 9 bytes ``` I:I*+12X\ ``` [**Try it online!**](https://tio.run/##y00syfn/39PKU0vb0Cgi5v9/EwA "MATL – Try It Online") ### Explanation Consider input `4` as an exmaple. ``` I: % Push [1 2 3] % STACK: [1 2 3] I % Push 3 % STACK: [1 2 3], 3 * % Multiply, element-wise % STACK: [3 6 9] + % Add implicit input, element-wise % STACK: [7 10 13] 12 % Push 12 X\ % 1-based modulus. Implicit display % STACK: [7 10 1] ``` [Answer] # [R](https://www.r-project.org), ~~29~~ 28 bytes *Thanks to @Giuseppe for saving a byte!* ``` function(n)(n+1:3*3-1)%%12+1 ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jT1MjT9vQyljLWNdQU1XV0Ejb8H9afpGCRqZCZp6CoZWhkSZXNZcCECQnlmikaWRqasJ5SjF5Sppctf8B) [Answer] # APL+WIN, 13bytes ``` (⎕⌽⍳12)[3×⍳3] ``` Explanation: ``` ⎕ Prompt for screen input of indicated time t ⍳12 Create a vector of integers from 1 to 12 ⌽ Rotate the vector by t elements front to back [3×⍳3] Select 3rd, 6th and 9th elements. ``` [Answer] # [C (gcc)](https://gcc.gnu.org), 48 bytes ``` i;f(n){for(i=4;--i;printf("%d ",n%12?:12))n+=3;} ``` [Try it online!](https://tio.run/##RY7BCsIwEETv@YolUNgl5pDWU9fQb5FIJAfXUuup5NtjUsXObebtDBvsPYRSEkcU2uJzweTPbG3ieUmyRtTdDfRJOtdPo@uJxPiBc6kMHtckSGpTUFWrgC0V7xjk4gYGY4R2@D1pOlbHOgtC/Eftg8PN7/WFWv@SrHL5AA) [Answer] # JavaScript (ES6), 29 bytes Similar to [xnor's answer](https://codegolf.stackexchange.com/a/152118/58563). ``` n=>[2,5,8].map(k=>(n+k)%12+1) ``` ### Demo ``` let f = n=>[2,5,8].map(k=>(n+k)%12+1) for(n = 1; n <= 12; n++) { console.log(n + ' -> ' + f(n)); } ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 25 bytes ``` @(x)[a=1:12 a](3+x:3:9+x) ``` [Try it online!](https://tio.run/##Lc47CsMwEEXR3qt4TUDGg/FI/goM2UdIIULcpgnBu1fm42Kaw1x4n9e3/N712Pu@r/dwto@yc@aI8gypO3PKW3e29QiMFrhhJCwEHpojRJeJsIqwSHKZCZtIFBldLJETmVwsIejP7GIJIYksLpYQRpH1Ek0Ik8h2iSaEWYQHF7KRCmyggWxUiAb6LxOb@gc "Octave – Try It Online") Fairly simple anonymous function. We first create an array of `[1:12 1:12]` - so two copies of the full number set. Then we index in to select the values of `x+3, x+6, x+9`, where `x` is the number input. Octave is 1-indexed, so we can simply select the array elements based on the input (although to be honest 0-indexed would use the same number of bytes here). This seems to use a method that is unique to the other answers in that by having two copies of the array, we don't have to wrap the indices using modulo. [Answer] # Befunge-93, ~~20~~ ~~19~~ 18 bytes ``` 852<_@#:.+1%+66+&p ``` [Try it online!](http://befunge.tryitonline.net/#code=ODUyPF9AIzouKzElKzY2KyZw&input=Ng) **Explanation** ``` 852 Push 8, 5 and 2 onto the stack - the offsets we're going to add. < Reverse direction, and start the main loop. 852 Push 2, 5, and 8 onto the stack, but we don't actually want these. p So we use a "put" operation to drop the top three values. & Read the hour from stdin. + Add it to the topmost offset. +1%+66 Mod 12 and add 1 to get it in the range 1 to 12. . Then output the result to stdout. _@#: Exit if the next offset is zero (i.e. nothing more on the stack). < Otherwise start the main loop again. ``` This relies on behaviour specific to the reference interpreter: on end-of-file, the `&` operator returns the last value that was read. That's why we can safely re-read the hour from stdin on each iteration of the loop. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 12 bytes ``` 1+12|2 5 8∘+ ``` [Try it online!](https://tio.run/##ATcAyP9hcGwtZHlhbG9n//9m4oaQMSsxMnwyIDUgOOKImCv//@KNqijiiqIsJ@KGkicsZinCqOKNszEy "APL (Dyalog Unicode) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` ƵžS+12%> ``` At the time of writing this, this submission has the lowest score submitted. Technically I am winning! [Try it online!](https://tio.run/##yy9OTMpM/f//2Naj@4K1DY1U7f7/NwEA) # How? ``` ƵžS # Push the list [2, 5, 8] + # Add the input to each number 12% # Mod each result by 12 > # Increment each # And print the ending list implicitly! ``` See [this tip of Kevin](https://codegolf.stackexchange.com/a/166851/98140) to know why `Ƶž` is 258! [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 9 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` 3{3+:6«‰P ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=MyU3QjMrJTNBNiVBQiV1MjAzMFA_,inputs=OQ__,v=0.12) [Answer] # [Clean](https://clean.cs.ru.nl), 44 bytes ``` import StdEnv @n=[(n+i)rem 12+1\\i<-[2,5,8]] ``` [Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r4zLIc82WiNPO1OzKDVXwdBI2zAmJtNGN9pIx1THIjb2f3BJIlCtrYKDguH/f8lpOYnpxf91PX3@u1TmJeZmJhcDAA "Clean – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 42 bytes ``` h=>new[]{(2+h)%12+1,(5+h)%12+1,(8+h)%12+1} ``` [Try it online!](https://tio.run/##RY3BisIwEIbPyVMM4kJKq9jCglDtRfCkILjgofQQstEOaAJJVCTk2euwrMrA/N/hn2@Unyjr9HD1aE6wf/igLzVXZ@k97CL3QQZUsL4atUATCqDVdg384EXvezwGWMLQLxuj720XRZX32VdZ5WUhvj84f2Eaav5S3iz@wlaiERmPnB2tA0FyQDKWNcWCsiLI84wzarCbdCCdkw9qvP8LzMjJ2Moab896enAY9AaNFuNRxASTBuLfUTvrUvGP5QerLo3IwBKnGZ4 "C# (.NET Core) – Try It Online") Essentially just a port of many of the other answers to C#. [Answer] # Japt, 11 bytes ``` 3ÆU±3 uC ªC ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=M8ZVsTMgdUMgqkM=&input=OA==) --- ## Explanation Implicit input of integer `U`. Generate a 3 element array (`3Æ`) and, for each element, increment `U` by 3 (`U±3`), modulo by 12 (`uC`) and, because `12%12=0`, return the result OR 12 (`ªC`). [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 11 bytes **Solution:** ``` 1+12!2 5 8+ ``` [Try it online!](https://tio.run/##y9bNz/7/31Db0EjRSMFUwULb8P9/AA "K (oK) – Try It Online") **Examples:** ``` 1+12!2 5 8+1 4 7 10 1+12!2 5 8+2 5 8 11 1+12!2 5 8+3 6 9 12 1+12!2 5 8+4 7 10 1 ``` **Explanation:** This was the first solution that came to mind. Might not be the best or shortest. ``` 1+12!2 5 8+ / the solution 2 5 8+ / add 2, 5 and 8 to the input 12! / apply modulo 12 to the results 1+ / add 1 ``` [Answer] # GolfScript, 46 bytes ``` ~13,1>:x?:y;0:i;x y 3+12%=x y 6+12%=x y 9+12%= ``` This is the first time I'm doing code golf, so with my lack of experience I've probably not found the best solution, but I need to start somewhere, right? [Try it online](https://copy.sh/golfscript/?c=IjEifjEzLDE+Ong/Onk7MDppO3ggeSAzKzEyJT14IHkgNisxMiU9eCB5IDkrMTIlPQ==) or [try all cases](https://copy.sh/golfscript/?c=IjEifjEzLDE+Ong/Onk7MDppO3ggeSAzKzEyJT14IHkgNisxMiU9eCB5IDkrMTIlPScnCiIyIn4xMywxPjp4Pzp5OzA6aTt4IHkgMysxMiU9eCB5IDYrMTIlPXggeSA5KzEyJT0nJwoiMyJ+MTMsMT46eD86eTswOmk7eCB5IDMrMTIlPXggeSA2KzEyJT14IHkgOSsxMiU9JycKIjQifjEzLDE+Ong/Onk7MDppO3ggeSAzKzEyJT14IHkgNisxMiU9eCB5IDkrMTIlPScnCiI1In4xMywxPjp4Pzp5OzA6aTt4IHkgMysxMiU9eCB5IDYrMTIlPXggeSA5KzEyJT0nJwoiNiJ+MTMsMT46eD86eTswOmk7eCB5IDMrMTIlPXggeSA2KzEyJT14IHkgOSsxMiU9JycKIjcifjEzLDE+Ong/Onk7MDppO3ggeSAzKzEyJT14IHkgNisxMiU9eCB5IDkrMTIlPScnCiI4In4xMywxPjp4Pzp5OzA6aTt4IHkgMysxMiU9eCB5IDYrMTIlPXggeSA5KzEyJT0nJwoiOSJ+MTMsMT46eD86eTswOmk7eCB5IDMrMTIlPXggeSA2KzEyJT14IHkgOSsxMiU9JycKIjEwIn4xMywxPjp4Pzp5OzA6aTt4IHkgMysxMiU9eCB5IDYrMTIlPXggeSA5KzEyJT0nJwoiMTEifjEzLDE+Ong/Onk7MDppO3ggeSAzKzEyJT14IHkgNisxMiU9eCB5IDkrMTIlPScnCiIxMiJ+MTMsMT46eD86eTswOmk7eCB5IDMrMTIlPXggeSA2KzEyJT14IHkgOSsxMiU9Jyc=) [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 84 bytes ``` (()()()){({}<(()(){})(((()()()){}){}<>){(({})){({}[()])<>}{}}<>(([{}]{})<>)>[()])}<> ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0NDEwQ1qzWqa23AnOpaTQ0NuHAtENnYAaWB8hBV0RqasZo2drXVtUAJDY3o6tpYoBRQjR1YBij4/78JAA "Brain-Flak – Try It Online") At least I beat [Doorknob's face solution](https://codegolf.stackexchange.com/a/152240/31203)... Explanation: ``` LOOP 3 TIMES: (()()()){({}< n += 2: (()(){}) push 12: (((()()()){}){}<>) n mod 12 + 1; pushing to both stacks: {(({})){({}[()])<>}{}}<>(([{}]{})<>) END LOOP: >[()])}<> ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 12 bytes ``` %R12+LQ*R3S3 ``` [Try it online!](https://tio.run/##K6gsyfj/XzXI0EjbJ1AryDjY@P9/EwA "Pyth – Try It Online") [Answer] # Wolfram Language (Mathematica) 20 bytes ``` Mod[#+{3,6,9},12,1]& ``` The normal modulus operation, threaded over a list, offset by 1. [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zc/JVpZu9pYx0zHslbH0EjHMFbtv0t@NFdAUWZeSXSmjoKSgq6dgpKOQlp0Zmwsl45CNVDMEIiMamP/AwA) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` ⁺ẇf+12%› ``` [Try it online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigbrhuodmKzEyJeKAuiIsIiIsIjQiXQ==) ([All test cases](https://vyxal.pythonanywhere.com/#WyIiLCIxMsm+xpsiLCLigbrhuodmKzEyJeKAuiIsIm4kd0o74oGLIiwiIl0=)) Port of [SunnyMoon's 05AB1E solution](https://codegolf.stackexchange.com/a/215712/80050) **How it works:** ``` ⁺ẇf+12%› ⁺ẇ The number 258 f ...as a list of digits ⟨ 2 | 5 | 8 ⟩ + Add the input to each 12% Mod-12 each › Increment each (implicit output) ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 8 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` ṇɗd+12%⁺ ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVFMSVCOSU4NyVDOSU5N2QlMkIxMiUyNSVFMiU4MSVCQSZmb290ZXI9JmlucHV0PTcmZmxhZ3M9) #### Explanation ``` ṇɗd+12%⁺ # Implicit input ṇɗ # Push compressed integer 258 d+ # Add [2,5,8] to input 12% # Mod each by 12 ⁺ # Increment each # Implicit output ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 9 bytes ``` 12Rᶠ{-Z3¦ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FmsMjYIebltQrRtlfGjZkuKk5GKoxIJdhlxGXMZcJlymXGZc5lwWXJZchgZchoZchkYQFQA) ``` 12Rᶠ{-Z3¦ 12R [1,2,...,12] ᶠ{ Filter by - Subtract the input Z Check if the result is non-zero 3¦ Check if the result is divisible by 3 ``` --- # [Nekomata](https://github.com/AlephAlpha/Nekomata), 10 bytes ``` 258¢D+12%→ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FmuNTC0OLXLRNjRSfdQ2aUlxUnIxVGbBLkMuIy5jLhMuUy4zLnMuCy5LLkMDLkNDLkMjiAoA) ``` 258¢D+12%→ 258¢D Decimal digits of 258 + Add 12% Modulo 12 → Increment ``` [Answer] # [Piet](https://www.dangermouse.net/esoteric/piet.html) + [ascii-piet](https://github.com/dloscutoff/ascii-piet), 45 bytes (5×18=90 codels) ``` tAaaqreeumccsqqqijlVa rbiqaaueljnvea?_ t?B tt ``` [Try Piet online!](https://piet.bubbler.one/#eJyVj1EKgzAQRO-y3yNkNYnGq6gfxaYgWCvYfknv3l27HsBk4G02M0uy0_i6Z2q7zoEjOF3SgE5DER4luFYFMIODqpK2bnZoIDZzJ_UeXY9_OmgwikkmHGOk24g0kOCOg7_2Ko25a38ZQFteqaWiKAg0T0-p2cmSU95Gah-3ecugaVk_b73rF7H2S2msjN4YjNFYGxtjMrI7i3Mil_T9AV0UXkY) ![](https://github.com/Bubbler-4/svg-stuff-and-tools/raw/47ae5ea89ef286f7aab2e4d517a06c3dd5363575/images/CodeGolfSE/152114.svg) My looping template is getting weirder and weirder... :P ``` inN 4 [n 4]; force toggle CC at the exit of 4 region Loop: dup CC+ [n flag] switch CC on 3rd iteration so it will exit after the loop 2 1 roll [flag n] 2 + [flag n+2] 3 dup dup * + % [flag (n+2)%12] 1 + d outN [flag next_n] compute and print the next number 1 outC [flag next_n] print the separator (ASCII 1) 2 1 roll [next_n flag] 2 / [next_n flag/2] divide flag by 2; flag becomes odd after two loops ``` [Answer] # [Piet](https://www.dangermouse.net/esoteric/piet.html) + [ascii-piet](https://github.com/dloscutoff/ascii-piet), 62 bytes (46×2=92 codels) ``` TABdDTvVvVnNNFJAQUiIiIIAeEeEuUUMTJBCSBvVvVNMLnNnNfFFVBQIMEiCcc ``` [Try Piet online!](https://piet.bubbler.one/#eJxdj8EOwiAMht-l55LQMYbyKoSDmZgsmbpkejJ7dxspDsahP7Tla_8PjM9rAh-CRjpHDDSI9qIdUsdaykj_6ND9Yi6YrKcWIxQrWabogzZDGeYqtWirz5RVt4PKntJlDulm34YjM4sLJyZMZYZaWL-7qEHk9ryVVWyMCGtawINSChDm6c530nz4ldYR_O0yrwlheizvF9cG2L7PpGCu) [Answer] # [Pushy](https://github.com/FTcode/Pushy), 12 bytes ``` 258s{K+12%h_ ``` **[Try it online!](https://tio.run/##Kygtzqj8/9/I1KK42lvb0Eg1I/7///@GhgA "Pushy – Try It Online")** ``` 258 \ Push 258 s \ Split into digits, yielding [2, 5, 8] {K+ \ Add input to each 12% \ Modulo each by 12 h \ Increment each _ \ Print (space separated) ``` ## 12 bytes An alternative for the same byte count: ``` 12R{:{;$...# ``` **[Try it online!](https://tio.run/##Kygtzqj8/9/QKKjaqtpaRU9PT/k/kAsA "Pushy – Try It Online")** ``` 12R \ Push range(1, 12), inclusive {: ; \ Input times do: { \ Rotate left $ \ While there are items on stack: ... \ Pop the top three # \ Print top item ``` [Answer] # [Haskell](https://www.haskell.org/), 29 bytes *-2 bytes thanks to Laikoni.* ``` f n=[mod(n+i)12+1|i<-[2,5,8]] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzY6Nz9FI087U9PQSNuwJtNGN9pIx1THIjb2f25iZp6CrUJuYoGvgkZBUWZeiYKeQpqmQrShnp6hUex/AA "Haskell – Try It Online") Not very original, no... [Answer] # [Swift](https://swift.org), 30 bytes ``` {n in[2,5,8].map{($0+n)%12+1}} ``` [Try it online!](https://tio.run/##Ky7PTCsx@Z@TWqKQpmD7vzpPITMv2kjHVMciVi83saBaQ8VAO09T1dBI27C29n9afpFCJlCFgqGenp6hUXVBUWZeiUamTppGpqZm7X8A) Port of many other answers to Swift [Answer] # Wolfram Language (Mathematica) 35 bytes ``` Range@12~RotateLeft~#~Take~{3,9,3}& ``` The above asserts, in infix notation, what can be expressed more clearly as ``` Function[Take[RotateLeft[Range[12],Slot[1]],List[3,9,3]]] ``` `RotateLeft` rotates `Range[12]`, the sequence 1,2,...12, leftward by the input number. `Slot[1]` or `#` holds the input number, n. For example, with n = 4, ``` Function[RotateLeft[Range[12],4]]] ``` returns the list ``` {5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4} ``` `Take...{3,9,3}` returns every third element in that list from position 3 through position 9, namely ``` {7, 10, 1} ``` ]
[Question] [ We had a [prime factorization challenge](https://codegolf.stackexchange.com/q/1979/42545) a while ago, but that challenge is nearly six years old and barely meets our current requirements, so I believe it's time for a new one. ## Challenge Write a program or function that takes as input an integer greater than 1 and outputs or returns a list of its prime factors. ## Rules * Input and output may be given by any standard method and in any standard format. * Duplicate factors must be included in the output. * The output may be in any order. * The input will not be less than 2 or more than 231 - 1. * Built-ins are allowed, but including a non-builtin solution is encouraged. ## Test cases ``` 2 -> 2 3 -> 3 4 -> 2, 2 6 -> 2, 3 8 -> 2, 2, 2 12 -> 2, 2, 3 255 -> 3, 5, 17 256 -> 2, 2, 2, 2, 2, 2, 2, 2 1001 -> 7, 11, 13 223092870 -> 2, 3, 5, 7, 11, 13, 17, 19, 23 2147483646 -> 2, 3, 3, 7, 11, 31, 151, 331 2147483647 -> 2147483647 ``` ## Scoring 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/), 55 bytes ``` f=lambda n,k=2:n/k*[0]and(f(n,k+1),[k]+f(n/k,k))[n%k<1] ``` [Try it online!](https://tio.run/nexus/python2#@59mm5OYm5SSqJCnk21rZJWnn60VbRCbmJeikaYBFNI21NSJzo7VBnL0s3WyNTWj81SzbQxj/xcUZeaVKKRpGJmaav4HAA "Python 2 – TIO Nexus") [Answer] # [Pyth](https://pyth.herokuapp.com/?code=P&input=2147483646&debug=0), 1 byte ``` P ``` I like Pyth's chances in this challenge. [Answer] ## Python 2, 53 bytes ``` f=lambda n,i=2:n/i*[f]and[f(n,i+1),[i]+f(n/i)][n%i<1] ``` Tries each potential divisor `i` in turn. If `i` is a divisor, prepends it and restarts with `n/i`. Else, tries the next-highest divisor. Because divisors are checked in increasing order, only the prime ones are found. As a program, for 55 bytes: ``` n=input();i=2 while~-n: if n%i:i+=1 else:n/=i;print i ``` [Answer] # Mathematica, ~~38~~ 30 bytes Thanks @MartinEnder for 8 bytes! ``` Join@@Table@@@FactorInteger@#& ``` [Answer] # [Haskell](https://www.haskell.org/), 48 bytes ``` (2%) n%1=[] n%m|mod m n<1=n:n%div m n|k<-n+1=k%m ``` [Try it online!](https://tio.run/##XY3BbsIwDIbvfgofqMREI9Vx2xREuPACHCdtHKpBt6pNmMa0C@zVlznVaNEkW/Zvf7/9Vp@7Y9@Hxj6HuU4ewCdkn/ZS3NWdDujQr8n6lU8O7VdU126t/IJsl7jg6tajxfeP1n/iDBukLCOAiwKNaoMaOBaGfFCpDMq/jqG6zeKY9KQYdFEMvhSLFMmILu/gfwHxZ1wbYUlS/Jqzpa5Mdns2HBr38abkUszCUm7yisu8nGAeYY6GIjZME2oGdFSgvsPPS9PXr@egHre73S8 "Haskell – Try It Online") Example usage: `(2%) 1001` yields `[7,11,13]`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` Æf ``` [Try it online!](https://tio.run/nexus/jelly#@3@4Le3/4fZHTWvc//830lEw1lEw0VEw01Gw0FEwBPKNTE1BBFDA0MDAEMg0MjawNLIwNwAyDU3MTSyMzUzMkNjmAA "Jelly – TIO Nexus") [Answer] # JavaScript (ES6), 44 bytes ``` f=(n,x=2)=>n-1?n%x?f(n,x+1):[x,...f(n/x)]:[] ``` Horribly inefficient due to the fact that it iterates from 2 up to every prime factor, including the last. You can cut the time complexity dramatically at the cost of 5 bytes: ``` f=(n,x=2)=>x*x>n?[n]:n%x?f(n,x+1):[x,...f(n/x,x)] ``` [Answer] # [Cubix](https://github.com/ETHproductions/cubix), ~~37~~ 32 bytes ``` vs(...<..1I>(!@)s)%?w;O,s(No;^;< ``` [Try it online!](https://tio.run/nexus/cubix#@19WrKGnp2ejp2foaaeh6KBZrKlqX27tr1Os4ZdvHWdt8/@/kZGxgaWRhbkBAA "Cubix – TIO Nexus") or [Watch it in action](http://ethproductions.github.io/cubix/?code=dnMoLi4uPC4uMUk+KCFAKXMpJT93O08scyhObzteOzw=&input=MTI=&speed=4). [Answer] # [Haskell](https://www.haskell.org/), 47 bytes Basically this checks all integers `2, 3, 4, 5, ...` for divisors of `n`. If we find one, we factor that out and repeat the process until we get to `1`. ``` f 1=[] f n=(:)<*>f.div n$until((<1).mod n)(+1)2 ``` [Try it online!](https://tio.run/##XY7BDoIwDIbvfYoeOIACoSswMMCLGA8kSFyEaRS9GJ8dNyJgTNas/9/v73aq7@dj141ji1TuD9CiLt2dV2yqNmzUE7Xz0IPqXLcgL@wvDWrP3ZInxr5WGku83pQe0MEWheAoF5mMAF4BCAwqFMD2Yogn5Rsj/XYM2exZm8SqGESSTDkfEx9JGp3@wH8HKIrIjqVhyZTJz1@ZH5sWLXO701RuwoalWMYZp3G6wrzAbAOJbZhWVE7ooiB4jx8 "Haskell – Try It Online") [Answer] # [Actually](https://github.com/Mego/Seriously), 6 bytes ``` w`in`M ``` [Try it online!](https://tio.run/nexus/actually#@1@ekJmX4Pv/vwUA "Actually – TIO Nexus") Explanation: ``` w`in`M w factor into primes and exponents `in`M repeat each prime # of times equal to exponent ``` [Answer] # J, 2 bytes ``` q: ``` ~~Body must be at least 30 characters.~~ [Answer] # [MATL](https://github.com/lmendo/MATL), 2 bytes ``` Yf ``` [Try it online!](https://tio.run/nexus/matl#@x@Z9v@/kQkA "MATL – TIO Nexus") Obligatory "boring built-in answer". [Answer] # Japt, 2 bytes ``` Uk ``` A built-in `k` used on the input `U`. Also refers to a country. [Test it online!](http://ethproductions.github.io/japt/?v=master&code=VWs=&input=MTEwMTE=) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 1 byte ``` ǐ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLHkCIsIiIsIjIxNDc0ODM2NDYiXQ==) Just the built-in. But that's boring, so ## [Vyxal](https://github.com/Vyxal/Vyxal), ~~16~~ 8 bytes ``` K~æ~Ǒ$ẋf ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJLfsOmfseRJOG6i2YiLCIiLCIyMTQ3NDgzNjQ2Il0=) ## Explained ``` ʀ~æ~Ǒ$ẋf ʀ~æ # From the all numbers in the range [0, input], keep only those that are prime ~Ǒ # Without popping anything, get the multiplicity of each prime divisor - this leaves the stack as [divisors, multiplicities] $ẋ # Swap the two items and repeat each divisor multiplicity times f # Flatten and output that ``` [Answer] # [tone-deaf](https://github.com/kade-robertson/tone-deaf), 3 bytes This language is quite young and not really ready for anything major yet, but it can do prime factorization: ``` A/D ``` This will wait for user input, and then output the list of prime factors. [Answer] # MATLAB, 6 bytes I think this does not require any explanation. ``` factor ``` [Answer] ## Batch, 96 bytes ``` @set/an=%1,f=2,r=0 :l @set/af+=!!r,r=n%%f @if %r%==0 echo %f%&set/an/=f @if %n% gtr 1 goto l ``` [Answer] # [R](https://www.r-project.org/), ~~53~~ 52 bytes ``` p=function(n,i=2)if(n>1)c(i[m<-!n%%i],p(n/i^m,i+!m)) ``` [Try it online!](https://tio.run/##dZHxCoIwEMb/7ykuIthoktvUGWQvEhVhEw5yytTnt1liOQnuYPvuft/dmO1ri6W@Ffe8rWyT9XVWdCZvsTLEMMwExYKYE6c5wXN5DNZmu8ULq4nZ47VkuFuXlM49iKCwgeAkVnNZfmTpydHYzcAHkqniM@mXWWJc/FZ9VMTxuAeDmAFXi3oyM/fCnxWG/NOunBd3uZgnZHgQqQq/j3kPnvqHHVwenPmC5ZGKUplEyS8sJ1gOBvFwkPwfqkZ0ukMGxR2fDTw6DW3logoeWtdgdd7Zxn38qn8B "R – Try It Online") Recursive function: overflows the stack limit and errors on TIO for the last test case. --- # [R](https://www.r-project.org/), ~~59~~ 58 bytes ``` function(n,i=2)while(n>1)if(n%%i)i=i+1 else{show(i);n=n/i} ``` [Try it online!](https://tio.run/##dY/taoMwFIb/9yoOlIJhlplEjWWktzJcG9dDs2QkEX@MXbvTVmyNDHLgfD3ve@L6b4df6r2pT8E6L/umNaeA1iQmRclId0GtEnOkBJvE7HZIUOILBaW9@vEX2yVI3ow0r/i7VEoYgS3sj2yzbPN7m0ftfNpOIQbKeRIz1YNZY5Q9T2OUFcV0RwpFClSs5uVCPHqxV5bR@7oYtOgQKz/GswOrRPb4zM143h9vGOIwiK9Ymou84mVePsN8hvkoUIwJp5vtP6yY2LkGCWerPBgbQDlnXQofbYAOtYZQXxXUoK35hDDIQW3O4O0t93vbhv4P "R – Try It Online") Non-recursive function: does not error for large primes, but will still take a very long time to run (and so times-out without erroring on TIO for the last test case anyway). [Answer] # [CellTail](https://github.com/mousetail/CellTail/blob/main/README.md), 166 bytes ``` N,(u,u,_),N:1,(u,1),(0,2);(0,2),N,N:1,N,N;N,(u,v,0),N:1,(v,1),(u/v,2,(u/v)%2);N,(u,v,w),N:1,(u,v+1,u%(v+1)),N;a&(_,_,_),N,N:1,a,N;_,(v,1),_:1,v,N;N,u,N:1,(u,2,u%2),N; ``` [Try the demo](https://mousetail.github.io/CellTail/#ST1DIE47Ck89TjsKI009NDA7CgpOLCh1LHUsXyksTjoxLCh1LDEpLCgwLDIpOygwLDIpLE4sTjoxLE4sTjtOLCh1LHYsMCksTjoxLCh2LDEpLCh1L3YsMiwodS92KSUyKTtOLCh1LHYsdyksTjoxLCh1LHYrMSx1JSh2KzEpKSxOO2EmKF8sXyxfKSxOLE46MSxhLE47XywodiwxKSxfOjEsdixOO04sdSxOOjEsKHUsMix1JTIpLE47) ## Explanation: Base case, when we reach the end switch to a recursion resistant tuple and pass a message right to break it. Then the message right sends a 1 to prevent recursion when the tuple has broken. ``` N,(u,u,_),N:1,(u,1),(0,2);(0,2),N,N:1,N,N; ``` We have found a factor, try again in the cell to the right with `(u/v)` ``` N,(u,v,0),N:1,(v,1),(u/v,2,(u/v)%2); ``` We have not found a factor, try another. ``` N,(u,v,w),N:1,(u,v+1,u%(v+1)),N; ``` Copy 3-tuples from left to current ``` a&(_,_,_),N,N:1,a,N; ``` Break recursion resistant tuples. Hopefully the next step the value from the right will throw a 1 to break the recursion. ``` _,(v,1),_:1,v,N; ``` Base case, start with trying 2 as a factor. ``` N,u,N:1,(u,2,u%2),N; ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) + coreutils, 19 bytes ``` factor|sed s/.*:.// ``` [Try it online!](https://tio.run/nexus/bash#@5@WmFySX1RTnJqiUKyvp2Wlp6///7@RqSkA "Bash – TIO Nexus") [Answer] ## Pyke, 1 byte ``` P ``` [Try it here!](http://pyke.catbus.co.uk/?code=P&input=12) Prime factors builtin. [Answer] # [Hexagony](https://github.com/m-ender/hexagony), 58 bytes Not done golfing yet, but @MartinEnder should be able to destroy this anyway Prints out factors space-separated, with a trailing space Golfed: ``` 2}\..}$?i6;>(<...=.\'/})."@...>%<..'':\}$"!>~\{=\)=\}&<.\\ ``` Laid-out: ``` 2 } \ . . } $ ? i 6 ; > ( < . . . = . \ ' / } ) . " @ . . . > % < . . ' ' : \ } $ " ! > ~ \ { = \ ) = \ } & < . \ \ . . . ``` Explanation coming later. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 1 byte ``` Ò ``` [Try it online!](https://tio.run/nexus/05ab1e#@3940v//RoYm5iYWxmYmZgA "05AB1E – TIO Nexus") [Answer] # CJam, 2 bytes ``` mf ``` [cjam.aditsu.net/...](//cjam.aditsu.net#code=rimf%60&input=2147483646) This is a function. Martin, it seems I was sleepy. [Answer] ## C, 92 bytes ``` int p(int n){for(int i=2;i<n;i++)if(n%i==0)return printf("%d, ",i)+p(n/i);printf("%d\n",n);} ``` Ungolfed version: ``` #include <stdio.h> #include <unistd.h> #include <stdlib.h> int prime(int number) { for (int i = 2; i < number; i++) { if (number % i == 0) { printf("%d, ", i); return prime(number / i); //you can golf away a few bytes by returning the sum of your recursive function and the return of printf, which is an int } //this allow you to golf a few more bytes thanks to inline calls } printf("%d\n", number); } int main(int argc, char **argv) { prime(atoi(argv[1])); } ``` [Answer] # [Java (OpenJDK)](http://openjdk.java.net/), 259 bytes ``` import java.util.*;interface g{static void main(String[]z){int a=new Scanner(System.in).nextInt();int b=0;int[]l={};for(int i=2;i<=a;i++){for(;a%i<1;l[b-1]=i){l=Arrays.copyOf(l,b=l.length+1);a/=i;}}for(int i=0;i<b;i++)System.out.print(l[i]+(i<b-1?", ":""));}} ``` [Try it online!](https://tio.run/nexus/java-openjdk#RY5BT4QwEIX/SkNi0sputStZzZbGePTkgSPhMGDB2ZRCyuwqEn47gjHx9JL33nzzFmz7LhA7wxXkhdDJW42ebKihsqyZBgLCil07fGctoOcZBfRNXnyLae0xMN5@sqwC723g2TiQbSV6Ib39oldPXGw4Vpr7TfPCmWnWdRf45qI5aEwNaIxjMW2uhhtMlXZ5uVeFQTE58xICjIOsun58q7nblcZJZ31DH7ESGu4M6nn@J65/0vIX@Demu5Ds183EXY5FzNd4r56jHYtOUSTEerwsB5U8Jk8Px@T4Aw "Java (OpenJDK) – TIO Nexus") [Answer] # [PHP](https://php.net/), 51 bytes ``` for($i=2;1<$a=&$argn;)$a%$i?$i++:$a/=$i*print"$i "; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkbGysZP0/Lb9IQyXT1sja0EYl0VYNLGetqZKoqpJpr5KprW2lkqhvq5KpVVCUmVeipJKpANTzHwA "PHP – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 51 bytes ``` i;f(n){for(i=2;i<=n;)n%i?i++:printf("%d ",i,n/=i);} ``` [Try it online!](https://tio.run/##XY7LCsIwEEXX5itKoDClLSZp@tBY/RapNMzCWGpdlX57TEwEcXXuXM4MM5R6GKxFNYLJ1vExA/ZC4ak3KjMpXjDPj9OMZhmBpreEFliYfY@Z2qwGVycmIyvZ/Sjl2VmuVmTnbzpMr@UJlLq4EeJ37lc08NnTILyhoQqQAU1AF8CjI@r6G6LAGeOxEhU7iK5lceSylV3VyOZvbv0X9g0 "C (gcc) – Try It Online") [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), 19 bytes ``` IT1WP2K%ZB|:N,:M?t; ``` [Try it online!](https://tio.run/##XY1NCgIxDIX3PUU37io0Sf9mBhTciSguBMEDqAOCi3Hp3WtSnFaEhua9fC@5PR/XcbrnvD3B@Yi7xWXz7g@m369fQ0a9XGlUJB8pV5RhI3w7Umn2xAZsihR6X3JGe6Mhsg4/8N9TYC3IODILXJxHsh2maOdjZVGdy06ujsPMgosuUXChwVRhkoCXhqChsaBV5XrvAw "Gol><> – Try It Online") ## Explanation ``` IT < [n] read input to n then mark cell (T) 1WP | < [n m=2] from 2 onwards (m=1;while m:m++;) 2K%ZB < [n m+1] copy two elements, mod, break if n%m==0 :N < [n m] (< where n%m==0) print m with newline ,:M?t; < [n/m] (< new n) divide, if not 1 redo from T else exit ``` [Answer] # [Pyt](https://github.com/mudkip201/pyt), 1 [byte](https://github.com/mudkip201/pyt/wiki/Codepage) ``` ḋ ``` Boring built-in answer [Try it online!](https://tio.run/##K6gs@f//4Y7u//8NjY0B) ]
[Question] [ # Task Your task is to produce string that contains average characters of string. First character of result would be average character of first character (which is first character) and second character average of two first characters and so on. # What is average character? Strings are arrays of bytes. *Average character* of string can be found by calculating the average of the ASCII values of characters in string and taking corresponding ASCII character. For example string `"Hello!"` can be written as byte sequence `72 101 108 108 111 33`. Average of ascii values is 533/6 = 88.833... and when it's rounded to nearest integer we get 89 which is ascii code for captial letter `Y`. # Rules * You can assume that input contains only printable ASCII characters * Input can be read from stdin or as command line arguments or as function arguments * Output must be stdout. If your program is function, you can also return the string you would otherwise print. * It must be whole program or function, not snippet * [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply * Integers are rounded by function `floor(x+0.5)` or similar function. # How do I win? This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer (in bytes) in wins. # Examples * `Hello!` → `HW^adY` * `test` → `tmop` * `42` → `43` * `StackExchange` → `Sdccd_ccccddd` [Answer] ## Brainfuck 106 bytes ``` ,[>,<.[->+<]>>++<[>[->+>+<<]>[-<<-[>]>>>[<[>>>-<<<[-]]>>]<<]>>>+<<[-<<+>>]<<<]>[-]>>>>[-<<<<<+>>>>>]<<<<<] ``` This is my first participation in a code-golf, please be gentle! It does work but brainfuck can't handle floats (not that i know of) so the rounded value is always the bottom one (might fix my algorithm later). Also, the algorithm averages the values 2 by 2, meaning it could be innacurate in some spots. And I need to fix a bug that is printing a number at the end of the output too. [Answer] # Pyth, 16 bytes ``` smCs+.5csaYCdlYz ``` Pretty straightforward. Using `s+.5` instead of rounding, because for some reason `round(0.5, 0)` is 0 in Python. [Answer] # Q, ~~15~~ 12 bytes 12 bytes as an expression ``` "c"$avgs"i"$ q)"c"$avgs"i"$"Hello!" "HW^adY" q)"c"$avgs"i"$"test" "tmop" q)"c"$avgs"i"$"42" "43" q)"c"$avgs"i"$"StackExchange" "Sdccd_ccccddd" ``` or 15 bytes as a function ``` {"c"$avgs"i"$x} q){"c"$avgs"i"$x} "Hello!" "HW^adY" q){"c"$avgs"i"$x} "test" "tmop" q){"c"$avgs"i"$x} "42" "43" q){"c"$avgs"i"$x} "StackExchange" "Sdccd_ccccddd" ``` takes advantage of 1. the "i"$ cast to convert a string (list of characters) to a list of integers 2. the avgs function, which computes the running average of a list as a list of floats 3. the "c"$ cast to convert a list of floats to a list of characters, and which automatically rounds each float to the nearest integer before doing so [i.e. ("c"$99.5) = ("c"$100) and ("c"$99.4) = ("c"$99) ] [Answer] # CJam, 19 bytes ``` Uq{i+_U):Ud/moco}/; ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=Uq%7Bi%2B_U)%3AUd%2Fmoco%7D%2F%3B&input=StackExchange). [Answer] # Perl: ~~31~~ 30 characters (29 characters code + 1 character command line option.) ``` s!.!chr.5+($s+=ord$&)/++$c!ge ``` Sample run: ``` bash-4.3$ perl -pe 's!.!chr.5+($s+=ord$&)/++$c!ge' <<< 'StackExchange' Sdccd_ccccddd ``` [Answer] # [Python 3](https://docs.python.org/3/), 65 bytes ``` n=t=0 for c in input():n+=1;t+=ord(c);print(end=chr(int(.5+t/n))) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P8@2xNaAKy2/SCFZITMPiApKSzQ0rfK0bQ2tS7Rt84tSNJI1rQuKMvNKNFLzUmyTM4o0QGw9U@0S/TxNTc3//z1Sc3LyFQE "Python 3 – Try It Online") If I use `round()` instead of `int(.5+` etc., it saves one character but is *technically* not in compliance with the challenge: Python's `round()` rounds halves to the nearest even integer, not upwards. However, it works correctly on all sample inputs. [Answer] # C# ~~189 135 134~~ 106 Bytes ``` var x=s.Select((t,i)=>Math.Round(s.Select(a=>(int)a).Take(i+1).Average())).Aggregate("",(m,c)=>m+(char)c); ``` Can be seen [here](http://csharppad.com/gist/f6195bf7201b38ea8f3c) First time golfer [Answer] # Ruby, 46 ``` s=0.0 $<.bytes{|b|s+=b;$><<'%c'%(0.5+s/$.+=1)} ``` [ideone](https://ideone.com/FmKAjX). With apologies to w0lf, my answer ended up different enough that it seemed worth posting. `$<.bytes` iterates over each byte in stdin, so we print the rolling average in each loop. '%c' converts a float to a character by rounding down and taking the ASCII, so all we have to do is add 0.5 to make it round properly. `$.` is a magic variable that starts off initialized to 0--it's supposed to store the line count, but since here we want byte count we just increment it manually. [Answer] # JavaScript (ES6), 75 bytes ``` let f = s=>s.replace(/./g,x=>String.fromCharCode((t+=x.charCodeAt())/++i+.5),i=t=0) ``` ``` <input oninput="O.value=f(this.value)" value="Hello!"><br> <input id=O value="HW^adY" disabled> ``` I can't believe there's no JS answer with this technique yet... [Answer] # [Python 2](https://docs.python.org/2/), 65 bytes ``` f=lambda s:s and f(s[:-1])+chr(int(sum(map(ord,s))*1./len(s)+.5)) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRodiqWCExL0UhTaM42krXMFZTOzmjSCMzr0SjuDRXIzexQCO/KEWnWFNTy1BPPyc1T6NYU1vPVFPzf0ERUBFQm7pHak5OvqK6poKygkd4XGJK5H8A "Python 2 – Try It Online") [Answer] # Ruby, 27 bytes ``` putc gets.sum.quo(~/$/)+0.5 ``` Solution produced through some collaborative golfing at work. ## How this works * `Kernel#putc` prints a single character (e.g. `putc "Hello"` outputs `H`). Passing an object to it prints the character whose code is the least-significant byte of the object. So `putc 72` outputs `H`. * `Kernel#gets` reads stdin and returns a string. * `String#sum` returns a checksum. The result is the sum of the binary value of each byte in the string modulo `2**16 - 1`. Since ASCII bytes comfortably fit in this space, this just returns the byte total. * Because the byte total is an integer, we can’t do floating point calculations (in Ruby `10 / 3` is `3` whereas `10.to_f / 3` is `3.33…`). Here’s where `Numeric#quo` comes in – `10.quo(3)` returns the Rational `(10/3)`. * `Regexp#~` matches a regular expression against the contents of `$_` (the last string read by `gets`). It returns index of the match. * The Regexp `/$/` matches the end of the string, so `~/$/` means “print the index of the end of the string” – in other words, the string length. This gives us the final is a short-hand for the length of the string read by `gets`. * This gives us the Rational (byte total/string length). Now we need to round it into an integer. `+0.5` casts the Rational to a float. `putc` floors the float into an integer. [Answer] # K, 36 bytes ``` `0:_ci_.5+{(+/x)%#x}'.0+1_|(-1_)\_ic ``` Usage: ``` `0:_ci_.5+{(+/x)%#x}'.0+1_|(-1_)\_ic"Hello!" HW^adY `0:_ci_.5+{(+/x)%#x}'.0+1_|(-1_)\_ic"test" tmop `0:_ci_.5+{(+/x)%#x}'.0+1_|(-1_)\_ic"42" 43 `0:_ci_.5+{(+/x)%#x}'.0+1_|(-1_)\_ic"StackExchange" Sdccd_ccccddd ``` `_ci` and `_ic` convert ascii to chars and vice versa, respectively. `{(+/x)%#x}` is a classic K idiom for calculating a mean. Pretty straightforward overall. Edit: oh, misread the spec. `0: is needed to print the result to stdout. Waiting for clarification on input re. Dennis' question. [Answer] ## Python 2, 71 ``` i=s=0 r='' for c in input():s+=ord(c);i+=1.;r+=chr(int(s/i+.5)) print r ``` With each new character, updates the character sum `s` and the number of characters `i` to compute and append the average character. [Answer] # Mathematica, 75 bytes ``` FromCharacterCode@Floor[.5+Accumulate@#/Range@Length@#]&@ToCharacterCode@#& ``` [Answer] # Julia, ~~85~~ 81 bytes ``` s->(i=[int(c)for c=s];print(join([char(iround(mean(i[1:j])))for j=1:length(i)]))) ``` This creates an unnamed function that accepts a string and creates a vector of its ASCII code points. Means are taken for each sequential group, rounded to integers, converted to characters, joined into a string, and printed to STDOUT. [Answer] # Mathcad, 60 "bytes" [![enter image description here](https://i.stack.imgur.com/BmOAh.jpg)](https://i.stack.imgur.com/BmOAh.jpg) Mathcad is mathematical application based on 2D worksheets comprised of "regions" each of which can be text, a mathematical expression, program, plot or scripted component. A mathematical or programming instruction is picked from a palette toolbar or entered using a keyboard shortcut. For golfing purposes, an operation ("byte") is taken to be the number of keyboard operations necessary to create a name or expression (for example, to set the variable a to 3, we would write a:=3. The definition operator := is a single keypress ":", as are a and 3 giving a total of 3 "bytes". The programming ***for*** operator requires typing ctl-shft-# (or a single click on the programming toolbar) so again is equivalent to 1 byte. In Mathcad the user enters programming language commands using keyboard shortcuts (or picking them from the Programming Toolbar) rather than writing them in text. For example, typing ctl-] creates a while-loop operator that has two "placeholders" for entering the condition and a single line of the body, respectively. Typing = at the end of a Mathcad expressions causes Mathcad to evaluate the expression. (Count bytes) By looking at it from a user input perspective and equating one Mathcad input operation (keyboard usually, mouse-click on toolbar if no kbd shortcut) to a character and interpreting this as a byte. csort = 5 bytes as it's typed char-by-char as are other variable/function names. The for operator is a special construct that occupies 11 characters (including 3 blank "placeholders" and 3 spaces) but is entered by ctl-shft-#, hence = 1 byte (similar to tokens in some languages). Typing ' (quote) creates balanced parentheses (usually) so counts as 1 byte. Indexing v = 3 bytes (type v[k). [Answer] # [Japt](https://github.com/ETHproductions/japt/), 11 bytes ``` c@V±X /°T r ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=Y0BWsVggL7BUIHI=&input=IkhlbGxvISI=) [Answer] **PHP**, **176 byte** ``` <?=(implode('',array_reduce(str_split($argv[1]),function($c,$k){array_push($c[1],chr(floor(((ord($k)+$c[0])/(count($c[1])+1))+0.5)));return[ord($k)+$c[0],$c[1]];},[0,[]])[1])); ``` Example: ``` >php cg.php Hello! HW^adY >php cg.php test tmop >php cg.php 42 43 ``` The biggest solution so far, but based on php it can't get much shorter I think. 2 bytes could be saved by removing the newlines. [Answer] # [Zig](https://ziglang.org) 0.6.0, 84 bytes ``` fn a(b:[]u8)void{var t:u64=0;for(b)|c,i|{t+=c;b[i]=@intCast(u8,(t+(i+1)/2)/(i+1));}} ``` [Try it Online](https://godbolt.org/z/zoPvbW) Formatted: ``` fn a(b: []u8) void { var t: u64 = 0; for (b) |c, i| { t += c; b[i] = @intCast(u8, (t + (i+1)/2) / (i+1)); } } ``` [Answer] # PHP 7, 79 bytes As I don't have enough reputation to comment on cb0's answer to provide him hints to improve his answer (mainly using the char index method in a string and while to loop through a string). But I still bothered to post it due to the large reduction in byte count. ``` <?php $i=$b=0;while($a=ord($argv[1][$i++]??'')){$b+=$a;echo chr(round($b/$i));} ``` I didn't find a way though to use the `<?=` shortcut and avoid undefined errors without using command line flags (this is why i used `$i=$b=0;`). This answer does not work in PHP 5 due to the `??` syntax. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 7 bytes ``` CKvṁ.+C ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwiQ0t24bmBLitDIiwiIiwiSGVsbG8hIl0=) `.+` should be `ṙ`, but there's a bug. [Answer] # [Knight](https://github.com/knight-lang/knight-lang), 62 bytes ``` ;;=sP=i 0W<=i+1i+1Ls;=aGs=t 0i;Wa;=t+tAa=aGa 1LaO+A/+t/i 2i"\" ``` [Try it online!](https://tio.run/##rVltU9tIEv5s/4rBKWzJloMkuKotyzJFssBRRyALyeUD@BIhyzC1suyTZFiOkL@e6@550cg2ucvdUinLmumXp1@mu8eJ@7dx/P0Vz@J0OUmGRTnh89d3o6a5kvKb2lJcPi6SFaKcZ7e1pZLPBM0kmfIsYWnK0nl2Sx9Nvfrh7OM75lWvlx8umF@9/v3ggu1Vr0dnb9kv1evFR@ZVxEenlwbt2cdTg/Tj2buDy79Zhc0s/Gizb95fbL17cAlqxWZ8F@Wsa1cMJhVg1SJGI7ZX7Z0dfsLNDDbJoq8Mvw@HKzSohmjQTKBJUxsJazRvzs9PiQg/9snIAdpmALk4FgTAb2C9j9JlYttX2dhuNskOiMrVOLxoHZ4fWd@DICzeh5y5n4Yh73nw77QIwui4CEvm8uBTFIRlrzyIYCli3ml03jvY6ZU7nPm8dd36boOQViDkdkFwEs1YiBqCZhNgLKK8SCybPTUbPCsZD5oNWCVIDutOl1kMK8Qcw3s5WzjFIrvyx@GT67jPIKPBQRzRw9PFhZ0dFM8X7OGOl0mxiOKk2YDvaWLBOrBbAobDWtfldXY9vc7Z0/PV2LIHr1o2QWnwKbM02pB1XnVsJkSo1S1Yvc5gudcTK4CzkaRFYi48CzjxXRL/zqbznGXL2U2SFxIPs3gx4be8VFJBO5rjOdoi8ewyz2U91pXIez2b9VnH7YAKRMptliflMs@YSiLBRnkUrGK4j3Ie3aSJQgEg0vlDklsx6FNA2NevTIGL6S0mR3zu2NI9fIPpPPQciFGol1fQ4bGU6Qsk2WS5sDCkTPq0z@BtHbAoEoWQJmBcdzoVplZHBA2YwQINioEQKCrwHZAtoqJk5V0CwqK8BGIZgK7yKAY0ttESBdY4ay@ChU/PpkA3KmcQfEzdks8zgI0Z644BWqw8UiwXC3S4rbJKrZjuN/MP3G44G2WoVF5kkMdQ4DBzJXLhlQ8dXQXEwhEuYLEbYJFDmCrJqD4KUy3EjVCjNJ3H1p7reDYaiMvaCDIwW6ZplD@ahlbxuTDC876jkZFCyb/MVrhJhYcqZFHYZOnB4Zu3X37bOv31/JthsSn3hm8U7K8L3qpJPj65fEFimeQkMsom7J/LSL2i2HtTxe66CuGB4452xskGZxDzXp25TvNMtTJfZhiiQFbpbjkvLFUs6QRAbpc8ZrR7s5xe@XtjiUNEuk31QQMoFnCuyqkFpGD/dppOWqrwUJdyUMiqADgVWoDof0J/jW7IvN26nWg8JuM@a5X5MmlBEup1zElYn0ZQQnCjhanVqpyAdqLtslGROz6/mc9T2Lmpe@BFWyuzfmRQ9@ctMmHerMFMEWP2p2KEpC3naWqZUB3mOtAi/gfI2RpkbMPvDt6fOdiMRaLB68mV57oupBOYAq/qreD/Sj6XDB@BkaOGtegBeHPww6fP3dBTPR1LHLZ1fNCnLx67QHB0cnrYZVOojkFDp7bUh3U4jhZOmmQ0Ahi@UnOU8Bmcu5ecscqIzQl7G3Yci9MwAc14SL4IoKtw3NR1I54tViJATuLjqoSgm/gY1RQPvIzvrC54Zm3sAh8x@Rdjo@ocdAYMtQiCEB2KgxuUYbtNRknxcnSspawdUBuuKGg@LXPsXTSiXo3tpyrNYIKi4i4UX4DiuuwcKp5lt90/pvhXUb4HSpAqfHSblClMl1abYtnGCGGPnPDMDvjUsiieOBHEdzlicSBPbVuEOXSDjVjhYdMcIPQdCn1idMRqIB0SKLzoJFk7K5RvKnsEvd55W@0gp@liTfMFaDAbIP/CxXyRZJah2GnlLZoVAFU4E60S8jH03b1faF1OF5YYSaYAfYJGwQwHKevggAfkMDzQG@oA1Sq9LFhkvZBmITyxQGlLd4Mc0kWuRgndkPnm0FK5sbLkN7Ak@QPmODzta3Zu1aJOl4gtrGRrhKdr6QFa0rpfDPJfOwM5KG5IZF35ZAdqndFcbGEPslUTGo327GqyXCuHivWSpkNru0DG@mFYZwZ3wuxj6oVKarcqUrWB7SWJMin2pRYme5YZAVlbpBfOKy/gwRA3H3SaiGfNdazdpptXv4@kYzHnXtO83VCwtl93C8BjwZvN1FHLDfjLslDR1zkhhj0BqKcBUZ2EeoklGVPLCI8Ypxv1aItrLFLD4M9ULvki5jgA02EQASAqXMZTHiorfXtzqsZRqR5y7PR6lZts9R1l2TCOOvQsZY2QdvXXstPIdpzV63gFU7eKzgYvrLbnDX7orvlBxHWTF2YbTOsSTWgKIQboQRZVyLBzDbc8JAr6fZInHUUtczXQwqNl7fTv/NAxO5sds/1Dpu3NTN/WmL5trDj/IK/XDBd3DFrzTW8EMjwiOiHrezoaRAsh8uA89j04i55J7P8k9RDKaI02DJGU9A7UiqtCQwHxR66MiW/TWNMNKU7N1YNDm2QK3CWoEGMrgu94tbhL8qRTsGwOszZPS56xh@gR/Msmc7i8lsltkgPPYp4lWckjvG3AiZ@zh4TdRfcJEEpBSF6yWZQtIc0eX@MqWneDHgdXkCeKZVrirwukXBdGRdI3aZTKFZeZfJpkRTzKe5nSfRmIJhvWqFy6yEcp9tBHsDqbpMmEfalgf9FSnvCbGOAMJZUxIxTW76t3m8gbkrRrQH/W9XJIybrSILE41upnWK@e@8wsEkPzuCDrQP6Q12aCYJ/VBkpadJhRNVGGKzhVa/ZFv0DarRC6kjEtjeAcYmrNJ/MBmyWzeIFplrHRl/3/15TRn2DKSJmytcGWUNoiTdl/2ftC6wbIuL3PagS@pvBVo93ahLN60eapymMK0PDaVcVDWzb1kH2TU5YSzf/1v@GXNcgQo/mDzsCkro3Dq7RhVXXr2z994VEzcHXjQbpG7dajSyHRoMRxWOM2yiRyIEWvp9kE5E9gnvh5zBxIa9Yxc8aRbCf16R5JDf59f7BruOVYXC1CYxLrmQ1o/S6VyQuKo8/Cbm3wvRSOXhEarLY8f1PL27X1vOBr7j1a/A@DEwLDJ4Yi1pcEPTaZM5QPFqLWnofDFA0SIv/FJj2IoidPAmifJNMIiiRYpiZRnsEmn9CPTVFcQpvqbMcdnE1xxWYv3HZRmO6BMDXKHxxmEc9wqGVRfhs7JLTbhe/3Nv6sRfdQ/H8hyyU09eve8/e/JmDw1r8B "C (gcc) – Try It Online") [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 15 bytes ``` .pvyDSÇOsg/îç}J ``` [Try it online!](http://05ab1e.tryitonline.net/#code=LnB2eURTw4dPc2cvw67Dp31K&input=SGVsbG8h) [Answer] # [Japt](https://github.com/ETHproductions/japt), 13 bytes ``` £T±Xc)/°Y r d ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=o1SxWGMpL7BZIHIgZA==&input=IkhlbGxvISI=) ### How it works ``` £ T± Xc)/° Y r d mXY{T+=Xc)/++Y r d} // Implicit: U = input string, T = 0 mXY{ } // Replace each char X and index Y in the string by this function: T+=Xc // Add X.charCodeAt() to T. )/++Y // Take T / (Y + 1). r d // Round, and convert to a character. // Implicit: output result of last expression ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` OÆmƤ+.Ọ ``` [Try it online!](https://tio.run/##y0rNyan8/9//cFvusSXaeg939/z//98DKJivCAA "Jelly – Try It Online") ``` OÆmƤ+.Ọ O - Get a list of character codes from the input string Ƥ - Over prefixes: Æm - Get the mean +. - To each, add 0.5 Ọ - Convert from character codes to charcters. Decimals are rounded down. ``` [Answer] # brev, 146 bytes ``` (as-list reverse(c pair-fold-right(fn(cons(integer->char(inexact->exact(floor(+(/(apply + x)(length x))0.5))))y))'())reverse(c map char->integer)) ``` 124 with banker's rounding: ``` (as-list reverse(c pair-fold-right(fn(cons(integer->char(round(/(apply + x)(length x))))y))'())reverse(c map char->integer)) ``` Which is still a lot. It's clear that a huge painpoint in brev is the type converting (chars to integers, strings to lists etc). [Answer] # [Dart](https://www.dartlang.org/), 76 bytes ``` t(a,[c=1,s=0])=>String.fromCharCodes([...a.runes.map((i)=>(s+=i+.5)~/c++)]); ``` [Try it online!](https://tio.run/##RZA9b8MgEIb3/AqKOoDs0PRrcsgSVeqeoaosN0JAbFQbLMBRpcj96@7ZsZsbOODe5@4FJXwchkhEmkv@mAa@KSjfHaI3tmQn75p9JfzeKR1IzhgTzHdWB9aIlhADShISbhL2Sn8fZJLQgmbD2RmFGmEsoeiyQhBn4ZGxbRcD4ijH77qu3R1OEY46xDG/PI3rIQr5/fYjK2FLjYvsn3VdvMEfX0J9TnDj2gl@nmAlpTpKCKXUAp@cJ9NwQDcZpO3sg9XalrGCKzA9u1ymRd20oL8KczO3GqOFX4kE319GSY/WOwRbMh5oj@lNJ0LQHgrXEuJ8eQF0m2X9qh/@AA "Dart – Try It Online") [Answer] # [J](http://jsoftware.com/), 22 bytes ``` (0.5<.@++/%#)\&.(3&u:) ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NQz0TG30HLS19VWVNWPU9DSM1UqtNP9rcqUmZ@QrpCmoe6Tm5OQrqsP5JanFJQieiRGCHVySmJztWpGckZiXnqr@HwA "J – Try It Online") ## Explanation ``` (0.5<.@++/%#)\&.(3&u:) &.( ) do this, the left verb then the inverse of this: 3&u: characters -> ordinates ( )\ over the prefixes of the input: +/%# take the average (sum divide length) 0.5 + add one-half <.@ then floor ``` [Answer] # Matlab, ~~43~~ 31 bytes *Thanks to [@beaker](https://codegolf.stackexchange.com/users/42892/beaker) for 9 bytes off!* Using an anonymous function: ``` @(s)[cumsum(+s)./find(s)+.5 ''] ``` Examples: ``` >> @(s)[cumsum(+s)./find(s)+.5 ''] ans = function_handle with value: @(s)[cumsum(+s)./(find(s))+.5 ''] >> f=ans; >> f('Hello!') ans = 'HW^adY' >> f('test') ans = 'tmop' >> f('42') ans = '43' >> f('StackExchange') ans = 'Sdccd_ccccddd' ``` [Answer] ### Ruby 59 ~~61~~ ``` ->w{s=c=0.0;w.chars.map{|l|s+=l.ord;(s/c+=1).round.chr}*''} ``` Test: <http://ideone.com/dT7orT> ]
[Question] [ Write a function which, given the first 12 digits of an [ISBN-13](https://en.wikipedia.org/wiki/International_Standard_Book_Number#ISBN-13_check_digit_calculation) code, will calculate the entire ISBN via calculating and appending an appropriate check digit. Your function's input is a string containing the first 12 digits of the ISBN. Its output is a string containing all 13 digits. ## Formal specification Write a function which, when given a string *s* consisting entirely of exactly 12 decimal digits (and no other characters), returns a string *t* with the following properties: * *t* consists of exactly 13 decimal digits (and no other characters); * *s* is a prefix of *t*; * the sum of all digits in odd positions in *t* (i.e. the first, third, fifth, etc.), plus three times the sum of all digits in even positions in *t* (i.e. the second, fourth, sixth, etc), is a multiple of 10. ## Example / test case **Input** `978030640615` **Output** `9780306406157` ## Victory condition As a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, the shortest answer wins. [Answer] ## Golfscript - 25 chars ``` {...+(;2%+{+}*3-~10%`+}:f ``` Whole program version is only 19 chars ``` ...+(;2%+{+}*3-~10% ``` Check back here for analysis later. Meanwhile check out my old uninspired answer **Golfscript - 32 chars** Similar to the luhn number calculation ``` {.{2+}%.(;2%{.+}%+{+}*~)10%`+}:f ``` Analysis for 978030640615 ``` {...}:f this is how you define the function in golfscript . store an extra copy of the input string '978030640615' '978030640615' {2+}% add 2 to each ascii digit, so '0'=>50, I can get away with this instead of {15&}% because we are doing mod 10 math on it later '978030640615' [59 57 58 50 53 50 56 54 50 56 51 55] . duplicate that list '978030640615' [59 57 58 50 53 50 56 54 50 56 51 55] [59 57 58 50 53 50 56 54 50 56 51 55] (; trim the first element off '978030640615' [59 57 58 50 53 50 56 54 50 56 51 55] [57 58 50 53 50 56 54 50 56 51 55] 2% select every second element '978030640615' [59 57 58 50 53 50 56 54 50 56 51 55] [57 50 50 54 56 55] {.+}% double each element by adding to itself '978030640615' [59 57 58 50 53 50 56 54 50 56 51 55] [114 100 100 108 112 110] + join the two lists together '978030640615' [59 57 58 50 53 50 56 54 50 56 51 55 114 100 100 108 112 110] {+}* add up the items in the list '978030640615' 1293 ~ bitwise not '978030640615' -1294 ) add one '978030640615' -1293 10% mod 10 '978030640615' 7 ` convert to str '978030640615' '7' + join the strings '9780306406157' ``` [Answer] ## Python - 44 chars ``` f=lambda s:s+`-sum(map(int,s+s[1::2]*2))%10` ``` Python - 53 chars ``` def f(s):d=map(int,s);return s+`-sum(d+d[1::2]*2)%10` ``` [Answer] ## Haskell - 54 characters ``` i s=s++show(sum[-read[c]*m|c<-s|m<-cycle[1,3]]`mod`10) ``` This requires support for [parallel list comprehensions](http://cvs.haskell.org/Hugs/pages/users_guide/hugs-ghc.html#ZIP-COMPREHENSION), which is supported by GHC (with the `-XParallelListComp` flag) and Hugs (with the `-98` flag). [Answer] ## APL (27 characters) ``` F←{⍵,⍕10|10-(12⍴1 3)+.×⍎¨⍵} ``` I'm using Dyalog APL as my interpreter. Here's a quick explanation, mostly from right to left (within the function definition, `F←{ ... }`): * `⍎¨⍵`: Execute/evaluate (`⍎`) each (`¨`) character given in the right argument (`⍵`). * `(12⍴1 3)`: Reshape (`⍴`) the vector `1 3` into a `12`-element vector (repeating to fill the gaps). * `+.×`: Take the dot product (`+.×`) of its left argument (`(12⍴1 3)`) and its right argument (`⍎¨⍵`). * `10-`: Subtract from 10. * `10|`: Find the remainder after division by `10`. * `⍕`: Format the number (i.e., give a character representation). * `⍵,`: Append (`,`) our calculated digit to the right argument. [Answer] ## PHP - ~~86~~ ~~85~~ 82 chars ``` function c($i){for($a=$s=0;$a<12;)$s+=$i[$a]*($a++%2?3:1);return$i.(10-$s%10)%10;} ``` Re-format and explanation: ``` function c($i){ // function c, $i is the input for($a=$s=0;$a<12;) // for loop x12 - both $a and $s equal 0 // notice there is no incrementation and // no curly braces as there is just one // command to loop through $s+=$i[$a]*($a++%2?3:1); // $s (sum) is being incremented by // $ath character of $i (auto-casted to // int) multiplied by 3 or 1, depending // wheter $a is even or not (%2 results // either 1 or 0, but 0 == FALSE) // $a is incremented here, using the // post-incrementation - which means that // it is incremented, but AFTER the value // is returned return$i.(10-$s%10)%10; // returns $i with the check digit // attached - first it is %'d by 10, // then the result is subtracted from // 10 and finally %'d by 10 again (which // effectively just replaces 10 with 0) // % has higher priority than -, so there // are no parentheses around $s%10 } ``` [Answer] ## Windows PowerShell, 57 ``` filter i{$_+(990-($_-replace'(.)(.)','+$1+3*$2'|iex))%10} ``` [Answer] ## Haskell, ~~78~~ ~~71~~ 66 characters ``` i s=s++(show$mod(2-sum(zipWith(*)(cycle[1,3])(map fromEnum s)))10) ``` [Answer] ## Ruby - ~~73~~ 65 chars ``` f=->s{s+((2-(s+s.gsub(/.(.)/,'\1')*2).bytes.inject(:+))%10).to_s} ``` [Answer] **C# (94 characters)** ``` string I(string i){int s=0,j=0;for(;j<12;)s+=(i[j]-48)*(j++%2<1?1:3);return i+((10-s%10)%10);} ``` With linebreaks/whitespace for readability: ``` string I(string i) { int s = 0, j = 0; for (; j < 12; ) s += (i[j] - 48) * (j++ % 2 < 1 ? 1 : 3); return i + ((10 - s % 10) % 10); } ``` Tested on several ISBNs from books on my shelf, so I know it's working! [Answer] **Python - ~~91~~, 89** ``` 0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 | | | | | | | | | | def c(i):return i+`(10-(sum(int(x)*3for x in i[1::2])+sum(int(x)for x in i[::2]))%10)%10` ``` [Answer] ## C# – ~~89~~ 77 characters ``` string I(string s){return s+(9992-s.Sum(x=>x-0)-2*s.Where((x,i)=>i%2>0).Sum(x=>x-0))%10;} ``` Formatted for readability: ``` string I(string s) { return s + (9992 - s.Sum(x => x - 0) - 2 * s.Where((x, i) => i%2 > 0).Sum(x => x - 0) ) % 10; } ``` We do not multiply by one or three, we just add everything, plus we add all even-placed characters one more time, multiplied by two. 9992 is large enough so that the sum of all ASCII characters is less than that (so that we may mod by 10 and be sure the result is positive, no need to mod by 10 twice), and is not divisible by zero because we add up all those extra 2\*12\*48 (twelve ASCII digits, weighed by 1 and 3) == 1152, which allows us to spare one extra character (instead of twice subtracting 48, we subtract 0 just to convert from char to int, but instead of 990, we need to write 9992). But then again, even though much less beautiful ;-), this old-school solution gets us to 80 characters (but this is almost C-compatible): ``` string T(string i){int s=2,j=0;for(;j<12;)s+=i[j]*(9-j++%2*2);return i+s%10;} ``` [Answer] ## J - 55 45 38 ``` f=:3 :'y,":10|10-10|+/(12$1 3)*"."0 y' ``` eg ``` f '978030640615' 9780306406157 ``` old way: ``` f=:,":@(10(10&|@-)(10&|@+/@((12$1 3)*(i.12)&(".@{)))) ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~29~~ 28 bytes ``` {$_~:1[.comb «*»(9,7)]%10} ``` [Try it online!](https://tio.run/##DcNRCoJAEADQq8yHikrI7M7szE5UF4mQivZLMexLoi7UEfrzYlsP3v02D5LHBaoE@/ws@vfWHbvrNF5g/bTrt7aNNqfS4Ss/zgukuugbSNMMO9OIhMIoLoAEUi//RhGcobcgkZU9GLEohajq@ZB/ "Perl 6 – Try It Online") [Answer] ## Ruby - 80 characters ``` def f s;s+(10-s.bytes.zip([1,3]*6).map{|j,k|(j-48)*k}.inject(:+)%10).to_s[0];end ``` [Answer] ## dc, 44 chars ``` [d0r[I~3*rI~rsn++lndZ0<x]dsxx+I%Ir-I%rI*+]sI ``` Invoke as `lIx`, e.g: ``` dc -e'[d0r[I~3*rI~rsn++lndZ0<x]dsxx+I%Ir-I%rI*+]sI' -e '978030640615lIxp' ``` [Answer] # Q, 36 chars ``` {x,-3!10-mod[;10]sum(12#1 3)*"I"$'x} ``` [Answer] ## Perl, 53 chars ``` sub i{($_)=@_;s/(.)(.)/$s+=$1+$2*3/ger;$_.(10-$s)%10} ``` [Answer] **D - 97 characters** ``` auto f(string s){int n;foreach(i,c;s)n+=((i&1)*2+1)*(c-48);return s~cast(char)((10-n%10)%10+48);} ``` Formatted more legibly: ``` auto f(string s) { int n; foreach(i, c; s) n += ((i & 1) * 2 + 1) * (c - 48); return s ~ cast(char)((10 - n % 10) % 10 + 48); } ``` The verbosity of D's cast operator definitely makes it harder to write obsessively short code though. [Answer] **Java - 161 Characters** :( ``` int b[]=new int[a.length]; int d=0,n=0,j=1; for(char c:a.toCharArray())b[d++]=Integer.valueOf(c+""); for(int i:b)n+=(j++%2==0)?(i*3):(i*1); return a+(10-(n%10)); ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 18 [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 string as argument. Using [Bubbler's approach](https://codegolf.stackexchange.com/a/174553/43319). ``` ⊢,∘⍕10|⍎¨+.×9 7⍴⍨≢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HXIp1HHTMe9U41NKh51Nt3aIW23uHplgrmj3q3POpd8ahz0f@0R20TgDKP@qZ6@j/qaj603vhR20QgLzjIGUiGeHgG/09TULc0tzAwNjAzMTAzNFUHAA "APL (Dyalog Unicode) – Try It Online") `≢` length of argument (12) `9 7⍴⍨` cyclically reshape `[9,7]` to that length `+.×` dot product of the following with that: `⍎¨` `evaluate each character `10|` mod-10 of that `,∘⍕` prepend the following the the stringification of that: `⊢` the unmodified argument [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` SιO`3*+θTα« ``` [Try it online](https://tio.run/##yy9OTMpM/f8/@NxO/wRjLe1zO0LObTy0@v9/S3MLA2MDMxMDM0NTAA) or [verify a few more test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn2ly//gczv9E4y1tM/tCDm38dDq/zr/Lc0tDIwNzEwMzAxNucxMjc2NzIDY0tiCy9DSwMjS1MzCxNzEiMvS2MTM3NjUwtzcyAQA). **Explanation:** ``` S # Convert the (implicit) input to a list of digits # i.e. 978030640615 → [9,7,8,0,3,0,6,4,0,6,1,5] ι # Uninterleave it # → [[9,8,3,6,0,1],[7,0,0,4,6,5]] O # Sum each inner list # → [27,22] ` # Push them both separated to the stack 3* # Multiply the top one by 3 # → 66 + # Sum them together # → 93 θ # Only leave the last digit # → 3 Tα # Take the absolute difference of this digit with 10 # → 7 « # And append this digit to the (implicit) input # → 9780306406157 # (after which it is output implicitly as result) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` ⁽Tẇ∑N₀%J ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigb1U4bqH4oiRTuKCgCVKIiwiIiwiOTc4MDMwNjQwNjE1Il0=) Port of Jelly ## Explained ``` ⁽Tẇ∑N₀%J ⁽Tẇ # Triple every second digit ∑N # -sum of that ₀% # modulo by 10 J # append that result to the original input ``` [Answer] # Q (44 chars) ``` f:{x,string 10-mod[;10]0+/sum@'2 cut"I"$/:x} ``` [Answer] ## Scala 84 ``` def b(i:String)=i+(10-((i.sliding(2,2).map(_.toInt).map(k=>k/10+k%10*3).sum)%10)%10) ``` Testing: ``` val isbn="978030640615" b(isbn) ``` Result: ``` "9780306406157" ``` [Answer] # C, 80 79 characters The function modifies the string in place, but returns the original string pointer to satisfy the problem requirements. ``` s;char*f(char*p){for(s=2;*p;s+=7**p++)s+=9**p++;*p++=48+s%10;*p=0;return p-13;} ``` Some explanation: Instead of subtracting 48 (the ASCII value of the digit `0`) from each input character, the accumulator `s` is initialized so that it is modulo 10 equal to 48+3\*48+48+3\*48...+48+3\*48 = 24\*48 = 1152. The step `10-sum` can be avoided by accumulating `s` by subtraction instead of addition. However, the module operator `%` in C would not give a usable result if `s` was negative, so instead of using `s-=` the multipliers 3 and 1 are replaced by -3=7 modulo 10 and -1=9 modulo 10, respectively. Test harness: ``` #include <stdio.h> #define N 12 int main() { char b[N+2]; fgets(b, N+1, stdin); puts(f(b)); return 0; } ``` [Answer] # Groovy 75, 66 chars ``` i={int i;it+(10-it.inject(0){t,c->t+(i++&1?:3)*(c as int)}%10)%10} ``` use: ``` String z = "978030640615" println i(z) -> 9780306406157 ``` [Answer] ### APL (25) ``` {⍵,⍕10-10|+/(⍎¨⍵)×12⍴1,3} ``` [Answer] # Powershell, ~~55~~ ~~53~~ 52 bytes *Inspired by [Joey's answer](https://codegolf.stackexchange.com/a/791/80745). I'm impressed with her regex.* ``` "$args"+($args-replace'(.)(.)','+40-$1-3*$2'|iex)%10 ``` ## Powershell, 55 bytes, whithout regex ``` param($s)$s[1,3,5,7,9,11*2+0..11]|%{$r+=58-$_};$s+$r%10 ``` Explanation: * the index range = (the even positions `1,3,5,7,9,11` repeated 2 times + all positions `0..11`) * `$r+=58-$_` makes a sum of supplements up to `10+[char]'0'` * `$s+$r%10` outputs the result Test script: ``` $f = { param($s)$s[1,3,5,7,9,11*2+0..11]|%{$r+=58-$_};$s+$r%10 } @( ,("978030640615" , "9780306406157") ) | % { $s,$expected = $_ $result = &$f $s "$($result-eq$expected)" $s $result } ``` Output: ``` True 978030640615 9780306406157 ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~78~~ 76 bytes ``` lambda n:n+`10-(sum(int(a)+3*int(b)for a,b in zip(n[::2],n[1::2]))%10or 10)` ``` [Try it online!](https://tio.run/##XY7RCoIwFIav3VPsJraTCzYtrcGexAQnKQk6xc2Levnlkoi6Ov8HH@f/p4e7jybxrbr6Xg/1TWMjTVwJfqB2GWhnHNUQp/sQamjHGWtW487gZzdRU0iZlMwUIlyAneCrIDhU3jXWWVWgiJJLfuYpz448EyfC8A/nBNjXSf@cjTkBVCIUusNXhufGLr0LI94tEkXTvO7DLQ0M7BOU2kz/Ag "Python 2 – Try It Online") Takes a string as an argument. # Explanation: Using python slice notation, converts a string into a list of character pairs. ("978030640615" -> [("9","7"), ("8", "0"), ("3", "0"), ("6", "4"), ("0", "6"), ("1", "5")] ) For that list of pairs, converts each item into an integer and returns a+3b. Sums all the results. Gets the sum modulo 10, OR 10 if the remainder is 0. (This prevents the final digit from being 10 instead of 0.) Removes the remainder from 10 to get the check digit. Converts the calculated check digit to a string via deprecated backtick expression. Returns the original number plus the calculated check digit. # Edit: Saved 2 byes by removing spaces (thanks [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king)!). [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 25 bytes ``` dn[A~9z^8+*rd0<M+]dsMxA%p ``` [Try it online!](https://tio.run/##S0n@b2luYWBsYGZiYGZo@j8lL9qxzrIqzkJbqyjFwMZXOzal2LfCUbXg/38A "dc – Try It Online") I know there's already a dc answer here, but 25<44 so I guess I feel 19 bytes of okay about it. This uses the fact that `8+9^z` is equivalent to either `-3` or `-1` mod 10 depending on whether z is even or odd. So I use `A~` to break the number into digits on the stack, but as I build the stack I multiply each digit by `8+9^z` where z is the current stack size. Then I add them all as the *function* stack unrolls, and print the last digit. ]
[Question] [ ## Goal Given a non-negative integer, create a function that returns the starting position of number of largest consecutive 1's in that integer's binary value. When given an input `0`, return `0`. If the number has multiple streaks of equal length, you must return the position of the last streak. ## Input An integer greater than **or equal to** 0. ## Output An integer calculated as explained below. ## Rules * This is code-golf, so the shortest code in bytes in each language wins. * Standard loopholes are forbidden. --- ## Examples and Test Cases ### Example 1 * Your function is passed the integer 142 * 142 is equal to 10001110 in binary * Longest streak is "111" (a streak of three ones) * The streak starts at the 2^1 position * **Your function returns 1 as the result** ### Example 2 * Your function is passed the integer 48 * 48 is equal to 110000 in binary * Longest streak is "11" (a streak of two ones) * The streak starts at the 2^4 position * **Your function returns 4 as the result** ### Example 3 * Your function is passed the integer 750 * 750 is equal to 1011101110 in binary * Longest streak is "111" (a streak of three ones) * Since there are two streaks of equal length, we return the later streak. * The later streak starts at the 2^5 position * **Your function returns 5 as the result** [Answer] # JavaScript (ES6), ~~33~~ 32 bytes ``` f=x=>x&(k=x>>1)?f(x&k):k&&1+f(k) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zbbC1q5CTSPbtsLOzlDTPk2jQi1b0ypbTc1QO00jW/N/cn5ecX5Oql5OfrpGmoaBpiYXqoihiRGGmIkFhpC5KVDrfwA "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), ~~41 40 36~~ 34 bytes *Saved 4 bytes thanks to @ThePirateBay* ``` f=x=>(k=x&x/2)?f(k):Math.log2(x)|0 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zbbC1k4j27ZCrULfSNM@TSNb08o3sSRDLyc/3UijQrPG4H9yfl5xfk4qSEQjTcNAU5MLVcTQxAhDzMQCQ8jcFKj1PwA "JavaScript (Node.js) – Try It Online") ### How? **General case x > 0** We recursively AND the input ***x*** with ***x / 2*** which progressively reduces the patterns of consecutive set bits until only the rightmost bit of the sequence remains. We keep a copy of the last non-zero value and determine the position of its most significant bit by floor-rounding its base-2 logarithm. Below are the steps we go through for ***x = 750*** (***1011101110*** in binary). ``` 1011101110 --. ,----------------' '-> 1011101110 AND 0101110111 ---------- = 0001100110 --. ,----------------' '-> 0001100110 AND 0000110011 ---------- = 0000100010 --. --> output = position of MSB = 5 (0000100010) ,----------------' ^ '-> 0000100010 AND 0000010001 ---------- = 0000000000 ``` **Edge case x = 0** The special case `x = 0` immediately leads to `Math.log2(0) | 0`. The logarithm of `0` evaluates to `-Infinity` and the binary bitwise OR forces a coercion to a 32-bit integer. In compliance with [the specification of the abstract operation **ToInt32**](https://www.ecma-international.org/ecma-262/6.0/#sec-toint32), this gives the expected `0`: > > If *number* is **NaN**, **+0**, **−0**, **+∞**, or **−∞**, return > **+0** > > > [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 8 bytes ``` Ba\ÐƤṀċ¬ ``` [Try it online!](https://tio.run/##AS8A0P9qZWxsef//QmFcw5DGpOG5gMSLwqz/xbzDh@KCrEf//zE0MiwgNDgsIDc1MCwgMA "Jelly – Try It Online") ### How it works ``` Ba\ÐƤṀċ¬ Main link. Argument: n B Binary; convert n to base 2. ÐƤ Apply the link to the left to all postfixes of the binary array. a\ Cumulatively reduce by logical AND. For example, the array [1, 0, 1, 1, 1, 0, 1, 1, 1, 0] becomes the following array of arrays. [1, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 1, 1, 0, 0, 0, 0, 0] [1, 1, 0, 0, 0, 0, 0] [1, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0] [1, 1, 1, 0] [1, 1, 0] [1, 0] [0] Ṁ Take the lexicographical maximum, i.e., the array with the most 1's at the beginning, breaking ties by length. ¬ Yield the logical NOT of n, i.e., 0 if n > 0 and 1 if n = 0. ċ Count the occurrences of the result to the right in the one to the left. ``` [Answer] # x86/x86-64 machine code, 14 bytes (TODO: 13 bytes with input in EAX, return value in EDX). Using [@Arnauld's algorithm](https://codegolf.stackexchange.com/questions/143000/calculate-the-longest-series-of-1s-in-an-integers-binary-value/143004#143004) of `x &= x>>1` and taking the highest set bit position in the step before `x` becomes `0`. Callable from C/C++ with signature `unsigned longest_set(unsigned edi);` in the x86-64 System V ABI. The same machine-code bytes will decode the same way in 32-bit mode, but the standard 32-bit calling conventions don't put the first arg in `edi`. (Changing the input register to `ecx` or `edx` for Windows `_fastcall` / `_vectorcall` or `gcc -mregparm` could be done without breaking anything.) ``` address machine-code bytes global longest_set 1 longest_set: 2 00000000 31C0 xor eax, eax ; 0 for input = 0 3 4 .loop: ; do{ 5 00000002 0FBDC7 bsr eax, edi ; eax = position of highest set bit 6 ;; bsr leaves output unmodified when input = 0 (and sets ZF) 7 ;; AMD documents this; Intel manuals say unspecified but Intel CPUs implement it 8 00000005 89F9 mov ecx, edi 9 00000007 D1E9 shr ecx, 1 10 00000009 21CF and edi, ecx 11 0000000B 75F5 jnz .loop ; } while (x &= x>>1); 12 13 0000000D C3 ret ``` x86's [`BSR` instruction](http://felixcloutier.com/x86/BSR.html) (Bit Scan Reverse) is perfect for this, giving us the bit-index directly, rather than counting leading zeros. (`bsr` doesn't directly produce 0 for input=0 like `32-lzcnt(x)` would, but we need bsr=31-lzcnt for non-zero inputs, so `lzcnt` wouldn't even save instructions, let alone byte count. Zeroing eax before the loop works because of `bsr`'s semi-official behaviour of leaving the destination unmodified when the input is zero.) This would be even shorter if we could return the MSB position of the longest run. In that case, `lea ecx, [rdi+rdi]` (3 bytes) would copy + *left*-shift instead of `mov` + `shr` (4 bytes). See [this TIO link](https://tio.run/##VVLRatswFH3XV5ynkrA02G26lpi0lI5BHjYKYy8roci2HKvIkvGVM2ej3@5Kslun98FG5@qce3x8OZGoUnU815yqvldG7wXZZxJ2zeCqMw0geLfwDw8gQYTCoVLXrcUGEWNLZUy9xqdKkJv/QSKlD4lchk7Q2qA2JK00GqZAKfelGww3GKm0gZgkgasEPwiCaa0f2OrKFFLk@FsKPZnAjOvcswl/vs/f6fc/vjkbWVsJ7Rq2lLTAVluhUHHdckUgfnSSVItMBtXUyQ03Hh5/E2RVK@HZGD1V5uDsZ8PHBITKZkTicPY@fHPhwYC86H8IEU3ZvDr7UgnMOpxt0N3exvOEhcuNsKzfK5NyhWeyvLFseK3ZZAANOf2nhuov8dfdCR7mOlzuxkGFbFyqK6RH6zMswJv94SneLYGfxgqXCbe4Q8kJ978etltkJheIustiyZJJ90O43g1wLrIRPv3lTjw7H2LIuFI4WadT92M8vPuE@Q25uBzYdKQgMEmLTtqZ2wy3NHPWRyxeXbDVDbu@ivo7V28 "Assembly (nasm, x64, Linux) – Try It Online") for an asm caller that does `exit(longest_set(argc-1));` Testing with a shell loop: ``` l=(); for ((i=0;i<1025;i++));do ./longest-set-bitrun "${l[@]}"; # number of args = $i printf "$i %#x: $?\n" $i; l+=($i); done | m 0 0: 0 1 0x1: 0 2 0x2: 1 3 0x3: 0 4 0x4: 2 5 0x5: 2 6 0x6: 1 7 0x7: 0 8 0x8: 3 9 0x9: 3 10 0xa: 3 11 0xb: 0 12 0xc: 2 13 0xd: 2 14 0xe: 1 15 0xf: 0 16 0x10: 4 17 0x11: 4 18 0x12: 4 19 0x13: 0 20 0x14: 4 21 0x15: 4 ... 747 0x2eb: 5 748 0x2ec: 5 749 0x2ed: 5 750 0x2ee: 5 751 0x2ef: 0 752 0x2f0: 4 753 0x2f1: 4 754 0x2f2: 4 ``` --- ## 13 bytes with a custom calling convention We could save a byte by taking the arg in EAX and returning in EDX: then we could use `cdq` (1 byte) to zero the return value in the case where input = 0 (so `bsr` leaves it unmodified). The value in other cases doesn't matter, overwritten by `bsr`. So `cdq` replaces `xor eax, eax`, saving a byte. We do need a `0` in a different register to (not) overwrite; in the non-zero case we can't let `bsr` replace the input value with its log2. So we can't avoid the instruction entirely, and taking input + returning in EAX (like GCC regparm) would mean we'd need to start with `mov edx, eax` or something to copy it somewhere else, while leaving the return value 0 for the input=0 case. [Answer] # [Python 2](https://docs.python.org/2/), 45 bytes ``` f=lambda x:f(x&x/2)if x&x/2else len(bin(x))-3 ``` [Try it online!](https://tio.run/##HcdBDoIwEAXQfU/xV9AmQ9QC0ZDgRYyLEjtxkjoQZFFPXwm795bf9p7Vl8JjCp/pFZAHtrnKJ@@EcSCmb0SKaidRm51r2hIw4nEmtIRL5wnXfk93exrD8wqBKMJgsKyiG4RqNHfUBLbiyh8 "Python 2 – Try It Online") *Saved plenty of bytes thanks to Dennis! (The heads up for `len(bin(...))-3` instead of `math.frexp`)* *Thanks to @xnor for finding a bug, which fortunately was easily fixable!* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ ~~17~~ 11 bytes ``` HÐĿ&\ḟ0ṪBL’ ``` [Try it online!](https://tio.run/##AR4A4f9qZWxsef//SMOQxL8mXOG4nzDhuapCTOKAmf///zA "Jelly – Try It Online") *-6 (!) bytes thanks to @Dennis's keen observations* **How it Works** ``` HÐĿ&\ḟ0ṪBL’ HÐĿ - halve repeatedly until reaching 0 due to rounding &\ - cumulative AND ḟ0Ṫ - final non-zero, or 0 if all elements are 0 BL - length of binary representation (log base 2). 0->[0]->1 ’ - decrement ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ ~~12~~ 11 bytes ``` bDγàŠrkrJgα ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/yeXc5sMLji4oyi7ySj@38f9/c1MDAA) or [run test cases](https://tio.run/##MzBNTDJM/X9u6/8kl3ObDy84uqAou8gr/dzG//@jDU2MdEwsdMxNDXQMYgE). ## Explanation ``` bDγàŠrkrJgα Implicit input (ex: 750) bD Convert input to binary string and duplicate '1011101110', '1011101110' γ Split into groups of 1s or 0s '1011101110', ['1', '0', '111', '0', '111', '0'] à Pull out max, parsing each as an integer '1011101110', ['1', '0', '0', '111', '0'], '111' Šrk Rearrange stack and get first index of max run of ones ['1', '0', '0', '111', '0'], 2 rJg Reverse stack, join the array to a string, and get its length 2, 7 α Get absolute difference 5 ``` [Answer] # [Perl 6](https://perl6.org), ~~45~~ 35 bytes *This highly improved version is courtesy of @nwellnhof.* ``` {.msb+1-(.base(2)~~m:g/1+/).max.to} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYKvwv1ovtzhJ21BXQy8psThVw0izri7XKl3fUFtfUy83sUKvJL/2vzVXcSJIvYZKvKZCWn6RgqGJkY6JhY65qcF/AA "Perl 6 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~89~~ 78 bytes ``` m=t=i=j=0 for c in bin(input()): t=-~t*(c>'0');i+=1 if t>m:j=i;m=t print i-j ``` [Try it online!](https://tio.run/##Fc1BDoIwEADA@75iw4VWQ0IJRlKyvMIXWEvYRkrTLFEvfr3iB2bSR5YtdsVtD09VVZWVhJgCtTBvGR1yxDtHxTHtorS2gELNV07KTXVb65HPZAB5RplWG4jHA4CUOQpyE8pBArwWfnq85d1b9G/v8L8VA6bv4HppoR9@ "Python 2 – Try It Online") EDIT: Saved 11 bytes thanks to Mr. Xcoder. [Answer] # [J](http://jsoftware.com/), ~~18~~ 17 bytes ``` (#-0{#\\:#.~\)@#: ``` [Try it online!](https://tio.run/##y/qfVqxga6VgoADE/zWUdQ2qlWNirJT16mI0HZSt/mtycSnpKain2VqpK@go1FoppBVzcaUmZ@QraFinaSoZKMQqGJoYKZhYKJibGgBNAAA) ## Explanation ``` (#-0{#\\:#.~\)@#: Input: integer n #: Binary #\ Length of each prefix \: Sorted down using #.~\ Mixed base conversion on each prefix 0{ Get the value at index 0 - Subtract from # Length ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 64 60 bytes ``` T=a=>(a&a/2)>0?T(a&a/2):Math.Log(a,2)<0?0:(int)Math.Log(a,2) ``` [Try it online!](https://tio.run/##dYy9CsIwGEVn8xSZJIFaY6go/R0EpxYEC84fMdRATaBJBSl99lhEB8Eul8s93CPsSphO@t4q3eDz0zp5T5BowVp8GpB14JTAx16LVGkX4Cly7OsMspzAEtac5qyoPzWuwN3C0jQEAk5TVrCYTAf6M/sEfbUPo664AqUJRQNaHIy2ppXhpVNOlkpLUhNGafKfbCI@y6L9LNpt38oRjf4F "C# (.NET Core) – Try It Online") A C# version of [@Arnauld's answer](https://codegolf.stackexchange.com/a/143004/73579) ### Acknowledgements 4 bytes saved thanks to Kevin Cruijssen. # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 131 123+18=141 bytes ``` a=>{string s=Convert.ToString(a,2),t=s.Split('0').OrderBy(x=>x.Length).Last();return a<1?0:s.Length-s.IndexOf(t)-t.Length;} ``` [Try it online!](https://tio.run/##dY9RS8MwFIWfza/I2xJoQzcmilkrKAhCZUILPof0OgM10dzb0VH622sdE3zYXi6c83Eu51hMbYgwdej8jlcHJPjU7L9SpfPfmtnWIPLXgSEZcpY/dd5unKeEz6fgNc/5ZPJiQIq/Wcwfg99DJFWH6mgJk6xkQjmq6qt1JBbZQqptbCA@HESfF70qwe/oQ6rSIAmpI1AXPTeb5X12hyeaonr2DfTbd0EypZOrx0mzv2b74Br@YpwXkg3sau6BoQX1Fh3BvAVELTIp9XmyXK8usvXtRXRzfXw5snH6AQ "C# (.NET Core) – Try It Online") +18 bytes for `using System.Linq;` ### Acknowledgements 8 bytes saved thanks to Grzegorz Puławski. ### Degolfed ``` a=>{ string s=Convert.ToString(a,2), // Convert to binary t=s.Split('0') // get largest group of 1's .OrderBy(x=>x.Length) .Last(); return a<1?0: // handle 0 case s.Length-s.IndexOf(t)-t.Length; // get position in reversed string } ``` # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 164 161 bytes ``` a=>{var s=Convert.ToString(a,2);int c=0,l=0,p=0,k=0,j=s.Length-1,i=j;for(;i>=0;i--){if(s[i]>'0'){if(i==j||s[i+1]<'1'){p=i;c=0;}if(++c>=l){l=c;k=p;}}}return j-k;} ``` [Try it online!](https://tio.run/##dY7NasMwEITP1VPoZhn/YIeUFJT1pdBTCoUYeig5CFVJ13YlI8mG4ujZXRHorTnMwM63DCNdIY1V6@RQX@jxx3n1zYkchHP0bSHOC4@Svkxa7lH7nEZraEuBrgKaZRaWOng2elbWl605ehtrmMg3KY@fVEKVD1FjVB/VgSsPSl/8V1HnCB0/G8s4NlBxLIp0wTNzH3hqkiq5HQjQXa8xyurTPqljOALy2MpDpFkmGxjSZQDJexh5CMEqP1lNu6LnYeXkb/9s8JO@CtQsJQt5iIOdGVT5btGrA2rFWlalKf@f1NvNXbZ9uot2j7fKQML6Cw "C# (.NET Core) – Try It Online") A non-`Linq` solution, which I'm sure could be improved, though nothing is immediately apparent. ### Degolfed ``` a=>{ var s=Convert.ToString(a,2); // Convert to binary int c=0,l=0,p=0,k=0,j=s.Length-1,i=j; for(;i>=0;i--) // Loop from end of string { if(s[i]>'0') // if '1' { if(i==j||s[i+1]<'1') // if first digit or previous digit was '0' { p=i; // set the position of the current group c=0; // reset the count } if(++c>=l) // if count is equal or greater than current largest count { l=c; // update largest count k=p; // store position for this group } } } return j-k; // as the string is reversed, return string length minus position of largest group } ``` [Answer] # [Python 3](https://docs.python.org/3/), 46 bytes ``` f=lambda x:x&x>>1and f(x&x>>1)or len(bin(x))-3 ``` [Try it online!](https://tio.run/##JczLCoMwEEbhfZ7iX9UMRPDWm2BepHQxYkMHdBRxkT59DHT3LQ5n@x3fVduUwjDzMk6M2MdL9L5mnRDs37TumD9qR1Ebico2MQa8Koe6axzu16zu4fBsbm9jQq4FouDeYNtFDyuuQOlRuLwUonQC "Python 3 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 12 bytes ``` →S§-€¤≠Lo▲gḋ ``` [Try it online!](https://tio.run/##ATgAx/9odXNr/yBtyK9z4oKBcsK2/@KGklPCpy3igqzCpOKJoExv4payZ@G4i////zAKMTQyCjQ4Cjc1MA "Husk – Try It Online") ### Explanation ``` Implicit input, e.g 750 ḋ Convert to binary [1,0,1,1,1,0,1,1,1,0] g Group equal elements [[1],[0],[1,1,1],[0],[1,1,1],[0]] o▲ Maximum [1,1,1] € Index of that substring in the binary number 3 ¤≠L Absolute difference of lengths abs (3 - 10) = 7 S§- Subtract the two 7 - 3 = 4 → Increment 5 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14 13 12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Bµṣ0Ṫ$ƤMḢạL ``` A monadic link taking and returning non-negative integers. **[Try it online!](https://tio.run/##ASQA2/9qZWxsef//4bmjMOG5qgpCwrXDh8akTeG4ouG6oUz///83NTA "Jelly – Try It Online")** or see the [test-suite](https://tio.run/##ATkAxv9qZWxsef//QsK14bmjMOG5qiTGpE3huKLhuqFM/zQ3UjtAMCwxNDIsNDgsNzUwwrXFvMOH4oKsR/8 "Jelly – Try It Online"). ### How? ``` Bµṣ0Ṫ$ƤMḢạL - Main link: number, n e.g. 750 B - convert to a binary list [1,0,1,1,1,0,1,1,1,0] µ - monadic chain separation, call that b Ƥ - map over prefixes: (i.e. for [1], [1,0], [1,0,1], [1,0,1,1],...) $ - last two links as a monad: e.g.: [1,0,1,1,1,0,1,1] 0 - literal zero 0 ṣ - split (prefix) at occurrences of (0) [[1],[1,1,1],[1,1]] Ṫ - tail [1,1] M - maximal indices [5,9] Ḣ - head 5 L - length (of b) 10 ạ - absolute difference 5 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` BŒgḄṀB BwÇɓÇL+ɓBL_‘ ``` [Try it online!](https://tio.run/##ASsA1P9qZWxsef//QsWSZ@G4hOG5gEIKQnfDh8mTw4dMK8mTQkxf4oCY////NzUw "Jelly – Try It Online") Thanks to Jonathan Allan for saving ~~4~~ 6 bytes! I've worked too much to just abandon this, although it is kind of long. I really wanted to add a solution that literally searches for the longest substring of `1`s in the binary representation... # Explanation ``` BŒgḄṀB - Monadic helper link. Will be used with Ç in the next link. B - Binary representation. Œg - Group runs of consecutive equal elements. Ḅ - Convert from binary to integer. Ṁ - Maximum value. B - Convert from integer to binary. BwÇɓÇL+ɓBL_‘ - Main link. B - Binary representation (of the input). Ç - Last link as a monad. Takes the input integer. w - First sublist index. ɓ - Start a separate dyadic chain. Reverses the arguments. Ç - Last link as a monad. L - Length. + - Addition ɓ - Start a separate dyadic chain. Reverses the arguments. B - Binary. L - Length. _‘ - Subtract and increment the result (because Jelly uses 1-indexing). - Implicitly output. ``` [Answer] # [Kotlin](https://kotlinlang.org), 77 bytes ``` {val b=it.toString(2) b.reversed().lastIndexOf(b.split(Regex("0+")).max()!!)} ``` ## Beautified ``` { val b = it.toString(2) // Find the left position of the first instance of b.reversed().lastIndexOf( // The largest group of 1s b.split(Regex("0+")).max()!!) } ``` ## Test ``` var s:(Int)->Int = {val b=it.toString(2) b.reversed().lastIndexOf(b.split(Regex("0+")).max()!!)} fun main(args: Array<String>) { r(0, 0) r(142, 1) r(48, 4) r(750, 5) } fun r(i: Int, i1: Int) { var v = s(i) println("$i -> $v [$i1] ${i1 == v}") } ``` [Answer] # [Haskell](https://www.haskell.org/), ~~101~~ ~~98~~ ~~96~~ 75 bytes ``` snd.maximum.(`zip`[0..]).c c 0=[0] c n|r<-c$div n 2=sum[r!!0+1|mod n 2>0]:r ``` [Try it online!](https://tio.run/##FcjRCsIgFADQ977iDvZQtMndWBSR/YgJE82SvCbaImLfntXTgXNV@Xb2vlh@KjkYRurlaCK2HN8ujgIZkyumFxqQC5Q/w5wOra6Ne0KAnueJRKoqXHcz3c2/jij3qZByATjE5MIDaiAVwYLAphv6Ztg12w3K8tHWq0surY7xCw "Haskell – Try It Online") Usage: `snd.maximum.(`zip`[0..]).c $ 142` yields `1`. ### Explanation: * `c` converts the input into binary while at the same time counting the length of streaks of one, collecting the results in a list. `r<-c$div n 2` recursively computes the rest `r` of this list, while `sum[r!!0+1|mod n 2>0]:r` adds the current length of the streak to `r`. The list comprehension checks if `mod n 2>0`, that is whether the current binary digit is a one, and if so, takes the length of the previous streak (the first element of `r`) and adds one. Otherwise the list comprehension is empty, and `sum[]` yields `0`. For the example input, `c 142` yields the list `[0,3,2,1,0,0,0,1,0]`. * `(`zip`[0..])` adds the position to each element of the previous list as the second component of a tuple. For the example this gives `[(0,0),(3,1),(2,2),(1,3),(0,4),(0,5),(0,6),(1,7),(0,8)]`. * `maximum` finds the lexicographically maximal tuple in this list, that is the streak lengths are considered first as they are the first component, and in the event of a tie the second component, namely the larger index, decides. This yields `(3,1)` in the example, and `snd` returns the second component of the tuple. [Answer] # Google Sheets, 94 bytes ``` =Len(Dec2Bin(A1))-Find(MAX(Split(Dec2Bin(A1),0)),Dec2Bin(A1))-Len(MAX(Split(Dec2Bin(A1),0)))+1 ``` No, it's not very pretty. It'd be real nice to be able to store `Dec2Bin(A1)` as a variable for reference. Key point: Like Excel, the `Dec2Bin` function has a max input value of `511`. Anything larger than that returns an error, as seen below. [![Results](https://i.stack.imgur.com/ONvG4.png)](https://i.stack.imgur.com/ONvG4.png) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~81~~ 80 bytes ``` i,l,c,r;f(n){for(i=l=c=r=0;n;n/=2,i++)c=n&1?c+1:c>=l?r=i-(l=c),0:0;n=c<l?r:i-c;} ``` [Try it online!](https://tio.run/##bcpBCsIwEIXhfU8RhEpCp9iUFEvj2Iu4kSmRgTpKcFd69pguuhHf5ofHR/WDKCWGGQiiD1rMEl5RM85IGLHx4uWELXBVGUI52pEqO9AV5zEi1zozA82QHdIlfwPX5Nf0vLNoUyyFyntHlk/Qh3JSVpXTTQ6grGtBBZ1jjP9Vbleu35Dr/5huN@eu2VDOptb0BQ "C (gcc) – Try It Online") # [C (gcc)](https://gcc.gnu.org/), 43 bytes A C version of @Arnauld's answer ``` k;f(n){n=(k=n&n/2)?f(k):(k=log2(n))<0?0:k;} ``` [Try it online!](https://tio.run/##bcpBCoMwFATQvacIguV/UBpDpGIqXqQbiSRI4m@p7sSrN00WbkpnMwzzdGW1DsEpA4Q79eB6utBV4GDAYRenf1oRP7zzgXdOHWEZZwLM9ozFvN4zbQbyYmI1K6YH5SWrpSiZgViI6lfJU8k2Idn@Mc1pbg1PKFZSR/ho40e7hsovXw "C (gcc) – Try It Online") [Answer] # MS SQL Server, 437 426 407 398 bytes [SQL Fiddle](http://sqlfiddle.com/#!6/5806d) I'm sure that I could remove line breaks, etc, but this is as compact as I was willing to make it: ``` create function j(@ int) returns int as BEGIN declare @a varchar(max)='',@b int,@c int=0,@d int=0,@e int=0,@f int=0,@g int=0,@h int=0 while @>0 BEGIN SELECT @a=cast(@%2 as char(1))+@a,@=@/2 END SET @b=len(@a) while @<@b BEGIN select @c=@d,@d=cast(substring(@a,@b-@,1)as int) IF @d=1 BEGIN IF @c=0 SELECT @e=@,@g=1 else SET @g+=1 END IF @g>=@h BEGIN select @h=@g,@f=@e END SET @+=1 END return @f END ``` Here's a more readable version: ``` create function BinaryString(@id int) returns int as BEGIN declare @bin varchar(max) declare @binLen int declare @pVal int = 0 declare @Val int = 0 declare @stC int = 0 --start of current string of 1s declare @stB int = 0 --start of biggest string of 1s declare @lenC int = 0 --length of current string of 1s declare @lenB int = 0 --length of biggest string of 1s set @bin = '' while @id>0 BEGIN SET @bin = cast(@id%2 as varchar(1)) + @bin SET @id = @id/2 END SET @binLen = len(@bin) while @id<@binLen BEGIN set @pVal = @Val set @Val = cast(substring(@bin,@binLen-@id,1) as int) IF @Val = 1 and @pVal = 0 BEGIN SET @stC = @id SET @lenC = 1 END IF @Val = 1 and @pVal = 1 BEGIN SET @lenC = @lenC + 1 END IF @lenC >= @lenB BEGIN set @lenB = @lenC set @StB = @StC END SET @id = @id + 1 END return @StB END ``` The real trick is that as far as I could find, there is no native SQL functionality to convert a number from decimal to binary. As a result, I had to code the conversion to binary manually, then I could compare that as a string, one character at a time until I found the right number. I'm sure there's a better way to do this, but I didn't see a(n) SQL answer, so I figured I'd throw it out there. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 21 bytes ([SBCS](https://github.com/abrudz/SBCS)) [−1 thanks to rabbitgrowth.](https://chat.stackexchange.com/transcript/message/59264944#59264944) Requires `⎕IO←0` which is default on many systems. ``` ⊃⌽⍸b⍷⍨∨⌿↑⊆⍨b←⌽2⊥⍣¯1⊢⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgkGXI862tP@P@pqftSz91HvjqRHvdsf9a541LHiUc/@R20TH3W1AblJQJVAeaNHXUsf9S4@tN7wUdcioAn/gXr/p3EZmhhxpXGZWAAJc1MDIGkAAA "APL (Dyalog Unicode) – Try It Online") `⎕` prompt for input `⊢` yield that (separates `¯1` from `⎕`) `2⊥⍣¯1` convert to base-2, using as many positions as needed `⌽` reverse `b←` store as `b` (for **b**inary) `⊆⍨b` self-partition `b` (i.e. the 1-streaks of `b`) `↑` mix (make list of lists into matrix, padding with zeros) `∨⌿` vertical OR reduction (yields longest streak) `b⍷⍨` mark the start positions of that in `b` `⍸` **ɩ**ndices of those starting positions `⌽` reverse `⊃` pick the first one (yields zero if none available) [Answer] # [MATL](https://github.com/lmendo/MATL), 15 bytes ``` `tt2/kZ&t]xBnq& ``` [Try it online!](https://tio.run/##y00syfn/P6GkxEg/O0qtJLbCKa9Q7f9/AwA "MATL – Try It Online") Uses the half and AND idea. The `k` is necessary only to make it terminate for `1` - for some reason, 1 AND 0.5 returns 1, causing an infinite loop. (alternate solution: `BtnwY'tYswb*&X>)-` by converting to binary and run-length encoding) [Answer] # R, 117 Bytes ``` z=rev(Reduce(function(x,y)ifelse(y==1,x+y,y),strtoi(intToBits(scan())),,,T));ifelse(!sum(z),0,33-which.max(z)-max(z)) ``` [Answer] # Excel VBA, ~~54~~ 44 Bytes -10 Bytes thanks to @EngineerToast Anonymous VBE immediate window function that takes input from range `[A1]` and outputs to the VBE immediate window ``` ?Instr(1,StrReverse([Dec2Bin(A1)]),1)+[A1>0] ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~24~~ 21 bytes ``` 63|-⊃⍒+/×\↑,⍨\⎕⊤⍨64⍴2 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQZcjzra0/6bGdfoPupqftQ7SVv/8PSYR20TdR71rogBqnrUtQTIMjN51LvF6D9Q7f80LkMTI640LhMLIGFuagAkDQA "APL (Dyalog Classic) – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 17 bytes This is a recursive function. The link includes `y` in order to call the function on the given input. ``` L|&K.&b/b2yKsl|b1 ``` **[Verify all test cases.](https://pyth.herokuapp.com/?code=L%7C%26K.%26b%2Fb2yKsl%7Cb1y&input=750&test_suite=1&test_suite_input=750%0A142%0A48%0A0&debug=0)** # [Pyth](https://github.com/isaacg1/pyth), 20 bytes ``` -lK.B|Q1+xKJeScK\0lJ ``` **[Verify all test cases.](https://pyth.herokuapp.com/?code=-lK.B%7CQ1%2BxKJeScK%5C0lJ&input=750&test_suite=1&test_suite_input=750%0A142%0A48%0A0&debug=0)** [Answer] # R, 66 Bytes ``` function(i){a=rle(intToBits(i));max(0,a[[1]][which(a[[2]]==1)])} ``` Explanation: ``` function(i){ a = rle( # Run-length encode intToBits(i) # The bits in i ); # And assign it to a. max(0, # Return the maximum of zero and a[[1]][ # The lengths of a, which(a[[2]]==1) # But only those where the repeated bit is 1 ]) } ``` [Answer] # [Python 2](https://docs.python.org/2/), 41 bytes ``` f=lambda n:n/2and(n&n/2<1)+f(n&n/2or n/2) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIc8qT98oMS9FI08NyLAx1NROgzDzixSApOb/NBBDITNPoSgxLz1Vw9DAQFM72sRCR8HQxEhHwdzUINaKS6GgKDOvRCFPRwGoWfM/AA "Python 2 – Try It Online") Based on [this solution by Mr. Xcoder](https://codegolf.stackexchange.com/a/143028/20260). [Answer] # Javascript, 54 chars ``` f=i=>i.toString(2).split(0).sort().reverse()[0].length ``` * `i.toString(2)` gets the binary string for the integer. * The `.split(0)` gets each sequential ones part in an array element. * `.sort().reverse()` gets us the highest value as first. * The `[0].length` gives us the length of that first value. [Answer] # Perl 5, 45 + 1 (-p) ``` (sprintf"%b",$_)=~/(1+)(?!.*1\1)/;$_=length$' ``` If you write this out on the command line of most shells, you may have to type this as: ``` perl -pE'(sprintf"%b",$_)=~/(1+)(?!.*1\1)/;$_=length$'"'" ``` The dance of the quotes at the end is just to get perl see a `'`, which would otherwise be consumed by the shell. [Answer] # [Retina](https://github.com/m-ender/retina), ~~52~~ 43 bytes Convert to binary, then replace with the length of what follows the largest string of ones. ``` .* $* +`(1+)\1 $+0 01 1 $'¶ O` A-3` ^1+ . ``` [**Try it online**](https://tio.run/##K0otycxL/K/qrpHA9V9Pi0tFi0s7QcNQWzPGkEtF24DLwJDLkItLRf3QNi7/BC5HXeMErjhDbS4uvf//DbgMTYy4TCy4zE0NAA) - all test cases *Saved 9 bytes thanks to Martin.* ]
[Question] [ Given a nonempty list of nonempty rows of numbers, compute the *column wise sum*, which is another list that has the length of the longest input row. The first entry of the output list is the sum of all the first entires of the input rows, the second one is the sum of all the second elements (if available) etc. I think following example will explain it way better: ``` Input: {[1,2,3,4],[1],[5,2,3],[6,1]} Computation: [1,2,3,4] + . . . [1]. . . + + + . [5,2,3]. + + . . [6,1]. . = = = = Output: [13,5,6,4] ``` ### Test Cases ``` {[0]} -> 0 {[1],[1,1,1,1]} -> [2,1,1,1] {[1],[1,2],[1,2,3],[1,2,3,4]} -> [4,6,6,4] {[1,6,2,-6],[-1,2,3,5]} -> [0,8,5,-1] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 1 byte ``` S ``` [Try it online!](https://tio.run/nexus/jelly#@x/8////6GjDWJ1oQx0jCKljDKN1TGJjAQ "Jelly – TIO Nexus") or [verify all test cases](https://tio.run/nexus/jelly#@x/8/@HuLWGH2x81rXH//z862iA2lis62jBWJ9pQBwyR@EYQUscYRuuYQGR1zIA8XTOgsC5E3DQ2FgA "Jelly – TIO Nexus"). ### How it works The sum atom `S` is a shorthand for `+/`, which performs reduction by addition. The quick `/` reduces along the outmost dimension, so it calls its link for the elements of the input. Here, the elements are the rows. The addition atom `+` vectorizes, so adding two row vectors perform element-by-element addition. When the arguments have different lengths, the elements of the longer argument that have no counterpart in the shorter one are left unaltered. All in all, with an irregular matrix as argument, `S` computes the column-wise sum, skipping missing entries in the shorter rows. [Answer] # [Python 2](https://docs.python.org/2/), ~~47~~ 45 bytes ``` lambda x:map(lambda*y:sum(filter(None,y)),*x) ``` *Thanks to @vaultah for golfing off 2 bytes!* [Try it online!](https://tio.run/nexus/python2#TYnRCoIwGIWv6ynOzXCTf5CZEkI9Qi@wdmHkQHBTNoP59EuyIA6cw/cdgwvuaWjt49kiNrad@Ab50oSX5aYf5s7z2@g6WoSgPIpkRo@I3oErddCaoFShSRX0yb84bk3lb@n0valeUdarl9tRaS2a/W7yvZuRMVmeA@QVLGRg4JFgeBQivQE "Python 2 – TIO Nexus") [Answer] # [Perl 6](http://perl6.org/), 23 bytes ``` {roundrobin(|$_)».sum} ``` [Answer] # Mathematica, 15 bytes ``` Total@*PadRight ``` [Answer] # Haskell, 34 bytes ``` import Data.List map sum.transpose ``` [Try it online!](https://tio.run/nexus/haskell#@5@ZW5BfVKLgkliSqOeTWVzClZuYmadgq1BQWhJcUqSgp1CckV8OpHITCxSKS3P1SooS84oL8otTFVQUoqMNdYx0jHVMYnWiDYHYFMQD0mY6hrGx//8DAA "Haskell – TIO Nexus") Usage: ``` Prelude Data.List> map sum.transpose $ [[1,2,3,4],[1],[5,2,3],[6,1]] [13,5,6,4] ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~7~~ 5 bytes *2 bytes off thanks to Dennis!* ``` {:.+} ``` This defines an anonymous block that takes a list of lists, such as `[[1 2 3 4] [1] [5 2 3] [6 1]]`, and replaces it by a list, `[13 5 6 4]`. [Try it online!](https://tio.run/nexus/cjam#y6n7X22lp137v67gf3S0oYKRgrGCSaxCtCEQm4J4QNpMwTA2FgA) Or [verify all test cases](https://tio.run/nexus/cjam#y6n7X22lp137X7Xgf7SCQnS0QWwsiDKMVYg2VABDZAEjCKlgDKMVTKDSCmZArq4ZUFwXImEKkogFAA). ### Explanation ``` { } e# Define block : e# Fold over the following dyadic function .+ e# Vectorized addition ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 3 bytes ``` oXs ``` (*MATL doesn't know that the plural of "ox" is "oxen"...*) Input is a cell array of numeric row vectors, in the same format as in the challenge text: ``` {[1,2,3,4],[1],[5,2,3],[6,1]} ``` [Try it online!](https://tio.run/nexus/matl#@58fUfz/f3W0oY6RjrGOSaxOtCEQm4J4QNpMxzC2FgA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#S/ifH1H83yXkf3W0QWwtV3W0YaxOtKEOGCLxjSCkjjGM1jGByOqYAXm6ZkBhXYi4aWwtAA). ``` % Implicit input o % Convert cell array to a matrix, right-padding with zeros each row Xs % Sum of each column % Implicit display ``` [Answer] ## JavaScript (ES6), ~~51~~ 48 bytes *Saved 3 bytes, thanks to ETHproductions* ``` a=>a.map(b=>b.map((v,i)=>r[i]=~~r[i]+v),r=[])&&r ``` ### Test cases ``` let f = a=>a.map(b=>b.map((v,i)=>r[i]=~~r[i]+v),r=[])&&r console.log(f([[1,2,3,4],[1],[5,2,3],[6,1]])); // -> [13,5,6,4] console.log(f([[0]])); // -> [0] console.log(f([[1],[1,1,1,1]])); // -> [2,1,1,1] console.log(f([[1],[1,2],[1,2,3],[1,2,3,4]])); // -> [4,6,6,4] console.log(f([[1,6,2,-6],[-1,2,3,5]])); // -> [0,8,5,-1] ``` [Answer] # [Wonder](https://github.com/wonderlang/wonder), 11 bytes ``` @->#sum '#0 ``` Transpose and map with sum function. Usage: ``` (@->#sum '#0)[[1 2 3 4];[1];[5 2 3];[6 1]] ``` [Answer] # C++14, 130 bytes As unnamed generic lambda: ``` [](auto C,auto&r){r.clear();int i=0,b=1;while(b--){r.push_back(0);for(auto c:C)r.back()+=i<c.size()?c[b=1,i]:0;++i;}r.pop_back();} ``` Requires `C` to be like `vector<vector<int>>` and return value `r` to be like `vector<int>` (should be okay according to [meta](https://codegolf.meta.stackexchange.com/a/4942/53667)). Ungolfed & usage: ``` #include<vector> #include<iostream> auto f= [](auto C, auto&r){ r.clear(); //clearing r just to be sure int i=0,b=1; //i is the position in the row, b is a boolean while(b--){ //while something was added r.push_back(0); //add zero for(auto c:C) //for each container r.back() += i<c.size() ? //add to the last element c[b=1,i] : 0; //set b and get the element or zero ++i; } r.pop_back(); //remove last unnecessary zero } ; using namespace std; int main(){ vector<vector<int> > C = { {1,2,3,4}, {1}, {5,2,3}, {6,1} }; vector<int> r; f(C,r); for (int i: r) cout << i << ", "; cout << endl; } ``` [Answer] # Pyth - 4 bytes ``` sM.T ``` [Try it online here](http://pyth.herokuapp.com/?code=sM.T&input=%5B1%2C2%2C3%2C4%5D%2C%5B1%5D%2C%5B5%2C2%2C3%5D%2C%5B6%2C1%5D&debug=0). [Answer] # Haskell, ~~61 41~~ 40 bytes Thanks @Laikoni for -20 bytes, @nimi for -1 byte! ``` f[]=[] f l=sum[h|h:_<-l]:f[t:u|_:t:u<-l] ``` **Explanation:** It is just a recursive summation of the first elements of the list, also dealing with discarding empty lists in every intermediate step: ``` sum[h|h:_<-l] -- sums up all the first elemetns of the list [t:u|_:t:u<-l] -- removes the first element of all the list, and removes empty lists f -- applies f to the remaining list : -- prepends the sum to the rest ``` [Answer] # J, 5 bytes ``` +/@:> ``` Takes input as a boxed list of lists. ## Test cases ``` 1 ; 1 1 1 1 +-+-------+ |1|1 1 1 1| +-+-------+ (+/@:>) 1 ; 1 1 1 1 2 1 1 1 1 ; 1 2 ; 1 2 3 ; 1 2 3 4 +-+---+-----+-------+ |1|1 2|1 2 3|1 2 3 4| +-+---+-----+-------+ (+/@:>) 1 ; 1 2 ; 1 2 3 ; 1 2 3 4 4 6 6 4 ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 3 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` +⌿↑ ``` `+⌿` sum column-wise `↑` the mixed (list of list, stacked into matrix, padding with zeros) argument [TryAPL online!](http://tryapl.org/?a=f%u2190+%u233F%u2191%20%u22C4%20f%281%202%203%204%29%281%29%285%202%203%29%286%201%29&run) [Answer] # [R](https://www.r-project.org), ~~53~~ ~~52~~ 51 bytes ``` \(x){for(i in x)F=F+i*!seq(!i)-1:max(lengths(x));F} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3jWM0KjSr0_KLNDIVMvMUKjTdbN20M7UUi1MLNRQzNXUNrXITKzRyUvPSSzKKgUo1rd1qoVrL0zRyMotLNAw0NbmgTEOdZCAGQ01kUUMrIyA2BmIThDBIqZmOkY6umSZQm64hkGmsY4qsz8pEB2SiKUgGpMYMbCzE-gULIDQA) Thanks to Giuseppe for a byte saved. [Answer] # Octave, 69 bytes ``` @(a){g=1:max(s=cellfun(@numel,a))<=s';f=g'+0;f(g')=[a{:}];sum(f')}{4} ``` [Answer] # Japt, 5 bytes ``` Uz mx ``` [Test it online!](http://ethproductions.github.io/japt/?v=master&code=VXogbXg=&input=W1sxLDIsMyw0XSxbMV0sWzUsMiwzXSxbNiwxXV0=) `U` is the input array, and `z` on arrays rotates the array clockwise by 90 degrees. Therefore, ``` [ [1,2,3,4], [1 ], [5,2,3 ], [6,1 ] ] ``` becomes ``` [ [6,5,1,1], [1,2, 2], [ 3, 3], [ 4] ] ``` (Spacing added only for display purposes.) `mx` then `m`aps by summation (`x`), which gives the desired result: `[13,5,6,4]`. [Answer] # [Uiua](https://uiua.org), 4 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` ⬚0/+ ``` [Try it!](https://uiua.org/pad?src=ZiDihpAg4qyaMC8rCgpmIHtbMSAyIDMgNF0gWzFdIFs1IDIgM10gWzYgMV19Cg==) ``` ⬚0/+ /+ # sum columns ⬚0 # filling needed nonexistent elements with zero ``` [Answer] # [R](https://www.r-project.org), 52 bytes ``` \(x)colSums(t(sapply(x,\(v)v[1:max(lengths(x))])),T) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3TWI0KjST83OCS3OLNUo0ihMLCnIqNSp0YjTKNMuiDa1yEys0clLz0ksyioEKNWM1NXVCNKF6y9M0cjKLSzQMNDW5oExDnWQgBkNNZFFDKyMgNgZiE4QwSKmZjpGOrpkmUJuuIZBprGOKrM_KRAdkoilIBqTGDGwsxPoFCyA0AA) Only one byte longer than [Kirill L.'s answer](https://codegolf.stackexchange.com/a/266570/55372), so I thought it's worth posting as well. [Answer] ## Pyke, 4 bytes ``` .,ms ``` [Try it here!](http://pyke.catbus.co.uk/?code=.%2Cms&input=%5B%5B1%2C2%2C3%2C4%5D%2C%5B1%5D%2C%5B5%2C2%2C3%5D%2C%5B6%2C1%5D%5D) [Answer] # Java 8, 124 bytes this is a lambda expression for a `Function< int[ ][ ], int[ ] >` ``` i->{int L=0,t,r[];for(int[]a:i)L=(t=a.length)>L?t:L;r=new int[L];for(;0>L--;)for(int[]a:i)r[L]+=a.length>L?a[L]:0;return r;} ``` it takes the largest array length from the input, creates a new array of that size, and then writes the sums of each column to the array. [Answer] ## R, ~~105~~ 97 bytes ``` a=c();l=length;for(i in 1:l(w)){length(w[[i]])=max(sapply(w,l));a=rbind(a,w[[i]])};colSums(a,n=T) ``` This takes in input a `list` object called `w` in the form : ``` w=list(c(1,2,3,4),c(1),c(1,2)) ``` It outputs the column-wise sum : `[1] 3 4 3 4` This solution is quite long to me. **R** has the particularity to recycle when you try to bind vectors of different length. For example : ``` a=c(1,2,3,4) b=c(1,2) cbind(a,b) a b [1,] 1 1 [2,] 2 2 [3,] 3 1 [4,] 4 2 ``` `b` is re-used once to fit, which is why I begin with a list. The program adjusts the length of all the elements of the list as the one of the longest, binds the elements and computs the column-wise sum. The length adjusting produces `NA`'s, that are ignored by the `sum`. *-8 bytes* thanks to @Jarko Dubbeldam ! [Answer] **Clojure, 70 bytes** ``` #(for[i(range(apply max(map count %)))](apply +(for[v %](get v i 0)))) ``` A basic nested loop. [Answer] # PHP, 63 bytes ``` <?foreach($_GETas$a)foreach($a as$i=>$x)$r[$i]+=$x;print_r($r); ``` call in browser with GET parameters as list of inputs. Example: `script.php?a[]=1&a[]=2&a[]=3&a[]=4&b[]=1&c[]=5&c[]=2&c[]=3&d[]=6&d[]=1` (Array names are ignored, so you can name them any way you want.) Try this function for testing: ``` function s($a){foreach($a as$b)foreach($b as$i=>$x)$r[$i]+=$x;return$r;} ``` or use `http_build_query($array,a)` to convert a given array of arrays to GET parameters. [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` mΣT0 ``` [Try it online!](https://tio.run/##yygtzv7/P/fc4hCD////R0cb6hjpGOuYxOpEGwKxKYgHpM10DGNjAQ "Husk – Try It Online") ## Explanation ``` mΣT0 T0 Transpose matrix, padding with 0's where needed mΣ map each column to its sum ``` [Answer] # [Scala](http://www.scala-lang.org/), 64 bytes Golfed version. [Try it online!](https://tio.run/##lVDBaoQwEL37FXM0MLrqqhRBocdCSw@7PS1SUjddLDGKicVW/HabjXXbg7DtJAwzk8mb90YWlNOpfnljhYIHWgoYLAveKYei5l0ldl0FCdj3pVQH4@6EynNIM7hkBFKYeJoN3K1oY/dp1rsNPe5rey48u7L8ZETHPXqEuKqlQja1ZMtrV5FxAjiyV6g0A5u2J5nAbdvSj8NOtaU45SSBJ1EqPWmwQNtmA3smFRRUMmkqje5TXNgX2obz7HwMcIshQZjTJYjO9SWJ0SfaztCPnWo6lXx3bxEihBghJFcneasQ3vWPF04@mrOKEyD48/0XYPAr/NG7LGVtUGj0/k2yj7FGcuIF15mBo/VNINyYdTpGwmiN0xc) ``` l=>{l.map(x=>x.padTo(l.map(_.size).max,0)).transpose.map(_.sum)} ``` Ungolfed version. [Try it online!](https://tio.run/##lVFda8IwFH33V5zHBmJt/ShDcLCHPQwce9A9yRhZTbWjTUqSTsfwt7s0adUHwa0t6b2Xc8@950SnrGDHo/z45KnBM8sFfno9YM0zpLKoS7Goy6DItdFTzO1v5Y4nYd7eSFtpEsxsH@wzGOBR6FpxmC2HawSzmcxQizyTqkTBxcZsYWMYxYSupM7FhiLLiwJ6K5XhClJwjV1ucZF2xF@sQMn2c98889RhyargPfSMxGb7E7adNncbXMKbCLN7Vwkrtl7K4MRLERHS64Qs2@3OWhoZXlNgaiV065FGLoyEkjtNwMQaui7BWbptSo7tcpuwU83b9S2aWNShM7601xAwtbGWPyjFvlcLo6xDjeGvIjeXXi@5XSplmnuTKoszhQjOV9dM9EdMh3REx4TCp10waepdktCY2KehfqlNVZtpix5RTCgSijG5OSm6ShHdbjztFFP3XuUZUsT@@xfh8CI86@1MuTZo7PT@TXJME8vUTzrevieeXHeC4s7Z2Y/9vR@Ox18) ``` object Main { def columnSum(lists: List[List[Int]]): List[Int] = { // Ensure the lists are of uniform length for transposing, fill shorter ones with 0s val maxLength = lists.map(_.length).max val uniformLists = lists.map(list => list.padTo(maxLength, 0)) // Transpose the list of lists (turns columns into rows) and sum each row uniformLists.transpose.map(_.sum) } def main(args: Array[String]): Unit = { // Test cases println(columnSum(List(List(1,2,3,4), List(1), List(5,2,3), List(6,1)))) // Output: List(13, 5, 6, 4) println(columnSum(List(List(0)))) // Output: List(0) println(columnSum(List(List(1), List(1,1,1,1)))) // Output: List(2, 1, 1, 1) println(columnSum(List(List(1), List(1,2), List(1,2,3), List(1,2,3,4)))) // Output: List(4, 6, 6, 4) println(columnSum(List(List(1,6,2,-6), List(-1,2,3,5)))) // Output: List(0, 8, 5, -1) } } ``` ]
[Question] [ ## Disarium Dilemma A Disarium is defined as a number whose: > > sum of its digits powered with their respective position is equal to the original number > > > --- **Your Task**: You have a strange obsession with numbers classified as being a disarium. The need to follow the ways of disarium is so great in you that you **refuse** to read any non-disarium numbered pages in any given book. You have two **BIG** problems: 1. Your professor just assigned you to read your textbook from page `n` to page `m` 2. You hit your head really hard last week and can't seem to remember how to programmatically determine if a number is considered to be a disarium. Time is of the essence so the code to determine the pages you will need to read needs to be as short as possible. You need to identify all of the disarium within an inclusive range of `n` through `m`. **Examples of a disarium**: > > 89 = 81 + 92 > > > 135 = 11 + 32 + 53 > > > 518 = 51 + 12 + 83 > > > This is code-golf, so the least number of bytes wins! Here is the full sequence of [A032799](https://oeis.org/A032799). [Answer] # [Perl 6](http://perl6.org/), ~~40~~ 39 bytes ``` {grep {$_==sum .comb Z**1..*},$^a..$^b} ``` [Try it online!](https://tio.run/nexus/perl6#y61UUEtTsP1fnV6UWqBQXVyaq6GXnJ@bpBClpWWop6elmVqoEl@ro6ASl6inpxKXVPu/OLFSIU3B0MBAR8HMwMD6PwA "Perl 6 – TIO Nexus") ### How it works ``` { } # A lambda. $^a..$^b # Range between the two lambda arguments. grep { }, # Return numbers from that range which satisfy: .comb Z 1..* # Digits zipped with the sequence 1,2,3,..., ** # with exponentiation operator applied to each pair, sum # and those exponents summed, $_== # equals the number. ``` [Answer] # Python2, ~~98~~ ~~89~~ ~~88~~ 84 bytes ``` lambda n,m:[x for x in range(n,m+1)if sum(int(m)**-~p for p,m in enumerate(`x`))==x] ``` ~~Horrible. Will get shorter.~~ Starting to look better Here's my recursive attempt (86 bytes): ``` f=lambda n,m:[]if n>m else[n]*(sum(int(m)**-~p for p,m in enumerate(`n`))==n)+f(n+1,m) ``` Thanks to [@Rod](https://codegolf.stackexchange.com/users/47120/rod) for saving 4 bytes! `range` to `enumerate` and so on. [Answer] # JavaScript (ES7), ~~105~~ ~~91~~ ~~89~~ ~~88~~ ~~83~~ ~~79~~ ~~82~~ 81 bytes *Thanks to Arnauld for saving 20B, and ETHProductions for saving 6B!* ``` a=>b=>[...Array(b).keys()].filter(c=>c>=a&([...c+''].map(d=>c-=d**++e,e=0),!c)) ``` ## Usage Assign the function to a variable, and give it the minimum and the maximum as arguments. Example: ``` f=a=>b=>[...Array(b).keys()].filter(c=>c>=a&([...c+''].map(d=>c-=d**++e,e=0),!c)) f(0)(90) ``` ### Output ``` [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 89] ``` ## Further golfing This seems pretty well-golfed, but there's always room for improvement... I think. [Answer] # Python 3, 100 bytes ``` lambda n,m:{*range(10),89,135,175,518,598,1306,1676,2427,2646798,0xa8b8cd06890f2773}&{*range(n,m+1)} ``` Not the shortest approach, but a pretty cute one. There are finitely many disariums; see the OEIS page for a nice proof. These are all of them. [Answer] # JavaScript (Firefox 52+), 68 bytes ``` f=(n,m)=>(e=0,[for(d of t=n+'')t-=d**++e],t||alert(n),n-m&&f(n+1,m)) ``` Recursive function that outputs via `alert`. Works in the Developer Edition of Firefox, which you can download on [this page](https://www.mozilla.org/en-US/firefox/channel/desktop/?v=a). Previous versions of Firefox don't support the `**` operator, and no other browser supports `[for(a of b)c]` syntax. ### Test snippet This uses `.map` instead of an array comprehension, and `Math.pow` instead of `**`, so it should work in all browsers that support ES6. ``` f=(n,m)=>(e=0,[...t=n+''].map(d=>t-=Math.pow(d,++e)),t||alert(n),n-m&&f(n+1,m)) f(0,100) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes Saved 2 bytes thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna) ``` ŸvygLySmOyQ— ``` [Try it online!](https://tio.run/nexus/05ab1e#@390R1lluk9lcK5/ZeCjhin//xtwGRoAAQA "05AB1E – TIO Nexus") ``` Ÿ # push [a .. b] vy # for each gL # push [1 .. num digits] yS # push [individual digits] m # push [list of digits to the power of [1..num digits] ] O # sum yQ— # print this value if equal ``` [Answer] # Perl, 43 bytes ``` map{say if$_==eval s/./+$&**$+[0]/gr}<>..<> ``` [Try it online!](https://tio.run/nexus/perl#@5@bWFBdnFipkJmmEm9rm1qWmKNQrK@nr62ipqWloh1tEKufXlRrY6enZ2P3/78hl6GBgcF/XV9TPQNDAwA "Perl – TIO Nexus") Regex is really powerful, you guys. ## Explanation The first thing the code does is read two integers as input via `<>`, and creates a range from the first to the second with `..`. It then uses the standard `map` function to iterate through this range, and applies the following code to each value: `say if$_==eval s/./+$&**$+[0]/gr`. This looks like gibberish, and it kind of is, but here's what's really happening. `map` implicitly stores its current value in the variable `$_`. Many perl functions and operations use this value when none is given. This includes regular expressions, such as the `s///` substitution operator. There are four parts to a substitution regex: 1. String to be manipulated. Ordinarily, the operator `=~` is used to apply a regex to a string, but if this operator is absent, then the regex is applied to the implicit variable `$_`, which contains our current number via the `map` function. 2. String to search for. In this case, we're searching for any single non-newline character, denoted by the wildcard `.`. In effect, we're capturing each individual digit. 3. String to replace with. We're substituting a plus sign `+` followed by a mathematical expression, mixed in with some magical Perl variables that make everything significantly easier. The special scalar variable `$&` always contains the entirety of the last successful regex capture, which in this case is a single digit. The special array variable `@+` always contains a list of *postmatch offsets* for the last successful match, i.e. the index of the text *after* the match. `$+[0]` is the index in `$_` of the text immediately following `$&`. In the case of `135`, we capture the digit `1`, and the index in `135` of the text immediately afterwards (namely, `35`) is 1, which is our exponent. So, we want to raise `$&` (1) to the power of `$+[0]` (1) and get 1. We want to raise 3 to the power of 2 and get 9. We want to raise 5 to the power of 3 and get 125. If the input was `135`, the resulting string is `+1**1+3**2+5**3`. 4. Regex-modifying flags. Here we're using two regex flags -- `/g` and `/r`. `/g` tells the interpreter to continue replacements after the first is found (otherwise we'd end up with `+1**135`). `/r` tells the interpreter *not to modify the original string*, and instead return what the string would be after the replacements. This is important, because otherwise, it would overwrite `$_`, and we need it for comparison purposes. Once the entire substitution is done, we get a mathematical expression, which is evaluated with the `eval` function. `+1**1+3**2+5**3` is evaluated into `1 + 9 + 125 = 135`, which is compared to the original number `135`. Since these two are equal, the code prints the number. [Answer] ## R, 100 bytes ``` function(n,m,x=n:m)x[sapply(x,function(y)sum(as.integer(el(strsplit(c(y,""),"")))^(1:nchar(y)))==y)] ``` Unnamed function that takes `n` and `m`. As always in R, splitting integers into a numeric digit vector is tedious and eats up a lot of bytes. This makes the function relatively slow and only works for 32-bit integers. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` D*J$S⁼ rÇÐf ``` [Try it online!](https://tio.run/nexus/jelly#@@@i5eKlEvyocQ9X0eH2wxPS/v//b2Tw39DEAAA "Jelly – TIO Nexus") Got this down from 16 to 11, with some help from @miles! Explanation: ``` rÇÐf Main link, arguments are m and n r Generate a list from m to n Ç Invoke the helper link Ðf And filter out all that don't return 1 on that link D*J$S⁼ Helper link, determines if item is Disarium D Break input (the current item of our list in Main) into digits (135 --> [1, 3, 5]) J$ Create a range from 1 to x, where x is the number of digits [1, 2, 3] * Raise each digit to the power of their respective index S⁼ And return a 1 if the sum of powers is equal to the helper-link's input ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 23 bytes ``` q~),\>{_Ab_,,:).#:+=},p ``` [Try it online!](https://tio.run/nexus/cjam#@19Yp6kTY1cd75gUr6NjpamnbKVtW6tT8P@/hYGCqZEBAA "CJam – TIO Nexus") **Explanation** ``` q~ Get and eval all input ),\> Get the range between m and n, inclusive { For each number in the range... _Ab Duplicate and get the list of digits _,,:) Duplicate the list, take its length, make the range from 1 to length .# Vectorize with exponentiation; computes first digit^1, second^2, etc :+ Sum the results = Compare to the original number }, Filter the range to only numbers for which the above block is true p Print nicely ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes ``` Ÿvy©SDgLsmO®Qi®}}) ``` [Try it online!](https://tio.run/nexus/05ab1e#@390R1nloZXBLuk@xbn@h9YFZh5aV1ur@f@/AZehARAAAA "05AB1E – TIO Nexus") [Answer] # Python 2.X, 92 bytes ``` lambda m,n:[k for k in range(m,n+1)if sum(int(j)**(i+1) for i,j in enumerate(list(`k`)))==k] ``` [Answer] # [Python 2](https://docs.python.org/2/), 84 bytes A full program approach, currently the same length as the lambda solution. ``` a,b=input() while a<=b: t=p=0 for x in`a`:p+=1;t+=int(x)**p if t==a:print a a+=1 ``` [**Try it online!**](https://tio.run/nexus/python2#DcpNCoAgEAbQ/ZziW/a3SEIoa@7SCElC1BBG3d7cPl6WznM89UlVTe8ejw2ysHeExMo9IVw3PsRzldVpy2ZObfmp@uqmUUIMJbI4vQtCCFJOzmawHew0/g) [Answer] # Japt, 15 bytes ``` òV f_¥Zì £XpYÄÃx ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.3&code=8lYgZl+lWuwgo1hwWcTDeA==&input=MCw2MDA=) This was a collaboration between @obarakon and myself. ### How it works ``` òV f_¥Zì £XpYÄÃx // Implicit: U, V = input integers òV // Create the inclusive range [U...V]. f_ // Filter to only the items Z where... x // the sum of Zì // the decimal digits of Z, £XpYÄà // where each is raised to the power of (index + 1), ¥ // is equal to Z. // Implicit: output result of last expression ``` In the latest version of Japt, `x` accepts a function as an argument, which allows us to golf another byte: ``` òV f_¥Zì x@XpYÄ ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=8lYgZl+lWuwgeEBYcFnE&input=MCw2MDA=) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` ŸʒDSāmOQ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//6I5Tk1yCjzTm@gf@/29oAARcBgA "05AB1E – Try It Online") [Answer] ## Clojure, 107 bytes ``` #(for[i(range %(inc %2)):when(=(int(apply +(map(fn[i v](Math/pow(-(int v)48)(inc i)))(range)(str i))))i)]i) ``` Implementing the equation is terribly long. [Answer] # TI-Basic, 85 bytes ``` Input For(I,X,Y If I<=9 or sum(I={89,135,175,518,598,1306,1676,2427,2646798,12157692622039623539 Disp I End ``` [Answer] ## Haskell, 61 bytes ``` n#m=[i|i<-[n..m],i==sum(zipWith(^)(read.pure<$>show i)[1..])] ``` Usage example `5 # 600` -> `[5,6,7,8,9,89,135,175,518,598]`. Check each number `i` in the range `[n..m]`. The digits are extracted by turning `i` into a string (`show`) and making each char a one element string (`pure`) which is turned into an integer again (`read`). Zip those numbers element wise with `[1..]` via the function `^` and take the `sum`. [Answer] # PHP, ~~92~~ ~~91~~ 88 bytes 3 bytes saved thanks @AlexHowansky ``` for([,$n,$m]=$argv;$n<=$m;$s-$n++?:print"$s,")for($i=$s=0;_>$b=($n._)[$i++];)$s+=$b**$i; ``` takes input from command line arguments; prints a trailing comma. Run with `-r`. [Answer] # Mathematica, 59 bytes ``` Select[Range@##,Tr[(d=IntegerDigits@#)^Range@Length@d]==#&]& ``` Unnamed function taking two integer arguments and returning a list of integers. `(d=IntegerDigits@#)^Range@Length@d` produces the list of digits of a number to the appropriate powers; `Tr[...]==#` detects whether the sum of those digit-powers equals the original number. [Answer] # **MATLAB, ~~88~~ 73 bytes** ``` @(n,m)find(arrayfun(@(n)n==sum((num2str(n)-48).^(1:log10(n)+1)),n:m))+n-1 ``` Original answer: ``` function g(n,m);a=n:m;a(arrayfun(@(n)n==sum((num2str(n)-'0').^(1:floor(log10(n))+1)),a)) ``` `num2str(n)-'0'` splits a `n` into a vector of its digits, and `1:floor(log10(n))+1` is a vector holding one to the number of digits in `n`. Thanks to [log](https://codegolf.stackexchange.com/users/64590/log) for the golf down to an anonymous function, saving 15 bytes. [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` òV fȶìxÈpYÄ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=8lYgZsi27HjIcFnE&input=MCw2MDA) ``` òV fȶìxÈpYÄ :Implicit input of integers U & V òV :Range [U,V] f :Filter by È :Passing each through the following function ¶ : Check for equality with ì : Convert to digit array x : Reduce by addition È : After passing each element at 0-based index Y through the following function p : Raise to the power of YÄ : Y+1 ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes ``` ⟦₂∋.i₁ᶠ^ᵐ+ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpofbFjzc1Vn7cOuE/4/mLwMKPOro1st81NQIlIgDimr//x8dbWhqoKNgaAAEsbEA "Brachylog – Try It Online") Generates each disarium through the output variable. ``` . The output variable is ∋ an element of ⟦₂ the inclusive range between the elements of the input. ᶠ Find every i₁ pair of a digit and its 1-index in the output variable, ^ᵐ and raise each digit to the power of its index. + The sum is equal to the output variable. ``` Also worth mentioning here, rather than in a comment or its own submission, that steenbergh's Jelly solution can now be golfed down to `rD*J$S⁼ƲƇ`, but I might find this a bit more idiomatic: # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` rD*J$SƊƑƇ ``` [Try it online!](https://tio.run/##y0rNyan8/7/IRctLJfhY17GJx9r///9vaGrw39AACAA "Jelly – Try It Online") [Answer] # [Desmos](https://www.desmos.com/calculator), 82 bytes ``` a=[n...m] d=\floor(\log a) f(n,m)=a[a=\sum_{i=0}^d\mod(\floor(a/10^i),10)^{d-i+1}] ``` [Try it on Desmos!](https://www.desmos.com/calculator/9a2v2hbnq7) [Answer] # [Haskell](https://www.haskell.org/), ~~82 76~~ 75 bytes ``` n!m=[x|x<-[n..m],x==x#(length.show)x] 0#i=0 n#i=(div n 10)#(i-1)+mod n 10^i ``` [Try it online!](https://tio.run/nexus/haskell#@5@nmGsbXVFTYaMbnaenlxurU2FrW6GskZOal16SoVeckV@uWRHLZaCcaWvAlQckNVIyyxTyFAwNNJU1MnUNNbVz81PA/LjM/7mJmXkKtgoFpSXBJUUKegog3QoqCgaKhuZm/wE "Haskell – TIO Nexus") Usage: `5 ! 175` This checks each number in the range `n` to `m` if its a disarium number and is hence quite slow for big `m`. --- Faster version: (93 bytes) ``` n!m=[x|x<-[0..9]++[89,135,175,518,598,1306,1676,2427,2646798,12157692622039623539],x>=n,x<=m] ``` [Try it online!](https://tio.run/nexus/haskell#FcwxDgIhEEDRq8wmdjsSGHYGJlm8hCWhsNMCNLpGCu@Oa/lf8Uebasr929djtsZomeccFZ1ndIGRXUTWuLcVdBIEaaGAJIuEP5PjIEpCZL0KefZasJ9Sw76mWka93BokeLy38/YEA6/r/QMH4Gmfjx8 "Haskell – TIO Nexus") [Answer] # [C (gcc)](https://gcc.gnu.org/), 136 bytes ``` r[]={0,0};f(n){if(n)f(n/10),r[1]=pow((n%10),*r)+r[1]+.5,r[0]++;else*r=1,r[1]=0;}g(m,x){for(;m<=x;m++){f(m);if(m==r[1])printf("%d,",m);}} ``` Header defining pow on TIO because for some reason it didn't auto include pow. My computer did, so I'm going to roll with that. [Try it online!](https://tio.run/nexus/c-gcc#LYzBCsIwEETvfkUoFHabqAniac2XlB4EmxIwaYkVIyHfXhPqYYedfTO7zB@I4ossHRizBsoWxvUdPIusY8tOjwqp4D9QdMhb6AedpJCZDHhMtmqZs5IoQq8GXavg2@q7gLze@OlamBw4p/H5Grug1Z6VlCdwImIycwByNx3JcV4sOKTy22ldg7gE61cDTfsQjSgo583drQdMbAIpLlIisbz9AA "C (gcc) – TIO Nexus") [Answer] # [MATL](https://github.com/lmendo/MATL), 16 bytes ``` &:"@tFYAtn:^s=?@ ``` [Try it online!](https://tio.run/nexus/matl#@69mpeRQ4hbpWJJnFVdsa@/w/78hl6GBAQA "MATL – TIO Nexus") ``` &: % Input two n, m implicitly. Push array [n n+1 ... m] " % For each k in that array @ % Push k tFYA % Duplicate. Convert to decimal digits tn: % Duplicate. Push [1 2 ... d], where d is the number of digits ^ % Element-wise power s % Sum of array = % Compare with previous copy of k: is it equal? ? % If so @ % Push k % End, implicit % End, implicit % Display stack, implicit ``` [Answer] ## Batch, 115 bytes ``` @for %%d in (0 1 2 3 4 5 6 7 8 9 89 135 175 518 598 1306 1676 2427 2646798)do @if %%d geq %1 if %%d leq %2 echo %%d ``` Batch only has 32-bit arithmetic which has no way of comparing the last disarium number, but if you insist on string comparisons, then for 402 bytes: ``` @echo off for %%d in (0 1 2 3 4 5 6 7 8 9 89 135 175 518 598 1306 1676 2427 2646798 12157692622039623539)do call:c %1 %%d&&call:c %%d %2&&echo %%d exit/b :c call:p %1 %2 set r=%s% call:p %2 %1 :g if %r:~,1% lss %s:~,1% exit/b0 if %r:~,1% gtr %s:~,1% exit/b1 if %r%==%s% exit/b0 set r=%r:~1% set s=%s:~1% goto g :p set s=%1 set t=%2 :l set s=0%s% set t=%t:~1% if not "%t%"=="" goto l ``` [Answer] ## Python 2, 100 bytes ``` for i in range(input(),input()+1):x=sum(int(`i`[n])**-~n for n in range(len(`i`)));print("",x)[x==i] ``` I haven't had a chance to run this yet (doing this on my phone). [Answer] ## Scala, ~~132~~ 129 bytes ``` (% :Int,^ :Int)=>for(i<- %to^)if(((0/:(i+"").zipWithIndex)((z,f)=>{z+BigInt(f._1.toInt-48).pow(f._2+1).intValue}))==i)println(i) ``` --- 129 edit: Changing the for loop's variable name from `&` to `i` saved three spaces. --- ## Explanation For each value in the input range: * convert it to a string with `+""` * use `zipWithIndex` to produce a list of tuples containing a char of the digit and its index * fold the list by returning each char's int value minus 48 (lines up to 0-9) to the power of its list index plus one (to start at ^1) * if the result matches the input, print it --- ## Comments Finally got around to learning how `fold` and `zipWithIndex` work. I'm unhappy with the `int` conversions, but I am pleased with the succinctness of `fold` and `zipWithIndex`. ]
[Question] [ # Code Bots I hate private and protected variables. I just want to access anything and everything! If you are like me, then this challenge is for you! Write a bot that ~~works together in harmony with other bots~~ makes other bots do what you want. You are a programmer, and you know how things are supposed to work. Your job is to convert as many other bots to your ways as possible. # The Code You will have 24 lines of code to write your bot. Each turn, every bot will execute 1 line sequentially. Each bot stores 5 variables `A` through `E`. `A` and `B` are for personal use, `C` stores the next line to execute, `D` stores the current direction, and `E` is a random number. The variables start at 0, except for `D`, which will start at a random value. All variables have only store 0-23. Numbers larger or smaller will be modulated by 24. In this post, I will use opponent to be the adjacent bot you are facing Each line must contain one of the following 5 commands: 1. `Flag` does nothing. Except it's how you win 2. `Move` moves your bot in the `D`th direction. If a bot already occupies the space, no move will happen 3. `Copy Var1 Var2` copies the contents of Var1 into Var2 4. `If Condition Line1 Line2` If Condition is true, executes Line1, else Line2 5. `Block Var1` blocks the next write on a variable A variable can be used as follows: `#Var` will use the variable as a line number. If `A` is 17, `Copy #8 #A` will copy the contents of line 8 onto line 17. `*Var` will use the variable of your opponent. `Copy 5 *C` will set the opponent's `C` variable to `5` `Var+Var` will add the two variables. `Copy D+1 D` will rotate the bot to the right When `D` is used as a direction, `[North, East, South, West][D%4]` will be used These modifiers can be chained: `Copy *#*C #9` will copy the next line your opponent will execute into your own code on line 9. `**D` refers to your opponent's opponent's `D` variable. A Condition will be evaluated as follows: 1. If `Var`: 1. If Var is `A` through `C`, it will return true if Var is nonzero, else false. 2. If Var is `D`, it will return true if there is a bot in the `D`th direction, else false 3. If Var is `E`, it will return true if E is odd, else false 4. If Var is a line, it will return true if it is a Flag line 2. If `Var1=Var2`: 1. Returns true if both are `A-E`, and equal the same number 2. Returns true if both are lines, and the line type is equal 3. If `Var1==Var2`: 1. Returns true if both are `A-E`, and equal the same number 2. Returns true if both are lines, and are identical (Flags from different bots will not be equal) 50 bots of each type will be placed in a toroidal world in the following pattern: ``` B...B...B...B... ..B...B...B...B. B...B...B...B... ..B...B...B...B. ``` After each game of 5,000 turns, the flags on each bot will be counted. You get a point if a bot has more of your flag than any other type of flag. If the case of a tie between `N` bots, no points are given. There will be 10 games, and scores will be accumulated at the end. # Side Notes End of line comments are allowed, and are denoted with `//` Attempting to do something that doesn't make sense, such as adding to a line will do nothing Attempting to do something on a non-existent bot will do nothing ## Infinite recursion on an `If` will end with no line being executed `If` does not change the value of `C` A `Block` doesn't expire until somebody attempts to write to it Multiple variables and lines can be blocked at once `Block`ing a variable multiple times will block multiple times as long as the second block statement is on a different line of code than your first Spaces are only allowed between arguments (and after the command) If a bot is shorter than 24 lines, Flag will be the rest of the lines. # Sample Program ``` Copy 2 C //Skip to the If line Flag //Where I'm storing my flag Move //Move in the D'th direction If D #5 #2 //If there's a bot, copy code, otherwise, move! Copy #1 *#E //Copy my flag onto a random spot in my bot's code Copy 2 C //Skip back to the If line ``` The program will be run by my Python controller [here](https://github.com/thenameipicked/CodeBots). **The Java controller is [here](https://github.com/thenameipicked/CodeBotsJava)** It is *fast* and looks much better than the python one. Scoreboard: 1. 6837 [$Copy](https://codegolf.stackexchange.com/a/37312/) 2. 3355 [Lockheed](https://codegolf.stackexchange.com/a/37253/) 3. 1695 [MindControl](https://codegolf.stackexchange.com/a/37711) 4. 967 [Byzantine](https://codegolf.stackexchange.com/a/37106) 5. 959 [AttackOrElse](https://codegolf.stackexchange.com/a/37208) 6. 743 [Cadmyllion](https://codegolf.stackexchange.com/a/37116) 7. 367 [Influenza](https://codegolf.stackexchange.com/a/37049/) 8. 251 [TheCommonCold](https://codegolf.stackexchange.com/a/37023) 9. 226 [Magus](https://codegolf.stackexchange.com/a/37011) 10. 137 [HideBlockAttack](https://codegolf.stackexchange.com/a/37016/) 11. 129 [RowBot](https://codegolf.stackexchange.com/a/37050/) 12. 123 [FastMoveCloneDodge](https://codegolf.stackexchange.com/a/36990) 13. 112 [FastForwardClone](https://codegolf.stackexchange.com/a/36989/) 14. 96 [QuickFreeze](https://codegolf.stackexchange.com/a/36993/) 15. 71 [RepairAndProtect](https://codegolf.stackexchange.com/a/36996) 16. 96 [SuperFreeze](https://codegolf.stackexchange.com/a/36998) 17. 93 [RovingVirus](https://codegolf.stackexchange.com/a/37022/) 18. 80 [ForwardClone](https://codegolf.stackexchange.com/a/36988) 19. 77 [FreezeTag](https://codegolf.stackexchange.com/a/36997/) 20. 68 [Palimpseste](https://codegolf.stackexchange.com/a/37084/) 21. 62 [BlockFreezeAttack](https://codegolf.stackexchange.com/a/37002) 22. 51 [RushAttackDodge](https://codegolf.stackexchange.com/a/36984/) 23. 46 [Blocker](https://codegolf.stackexchange.com/a/36980/) 24. 40 [TurretMaker](https://codegolf.stackexchange.com/a/37074/) 25. 37 [Copycat](https://codegolf.stackexchange.com/a/36981) 26. 37 [Kamikaze](https://codegolf.stackexchange.com/a/37215) 27. 35 [FlagInjector](https://codegolf.stackexchange.com/a/37067/) 28. 33 [RandomCopier](https://codegolf.stackexchange.com/a/36982) 29. 31 [Insidious](https://codegolf.stackexchange.com/a/37055/) 30. 29 [HappyAsAClam](https://codegolf.stackexchange.com/a/37303) 31. 25 NanoVirus 32. 21 [Nullifier](https://codegolf.stackexchange.com/a/37083/) 33. 19 [Nanoviris](https://codegolf.stackexchange.com/a/37026) 34. 17 [BoringCopybot](https://codegolf.stackexchange.com/a/36999) 35. 16 [Movebot](https://codegolf.stackexchange.com/a/36994/) 36. 14 [Flagbot](https://codegolf.stackexchange.com/a/36992) 37. 13 [Neutralizer](https://codegolf.stackexchange.com/a/37066/) 38. 12 [Cancer](https://codegolf.stackexchange.com/a/37054) 39. 9 [DNAbot](https://codegolf.stackexchange.com/a/36987) 40. 9 [Parasite](https://codegolf.stackexchange.com/a/37017) 41. 8 [MetaInsidious](https://codegolf.stackexchange.com/a/37060) 42. 8 [Rebranding](https://codegolf.stackexchange.com/a/37072/) 43. 8 [AdaptiveBot](https://codegolf.stackexchange.com/a/37098/) 44. 8 [ReproducingBot](https://codegolf.stackexchange.com/a/37015) 45. 8 [KungFuBot](https://codegolf.stackexchange.com/a/37046) 46. 5 [QuickFreezerbot](https://codegolf.stackexchange.com/a/37004) 47. 4 [Attacker](https://codegolf.stackexchange.com/a/36979/) [Answer] # Flagbot ``` Flag ``` Why bother doing anything when other bots are going to be nice enough to give me their code? [Answer] # Freeze Tag ``` Move If D #3 #2 Copy 23 C Copy 3 C Copy #23 *#*C Copy #21 *#*C+1 Copy #22 *#*C+2 Copy #21 *#*C+3 Copy #22 *#*C+4 Copy #21 *#*C+5 Copy #22 *#*C+6 Copy #21 *#*C+7 Copy #22 *#*C+8 Copy #21 *#*C+9 Copy #22 *#*C+10 Copy #21 *#*C+11 Copy #22 *#*C+12 Copy #21 *#*C+13 Copy #22 *#*C+14 Copy D+1 D Copy 0 C Flag Flag Copy C+23 C ``` Trap opponent in a loop, fill him with flags, move on to next opponent. [Answer] # Parasite Why kill other bots? This bot looks through opponent's code and replaces only the flags. ``` Copy 1 A Copy E D Block #A If *#A #C+3 #C Copy A+A+A+A+A A Copy C+19 C Copy #C+4 *#A Flag Copy 1 A Copy E D Block #A If *#A #C+3 #C Copy A+A+A+A+A A Copy C+19 C Copy #C+4 *#A Flag Copy 1 A Copy E D Block #A If *#A #C+3 #C Copy A+A+A+A+A A Copy C+19 C Copy #C+4 *#A Flag ``` [Answer] # $Copy This bot uses much of the same techniques as COTO's Lockheed, so I will shamelessly borrow and enhance. This exploits a `C` vulnerability to break blocks and even reverses the neutralizer. It is also written in absolutes because of this. I think this might break if the `C` shift is reinstated, but as long as the shift is constant, it can be rewritten to combat it. For whatever reason, the lack of loop at the end made this bot super good. ``` Block #C+A If D #7 #13 //If [enemy] Copy 0 ELSE block If D #8 #0 //If [enemy] Freeze 0 ELSE block If D #9 #6 //If [enemy] FreezeCheck ELSE Inc Move Copy 0 C Copy A+5 A //Inc Copy 23 *C //Copy 0 Copy #10 *#*C+23 //FreezeAttack If *#*C==#10 #11 #5 //FreezeCheck: If [frozen] GOTO Copy Attack ELSE GOTO [1] Copy C+23 C //FREEZE Copy 13 C //GOTO Copy Attack Copy 15 C //Loop Copy Attack Block #C+A Copy D+3 *D //Copy Attack: Spin Enemy Copy 0 *B //Set enemy counter (a la COTO) Copy #*B+0 *#*C+*B+1 //Copy my lines Copy #*B+1 *#*C+*B+2 //Copy my lines Copy #*B+2 *#*C+*B+3 //Copy my lines Copy *B+3 *B //Inc counter If *B==0 #19 #12 //Loop check Copy D+1 D //Turn myself ``` [Answer] # Lockheed My third (and likely final) submission to this particular bot war: the Lockheed Reactor, or "Lockheed" for short. ``` Block #C+A If D #C+7 #C+1 Block #C+A Move Copy A+5 A If A==0 #C+12 #C+21 Copy C+17 C Copy D+3 *D Copy C+9 C Copy C+21 C Copy C+23 C Copy #C+23 *#*C+2 Copy #C+22 *#*C+1 Copy 0 *A Copy #*A+C+9 *#*C+*A+1 Copy *A+1 *A If *A==0 #C+15 #C+17 Copy D+1 D Copy C+5 C ``` Special thanks goes to @Wasmoo, who shared his discovery of the "'Blocking a variable multiple times will block multiple times as long as the second block statement is on a different line of code than your first.' simply isn't true" exploit. I make extensive use of it. Also, thanks goes to Nathan Merill for administrating the competition and for publishing the simulator. The simulator is utterly invaluable in tuning bots. I wouldn't have believed it if I hadn't simulated it with my own eyes, but the addition or removal of the most conceptually minor bot feature can mean the difference between great success and abject failure. I'm torn as to whether that's a good thing or not. [Answer] # Attack Or Else Seeing as defensive robots like Byzantine were doing so well, I decided to make a defensive robot as well. This has two sets of patterns, depending on whether or not the enemy is present. * If the enemy is not present, it blocks its lines for 3 turns and then moves. * If the enemy is present, ~~it alternates between copying its flag and copying code that will cause the enemy to copy that flag (a weak replicator)~~ it copies its flag * At the end of the loop, it changes to a random direction and continues * Most aspects of its code is duplicated More testing showed a few important concepts: * "Turn random" performed dramatically better than "Turn right" (+2700 over alternative) * Block increment of `A+7` shown to be more effective than any other increment (+200 over next best) * "Direct attack" shown to be better than "Weak replicator" (+900 over alternative) * Defense of "3-1-2-1" better than other combinations (+200 over next best) * Duplicated attack, block, and loop code improves its score (+300 over non-duplicated) * Duplicated block increment does not improve its score (+400 over duplicated) Observing the simulation graphically via the Java UI helped a lot. Thank you! Below is the new and improved code. I don't think I can do anything more. ``` Block #C+A //Dynamic block for If statements If D #20 #0 If D #19 #8 If D #20 #23 If D #19 #0 If D #20 #8 If D #19 #23 Copy A+7 A //Increment dynamic block Block #C+A //Dynamic block for If statements If D #19 #8 If D #20 #0 If D #19 #8 If D #20 #23 If D #19 #8 If D #20 #0 If D #19 #23 Copy E D //Turn Random Copy 23 C //Loop to beginning Copy 23 C //Loop to beginning Copy #22 *#*C+1 //Copy my flag to the enemy's next Copy #21 *#*C+1 //Copy my flag to the enemy's next Flag Flag Move ``` [Answer] # Row Bot ``` Move If D #7 #0 If D #7 #0 If D #7 #0 If D #7 #0 If D #7 #0 Copy 0 C If D=*D #9 #8 //If they point in a different direction Copy *D D //fix that If #A==*#A #10 #11 //Did we copy line A already? Copy A+1 A //If so, A++ Copy #A *#A //else, copy it! ``` Will move until it finds a robot. Will set that robot in the same direction as itself. Will then copy its code into the robot. This should make a row of "Row Bot" Robots. :) [Answer] # Super Freeze ``` Move // start moving! Block #E If D #12 #0 // 8 turns of attack or move If D #12 #0 If D #12 #0 If D #12 #0 If D #12 #0 If D #12 #0 If D #12 #0 If D #12 #0 Copy D+1 D // change direction Copy 0 C // start over If *#*C==#23 #13 #14 // if opponent is frozen, give them a flag, otherwise freeze them Copy #C+13 *#E // give a flag to opponent Copy #23 *#*C // copy freeze line to opponent Flag // 8 flags, one per If above Flag Flag Flag Flag Flag Flag Flag Copy C+23 C // this line freezes any bot that executes it ``` This bot keeps trying to freeze the bot in front of it until it works, then writes a bunch of flags to random lines, and after 8 turns of that it rotates and moves on to another opponent. [Answer] # Byzantine A highly defensive bot that institutes multiple blocks on its flags and most sensitive instructions, including meta-blocks (i.e. blocks on critical block instructions). It also moves constantly in unpredictable ways, and plants flags in numerous locations on opponents on a best-effort basis. ``` Block #A Block #A+1 Block #A+2 Copy E D Move Block #A+3 Block #A+4 Move Copy #22 *#*C+1 Copy E D Move Block #A+5 Block #A+6 Block #A+7 Move Copy #22 *#23 Block #A+8 Block #A+9 Block #A+10 Copy #22 *#2 Copy A+14 A Move Flag Copy #22 *#*C+12 ``` Not sure how it will perform, since I can't simulate. But we'll give it a shot. ;) --- ### Disclaimer I wrote this before being kindly informed by PhiNotPi that conditional logic is cost-free. However, I've decided to leave it in since one can never have too many bots. [Answer] # Cadmyllion "I just entered a bot in the battle royale," I say. "It moves every few turns to prevent attacks by slower bots." "What do you mean by slower bots?" PhiNotPi asks. "Bots that are stuck evaluating long chains of conditional logic," I reply. "'If' statements that redirect to other statements---including other 'if' statements---are all executed on the same turn," says PhiNotPi. "Sweet massacred rules of assembly code!" I cry. "Who came up with that idea?" ...and thus is the story of how Cadmyllion came about. Cadmyllion: the bot that happily exploits the surreal ability to evaluate infinitely many conditional expressions in a single instruction... by making pretty much every thing it does conditional. ### Code ``` If D #15 #19 Move If D #16 #20 Copy D+3 D Block #A If D #15 #20 Copy A+1 A If D #16 #1 Move If D #15 #19 If D #16 #4 Copy E D Block #A+12 Copy C+10 C Flag If *#0==#14 #17 #21 If *#0==#14 #18 #21 If *#*C+1==#14 #18 #22 Copy *C+11 *C Block #A+6 Block #A+18 Copy #14 *#0 Copy #23 *#*C+1 Flag ``` [Answer] # Meta Insidious This bot freezes and then converts opponents into less efficient versions of [Sparr's Insidious](https://codegolf.stackexchange.com/questions/36978/whats-wrong-with-public-variables/37055#37055), which in their turn, will turn opponents into bots that spam flags for me. This is likely the most complex bot I've written and I thus expect it to do terrible, there was no space for blocking and only one flag fitted in the code. Turning a bot into an insidious clone also takes too long. The biggest challenge was writing the code for the insidious clones in such a way that it works regardless of its position in the bot. The freeze gets removed when I paste the second to last code exactly where the freeze is located, this starts up the opponent just in time. ``` If D #2 #1 Copy 23 C Copy #8 *#*C // freeze the opponent Copy 9 A Copy #A *#A+*C // copy the next line at the appropriate line Copy A+1 A If A==0 #7 #23 Copy 23 C Copy C+23 C If D #C+2 #C+23 // the code for the Insidious clone starts here Copy C+21 C Copy C+2 C If D #C+6 #C+22 If D #C+5 #C+22 If D #C+4 #C+20 If D #C+3 #C+19 If D #C+2 #C+18 Copy E D Copy #C+7 *#*C Flag Copy C+3 A Copy #C+22 #A Copy A+1 A Copy C+21 C // And ends here ``` [Answer] # Repair and Protect This bot repairs its own code, while protecting the newly repaired lines. ``` If #A==#A+16 #C+1 #C Copy #A #A+8 Block #A+8 Copy A+1 A Copy E D Move Copy #C+1 *#*C Flag If #A==#A+16 #C+1 #C Copy #A #A+8 Block #A+8 Copy A+1 A Copy E D Move Copy #C+1 *#*C Flag If #A==#A+16 #C+1 #C Copy #A #A+8 Block #A+8 Copy A+1 A Copy E D Move Copy #C+1 *#*C Flag ``` Explanation: The initial value of `A` is `0`, and the lines are numbered 0-23. If the `If` statement is executed and is false, it does attempt the execute the same line again. The controller does not allow a bot to execute the same line twice, so the turn is ended and `C` is incremented to `1`. The next line, `Copy #A #A+8` is actually performed regardless of the value of the `If` statement. The difference is that it is executed twice if true and once if false. If the line `#A+8` is blocked (which happens eventually), then performing it twice with actually copy, while performing it once will only unblock it. Then, the newly copied line is blocked to preserve it. [Answer] # Neutralizer This bot makes its victim rewrite its entire program, making it worth 0 points. Once the virus is in place, it moves on. This is a scorched earth approach to victory. ``` If D #C+2 #C+3 // A: If [enemy exists] B else C Copy C+22 C // GOTO A If *#*C==#7 #C+4 #C+5 // B: If [enemy was neutralized] D else E Move // C: Move Copy E D // D: Turn Randomly Copy #7 *#*C // E: Neutralize enemy Copy C+1 C // Skip the next line Copy #C #C+1 // Neutralizing Code [Copy this line to next line] ``` The comparison `*#*C==#7` doesn't seems to adjust for the opponent's shift correctly, but the bot does eventually move on. [Answer] # Insidious ``` Move If D #4 #0 If D #4 #0 Copy 0 C Copy 4 C If D #12 #11 If D #12 #11 If D #12 #11 If D #12 #11 If D #12 #11 Copy D+1 D If D #4 #3 Copy #C+8 *#*C Flag Copy C A Copy #C+22 #A Copy A+23 A Copy C+21 C ``` Inspired by @Cruncher, this bot infects other bots with a small block of code, filling the other bot with this bot's flags. Those bots are then sitting ducks for further attack, but they will be mostly full of my flags when they get re-infected by someone else. Edit: thanks to @PhiNotPi for golf assistance, @overactor for efficiency advice [Answer] # Happy As A Clam This is an exercise in blocking. It performed remarkably well until [`$Copy`](https://codegolf.stackexchange.com/a/37312/) came around. The clam has 22 block commands. Because `A` is shifted every loop, they will reference different lines each time through the loop. This allows each command to stack blocks on every other line, maxing out at 22 blocks per line. Thus, to break the fully armored clam, one would need to write to a line 22 times. For example, `#10` will be protected each time through the loop by the following lines: * Loop 0, A=0 `#10` protected by line 7 (`7+0+3`=10) * Loop 1, A=7 `#10` protected by line 0 (`0+7+3`=10) * Loop 2, A=14 `#10` protected by line 17 (`17+14+3`=34=10) * Loop 3, A=21 `#10` protected by line 10 (`10+21+3`=34=10) So after Line 10 of Loop 3, `#10` has been blocked 4 times, requiring 4 writes to `#10` to break the blocks, with a 5th one to actually overwrite the line. Note that blocks are keyed by their `C` value and will **not** stack if the protected line was already blocked by the same `C` value. So after 22 blocks are established for each line, the blocks will no longer stack. ``` Block #C+A+3 Block #C+A+3 Block #C+A+3 Block #C+A+3 Block #C+A+3 Block #C+A+3 Block #C+A+3 Block #C+A+3 Block #C+A+3 Block #C+A+3 Block #C+A+3 Block #C+A+3 Block #C+A+3 Block #C+A+3 Block #C+A+3 Block #C+A+3 Block #C+A+3 Block #C+A+3 Block #C+A+3 Block #C+A+3 Block #C+A+3 Block #C+A+3 Copy A+7 A Flag ``` [Answer] ## MindControl I guess it's never too late? ``` Block #C+D If D #2 #0 // Scan for enemy If *#E==#E #0 #5 // Attack if necessary Copy D+5 D // Turn Copy 22+1 C // Repeat Copy 4+1 C // ATTACK: Copy #22+1 *#*C // Freeze Copy #17 *#17 // Upload the DOWNLOADER Copy #18 *#18 // Copy #21 *#19 // Copy D+2 *D // FACE ME!! Copy 17 *C // Start download If E #0 #13 If E #0 #13 Copy 22+1 C Flag Flag Copy *#B+20 #B+20 // DOWNLOADER If *#B+20==#B+20 *#20 #19 // Copy 22+1 C // Copy 1+B B // Copy 16 C // Flag Copy 23+C C // FREEZE ``` MindControl comes from my idea that it would take some considerable time to copy my whole program to the opponent, during which my bot is vulnerable to attacks from other directions. So why not make the opponent copy my program while I scan for enemies? Once it finds an enemy, MindControl immediately freezes the enemy to prevent escape. Then it uploads the downloader to the opponent and let the victim download MindControl's program itself. The downloader exploit the fact that few bots uses `B` and will loop until it downloads all 24 lines. When the downloader rewrites `#19` from `Copy 16 C` to `Copy 23 C`, it signifies the victim have downloaded all lines and will go on to reboot itself. The first versions of my bot does not include Blocks. And it was so vulnerable that almost any change is crippling. So I decided to add Blocks based on Wasmoo's $Copy (which is based on COTO's Lockheed). The downside I found is that it is difficult for the original to correct mistakes in the copies. But this is far from crippling and the score increased significantly so I kept the Blocks. ## UPDATES I improved the downloader to keep trying to download until a successful rewrite to circumvent blocks. It does mean it takes one more turn to upload the downloader but my score doubled after this change!! Can't argue with numbers. --- Another update. As you may have noticed, MindControl decides whether to attack target by comparing a random line between itself and its target. If they match, MindControl just assumes the target is already infected and leave it alone. (Side note: I used to use a static line for comparison but that gives lots of false positives and negatives) Turns out that gives a lot of false negatives. So I decided to exploit `==` and make some trivial changes like `C+23` to `23+C`. The program is functionally identical but different in the eyes of `==`. Now that MindControl has no line that is identical to any line in any other bot, it will 100% hit any untouched bot. Again, score increased significantly. --- Improved the Downloader again. It now runs on a shorter loop. (which seems to have a large correlation with my score) --- Improved Downloader yet again. Uses original bot's code so it uploads faster. Also added 2 random blocks which seems to improve score [Answer] # Attacker ``` Copy #E *#*C Copy #E *#*C Copy #E *#*C Copy #E *#*C Copy #E *#*C Copy #E *#*C Copy #E *#*C Copy #E *#*C Copy #E *#*C Copy #E *#*C Copy #E *#*C Copy #E *#*C Copy #E *#*C Copy #E *#*C Copy #E *#*C Copy #E *#*C Copy #E *#*C Copy #E *#*C Copy #E *#*C Copy #E *#*C Copy #E *#*C Copy #E *#*C Copy #E *#*C Flag ``` [Answer] # Movebot ``` Move Copy 23 C Flag ``` Like Flagbot, but move around while accepting gifts of code to go with all of our flags. [Answer] # Reproducing bot This bot tries to freeze his opponent and then copy his entire code into that bot before restarting the other bot. This should also work (mostly) if the opponent uses blocking, though that does make it all even slower than it already is. ``` If D #23 #22 Copy 23 C Copy #18 *#*C Copy #18 *#*C+1 Copy #18 *#*C Copy #18 *#0 Copy #18 *#0 Copy 0 *C Copy 0 *C Copy 1 A Copy #A *#*A If D #12 #14 Copy A+1 A Copy 9 C Copy 23 C Flag Flag Flag Copy C+23 C Copy D+1 D Flag If *#*C==#*C #19 #13 Move If *#*C+1==#*C+1 #21 #13 ``` [Answer] # Magus Magus is a simple attempt at a self-propagating virus. It attempts to copy itself into the programs of other bots. (Edited to remove negative numbers, fix condition, trim lines.) ``` Block #A Copy #A *#A Copy A+1 A If A #0 #4 Copy 0 *C Flag Move Copy 0 C ``` [Answer] # DNAbot ``` Flag Copy 8 D Copy 16 B If #D==#B #C+2 #C+3 Block #A Copy #D #A If D #7 #15 Copy #23 *#*C Copy A+1 A Copy B+1 B Copy D+1 D If #D==#B #C+2 #C+3 Block #A Copy #D #A If D #7 #15 Move Copy A+1 A Copy B+1 B Copy D+1 D If #D==#B #C+2 #C+3 Block #A Copy #D #A If D #7 #15 Flag ``` This bot repairs its own code while moving and attacking. [Answer] # Blocker ``` Copy A+1 A Block #A Copy C+22 C ``` [Answer] # Copycat ``` If D #4 #3 Move Copy 23 C Copy *#*C #1 Copy #23 *#E ``` [Answer] # Quick freezerbot Tries to copy flags in the line that will get executed next of his opponent, moves if there is no enemy to attack. ``` Block #13 Block #14 If D #13 #14 If D #13 #14 If D #13 #14 If D #13 #14 If D #13 #14 If D #13 #14 If D #13 #14 If D #13 #14 If D #13 #14 If D #13 #14 Copy 23 C If E #15 #16 Move Copy #23 *#*C Copy D+1 D ``` [Answer] # Block, Freeze, Attack ``` Block #A // start block loop Copy A+1 A // loop A from 0 to 23 If A #3 #4 Copy 23 C // repeat block loop Copy 5 C // exit block loop to attack/move loop Move If D #11 #5 // attack or move Copy A+1 A // loop A from 0 to 23 If A #9 #10 Copy 5 C // repeat attack/move loop Copy 23 C // exit attack/move loop to block loop Copy 11 C // start of attack routine Copy #23 *#*C // freeze opponent Copy #19 *#E // copy flag to opponent Copy #20 *#E // copy flag to opponent Copy #21 *#E // copy flag to opponent Copy #22 *#E // copy flag to opponent Copy D+1 D // change direction Copy 5 C // repeat attack/move loop Flag Flag Flag Flag Copy C+23 C // freeze instruction, for copying ``` Blocks all 24 lines, then loops 24 times either moving or attacking, then repeats. An attack involves attempting to freeze the opponent, then copying four flags to random locations, then turning. [Answer] # Hide, Block, Attack This bot is based off of Block Freeze Attack. I changed the placement of some `If` statements to make it more compact allowing me to plant more flags. I also have it run away at the start of a game to buy some time to block. ``` Copy D+1 D Move //buy some time by moving to a more secure location Block #A+2 Copy A+1 A If A #11 #17 Copy #23 *#E Copy #22 *#E Copy #21 *#E Copy #20 *#E Copy #19 *#E Copy D+1 D Copy 1 C Move If D #14 #15 Copy 3 C Copy 11 C Copy #18 *#*C If D #16 #15 Copy C+23 C Flag Flag Flag Flag Flag ``` [Answer] # Roving Virus ``` If D #6 #16 Move Copy 23 C Flag Flag Flag Copy 6 C Copy A+23 A Copy #A *#A //clone previous line to enemy Copy 23 *C //freeze enemy If A #6 #16 //loop or turn then continue Copy 0 *C //reboot enemy Copy 23 C //start moving again Flag Flag Flag Copy D+1 D //turn Flag Flag Flag Flag Flag Flag Copy 22 C //freeze instruction ``` This bot wanders until it finds an enemy, then freezes them, replaces all of their code with its own, unfreezes them, then wanders again. [Answer] # The common cold It infects you virtually immediately and you'll spread it around. based on [PhiNotPi's Parasite](https://codegolf.stackexchange.com/questions/36978/whats-wrong-with-public-variables/37017#37017), the common cold checks almost immediately if it can copy its flag over yours. Blocks a random value if it can't. Moves around a bit if there's no opponent. ``` Block #22 If D #8 #5 If D #8 #5 If D #8 #5 Copy 23 C If E #6 #7 Copy D+1 D Move If *#E=#22 #15 #9 If *#E+1=#22 #16 #10 If *#E+2=#22 #17 #11 If *#E+3=#22 #18 #12 If *#E+4=#22 #19 #13 If *#E+5=#22 #20 #14 If *#E+6=#22 #21 #23 Copy #22 *#E Copy #22 *#E+1 Copy #22 *#E+2 Copy #22 *#E+3 Copy #22 *#E+4 Copy #22 *#E+5 Copy #22 *#E+6 Flag Block #E ``` [Answer] # Influenza This is closely based off of the Common Cold (which was based off my Parasite) with slightly increased speed. ``` Move Block #23 If D #8 #0 If D #8 #0 If D #8 #0 If D #8 #7 Copy 0 C Copy D+1 D If *#E #9 #10 Copy #23 *#E If *#E+1 #11 #12 Copy #23 *#E+1 If *#E+2 #13 #14 Copy #23 *#E+2 If *#E+3 #15 #16 Copy #23 *#E+3 If *#E+4 #17 #18 Copy #23 *#E+4 If *#E+5 #19 #20 Copy #23 *#E+5 If *#E+6 #21 #22 Copy #23 *#E+6 Block #E Flag ``` [Answer] # Rebranding ``` Move If D #10 #0 If D #10 #0 If D #10 #0 If D #10 #0 If D #10 #0 If D #10 #0 If D #10 #0 If D #10 #0 Copy 0 C If *#E=#14 #11 #9 If *#E==#14 #13 #12 Copy D+1 D Copy #14 *#E Flag ``` This bot tries to randomly locate flags in enemy bots and replace them with friendly flags, turning away after detecting success. Inspired by Cancer bot. ]
[Question] [ I absolutely hate the digit `1`. So, I need your help to convert numbers to their "proper forms". Numbers in proper form never have two `1`s in a row. `101` is okay, but `110` is hideous. To convert, simply skip all the improper numbers and count normally. For instance... ``` 1 -> 1 2 -> 2 ... 10 -> 10 11 -> 12 12 -> 13 ... 108 -> 109 109 -> 120 110 -> 121 111 -> 122 ``` and so on. Your program should take an integer and output it in proper form. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. [Answer] # Bash + GNU utils, 36 ``` seq $1$1|grep -v 11|sed -n "$1{p;q}" ``` [Try it Online](https://tio.run/##S0oszvj/vzi1UEHFUMWwJr0otUBBt0zB0LCmODVFQTdPQUnFsLrAurBW6f///4YgAAA) [Answer] ## [Burlesque](http://mroman.ch/burlesque), 10 bytes [{11~[n!}FO](http://104.167.104.168/~burlesque/burlesque.cgi?q=150%7B11~[n!%7DFO) Older versions: ``` ro{11~[n!}f[ ro{Sh"11"~=n!}f[ ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` 1w11¬$#Ṫ ``` [Try it online!](https://tio.run/##y0rNyan8/9@w3NDw0BoV5Yc7V/3/b2RgAAA "Jelly – Try It Online") Almost entirely printable ASCII! Takes input from STDIN ## How it works ``` 1w11¬$#Ṫ - Main link. No arguments $ - Group the previous 2 links into a monad f(k): 11 - Yield 11 w - Yield 1 if 11 is a sublist of k's digit else 0 ¬ - Map 1 to 0 and 0 to 1 1 # - Count up k = 1, 2, 3, ... until n integers return true under f(k) Ṫ - Return the last k ``` --- # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ²wÐḟ11ị@ ``` [Try it online!](https://tio.run/##ASIA3f9qZWxsef//wrJ3w5DhuJ8xMeG7i0D/MjAwO8OHJOKCrEf/ "Jelly – Try It Online") An alternate approach, still only 8 bytes though. Relies on the assumption that the output is always less than the square of the input ## How it works ``` ²wÐḟ11ị@ - Main link. Takes n on the left ² - n² Ðḟ - Filter-false the range [1, 2, ..., n²] on: 11 - 11 w - Is a sublist of the digits ị@ - Take the n'th value in this list ``` [Answer] # JavaScript, 53 bytes ``` n=>[...Array(n*2).keys()].filter(a=>!/11/.test(a))[n] ``` Alternate (using comprehensions, same length): ``` n=>[for(i of Array(n*2).keys())if(!/11/.test(i))i][n] ``` [Answer] # [Perl 5](http://dev.perl.org/perl5/), 34 Bytes Looping a counter and changing the occasional double-one. ``` map{$i++;$i=~s/11/12/}1..pop;say$i ``` ### Test ``` $ perl -M5.012 -e 'map{$i++;$i=~s/11/12/}1..pop;say$i' 111 $ 122 ``` [Answer] ## Python 2, 50 ``` lambda n:[i for i in range(n*2)if'11'not in`i`][n] ``` An anonymous function that lists the numbers not containing `11` in order, and takes the `n`th one. The off-by-one error of zero-indexing cancels with the inclusion of `0` in the list. In theory, this will fail for sufficiently high numbers where `f(n)>2*n`, but this shouldn't happen until `n` is at least `10**50`. --- 51 bytes: ``` n=input();i=0 while n:i+=1;n-='11'not in`i` print i ``` Counts up numbers `i` until the quota of `n` numbers without `11` is met. A function is the same length because of the off-by-one corrections needed. ``` f=lambda n,i=0:n+1and f(n-('11'not in`i`),i+1)or~-i ``` [Answer] # Pyth, ~~13~~ 11 bytes ``` e.f!}`hT`ZQ ``` Saved 2 bytes thanks to @FryAmTheEggman. [Live demo and test cases.](https://pyth.herokuapp.com/?code=e.f%21%7D%60hT%60ZQ&test_suite=1&test_suite_input=1%0A2%0A10%0A11%0A12%0A108%0A109%0A110%0A111&debug=1) ## 13-byte version ``` e.f!}"11"+ZkQ ``` [Answer] # Python 3 74 Still need a bit of golfing. ``` n=int(input()) c=0 for x in ' '*n: c+=1 while'11'in str(c):c+=1 print(c) ``` It's pretty brute force right now. [Answer] # JavaScript (ES6) 43 bytes As an anonymous function ``` n=>eval('for(i=0;/11/.test(i)||n--;i++);i') ``` Note: the very simplest way would be 44: ``` n=>{for(i=0;/11/.test(i)||n--;i++);return i} ``` Test running the snippet below. ``` f=n=>eval('for(i=0;/11/.test(i)||n--;i++);i') var o='',v=0,r,c; for(r=0;r<30;r++) { o += '<tr>'; for(c=0;c<10;c++) { o += '<td>' +v + '⇨' + f(v) + '</td>'; v++; } o += '</tr>' } O.innerHTML=o ``` ``` <table id=O style='font-size:80%'></table> ``` [Answer] # Haskell, 51 bytes ``` ([x|x<-[0..],notElem('1','1')$zip=<<tail$show x]!!) ``` Usage example: `([x|x<-[0..],notElem('1','1')$zip=<<tail$show x]!!) 110` -> `121`. How it works: ``` [x|x<-[0..] ] -- take all x starting with 0 , -- where ('1','1') -- the pair of two chars '1' notElem -- is not part of zip=<<tail -- the list of pairs of neighbor elements of show x -- the string representation of x !! -- take nth element, where n is the parameter ``` [Answer] # MUMPS, 37 bytes ``` t(i) f j=1:1 s:j'[11 k=k+1 q:k=i q j ``` Pretty straightforward. The only "interesting" thing here is the construct `j'[11` - `'[` is the "does not contain" operator, so that `"abc"'["ab"` is false and `"abc"'["cd"` is true. Despite both operands of `j'[11` being numbers, MUMPS remains unperturbed. It will happily autocoerce both operands to strings and move on with its life. Hooray! (Incidentally, if you're okay with the program never terminating, we can shorten this to 35 bytes: `t2(i) f j=1:1 s:j'[11 k=k+1 w:k=i j`) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes ``` ∧{ℕ₁≜¬s11&}ᶠ↖?t ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSu9qhtw6Ompoe7Omsfbp3w/1HH8upHLVMfNTU@6pxzaE2xoaFa7cNtCx61TbMv@f8/2lDHSMfQQMfQUMcQxLAAYksgDyRiGAsA "Brachylog – Try It Online") ``` ∧{ℕ₁≜¬s11&}ᶠ↖?t ∧{ … }ᶠ↖?t get the N'th output from … ℕ₁≜ try a number, starting with 1 ¬s11 doesn't contain 11 & output that number ``` [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), ~~29~~ ~~24~~ 18 bytes ``` ~0\{{).`11`?)}do}* ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v84gprpaUy/B0DDBXrM2Jb9W6/9/Q0NDAA "GolfScript – Try It Online") This is my first code golf, so this is probably the least effecient way of doing things -5 bytes by not being dumb and using the increment symbol as well as just keeping the input on the stack and decrementing instead of wasting space saving it as a variable and comparing it, probably more things I could save on -6 bytes the loop is fixed size and I don't need the input after the loop so I can just use repeat [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~7~~ 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` µN11å≠ ``` -1 byte switching to the legacy version of 05AB1E, where the index is output implicitly after a while-loop `µ`. In the new 05AB1E version we have to push the `N` explicitly, and it'll output the top of the stack after the while-loop instead (so the `N` would be `NN` or `ND`). [Try it online](https://tio.run/##MzBNTDJM/f//0FY/Q8PDSx91Lvj/39DQAAA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKS/bntfodX@P8/tNXP0PDw0kedC/7X@un8jzbUMdIxNNAxNNQxBDEsgNgSyAOJGIKwoWEsAA). **Explanation:** ``` µ # Loop until the counter_variable is equal to the (implicit) input-integer: # (the counter_variable is 0 by default) N11å # Check if the 0-based loop-index `N` contains 11 as substring ≠ # Invert this boolean (1→0; 0→1) # (implicitly pop the top of the stack, and increase the counter_variable by # 1 if it's truthy) # (after which the index `N` is output implicitly as result) ``` [Answer] ## Perl 5, 47 bytes ``` @_[$_]=++$i!~/11/?$i:redo for 1..<>;print$_[-1] ``` [Answer] # PHP, 43 bytes ``` while(preg_match('/11/',$i)){$i++;}print$i; ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 25 bytes ``` $\++while$\=~/11/||$_--}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lRlu7PCMzJ1UlxrZO39BQv6ZGJV5Xt7b6/39DA4t/@QUlmfl5xf91CwA "Perl 5 – Try It Online") [Answer] # [Raku](http://raku.org/), 24 bytes ``` {grep(?1^/11/,^∞)[$_]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Or0otUDD3jBO39BQXyfuUcc8zWiV@Nja/8WJlQq5iQVAVToKNoYKRgrGCoYGCoaGCoZGQIYFEFsCeSARQ7v/AA "Perl 6 – Try It Online") `grep(..., ^∞)` filters the numbers from zero to infinity according to the given test object, and `[$_]` indexes into that sequence with the function argument, returning the number at that index. `/11/` matches any number whose decimal representation contains two consecutive one digits. The sense of the match can be inverted by writing `True ^ /11/`, where `^` creates an exclusive-or junction matcher that succeeds only if exactly one of its operands succeeds. `True` will always succeed, so the overall junction can only succeed if the `/11/` fails. Finally, `True` can be expressed more concisely as `?1`, that is, `1` coerced to a Boolean. `none(/11/)` also works as a matcher, but is longer. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~11~~ 10 bytes *Edit: -1 byte thanks to Razetime* ``` !fö¬€ḋ3QdN ``` [Try it online!](https://tio.run/##ASIA3f9odXNr/23igoHhuKMyMDD/IWbDtsKs4oKs4biLM1FkTv// "Husk – Try It Online") Finds index of input among natural numbers filtered to exclude those with digit-sublists that include `[1,1]`. [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 33 bytes ``` {for(;$1;)$1-=!index(++b,11)}$0=b ``` [Try it online!](https://tio.run/##SyzP/v@/Oi2/SMNaxdBaU8VQ11YxMy8ltUJDWztJx9BQs1bFwDbp/39DA0sA "AWK – Try It Online") It works by running a loop that increments a counter blindly each iteration, but only decrements the control variable if the blind counter does NOT include the string 11. Once the loop exits, the blind counter is printed as the answer. ``` { } - code block run for each input line for(;$1;) - loop until $1 is 0 $1-=!index( ,11) - decrement $1 if "b" doesn't include "11" ++b - blindly increment a counter $0=b - set $0 to blind count, prints automatically ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~9~~ 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` È¥srB}iU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yKVzckJ9aVU&input=MTA5) [Answer] # [Julia 1.0](http://julialang.org/), ~~44~~ 42 bytes ``` x->(r=1:9x)[.!occursin.("11",repr.(r))][x] ``` [Try it online!](https://tio.run/##PY5BDoIwEEXX9hRjV9NYCYMbMSkXaVgYhKSEFFLFcBDjytN5EaSUOpv5f@bNz7RjZ640zQ0omKdjgU7RJZ@ETvZ9VY3ubmyCnIhLVw8uQSdEqadyZs/aGX@EDJYiUAWQXHXmdRY0pesi3VzA4m4F6RTJc0Dz6PMA/29DVEbRb2FLmmCs6R2gka0AY2H9je0GZ@yjs6j59/MGLmHpL@ClxgaNUKoVByolGJ/jJ4LV9jb/AA "Julia 1.0 – Try It Online") [Answer] # Python 3, 64 bytes ``` [print(e) for e in map(str,range(int(input())+1))if not'11'in e] ``` [Try it online!](https://tio.run/##FcoxDoAwCADAr7AVokvtc4xDB6oM0gZx8PWo8914/OhaItZhoo5M0LoBgyicdeDlNlvVnfFX0XE7Ek2ZSBpo95Rz@ipvEXkpLw) [Answer] # [Java (JDK)](http://jdk.java.net/), 76 bytes ``` p->{int c=1,s=0;while((c+s+"").indexOf("11")>=0&&++s>0||c++<p);return p+s;}; ``` [Try it online!](https://tio.run/##XY6xbsMgFEVn@ysQQwSiQXZXgqWOnTJYnaoOxHbSRzEgeE5jJf5211k7XV3p6txjzdXsbf@zwhhDQmK3LicEJ8@T7xCCl@8eP7xJ8zEOyWBIqiw7Z3ImrfH9KdzIvSzidHLQkYwGt7gG6MlowLMWE/jL5xcx6ZL5c1n8xxEgeo375g4eSafrl6wr9fsNbmCsE1lQyiX4frgdz4zWNeWNrnY7IXJTPR6dEIfIVRpwSp5EkdWi1nNI7Amzulb2oOvXSlkh@PZdtHPGYZRhQhk3M3SeWUEJFSBNjG5@y5ses5yrsljKZf0D "Java (JDK) – Try It Online") How it works: Lambda function obviously, but mostly it uses short-circuit logic in the while loop boolean to increment the appropriate counter keeping track of the cumulative shift for each input and returning the input plus that shift. [Answer] # Excel, 64 bytes ``` =LET(x,SEQUENCE(2^20),INDEX(FILTER(x,ISERROR(FIND("11",x))),I7)) ``` Works up to 1,000,579 -> 1,048,576 [Answer] # [Pip](https://github.com/dloscutoff/pip), 11 bytes ``` LaW11N Ui_i ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuharfRLDDQ39tLUz4zMhIlCJpdGGBpaxUA4A) ### Explanation ``` i is 0; a is first command-line argument (implicit) La Loop (a) times: W Loop while 11N 11 is a substring of Ui i, incremented: _ No-op i Once the loop completes, output i ``` ]
[Question] [ This should be a simple challenge. Given a number \$n \ge 0\$, output the [super-logarithm](https://en.wikipedia.org/wiki/Super-logarithm) (or the \$\log^\*\$, log-star, or [iterated logarithm](https://en.wikipedia.org/wiki/Iterated_logarithm), which are equivalent since \$n\$ is never negative for this challenge.) of \$n\$. $$\log^\*(n) = \begin{cases} 0 & \text{ if } n \le 1 \\ 1 + \log^\*(\log(n)) & \text{ if } n > 1 \end{cases}$$ This is one of the two inverse functions to [tetration](https://en.wikipedia.org/wiki/Tetration). The other is the [super-root](https://en.wikipedia.org/wiki/Super-root), which is in a [related question](https://codegolf.stackexchange.com/questions/20308/calculate-the-super-root-of-a-number). ### Examples ``` Input Output 0 0 1 0 2 1 3 2 4 2 ... 15 2 16 3 ... 3814279 3 3814280 4 ``` ### Rules * You do not need to support decimals, though you may. * You need to support input of at least \$3814280 = \left\lceil e^{e^e} \right\rceil\$. * **You may not hard-code the values like `3814280`. (Your program must *theoretically* support higher numbers.) I want an algorithm to be implemented.** * Shortest code wins. [**Related OEIS**](https://oeis.org/search?q=3814280&sort=&language=english&go=Search) [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ÆlÐĿĊḊi1 ``` [Try it online!](http://jelly.tryitonline.net/#code=w4Zsw5DEv8SK4biKaTE&input=&args=MzgxNDI4MA) or [verify all test cases](http://jelly.tryitonline.net/#code=w4Zsw5DEv8SK4biKaTEKxbzDh-KCrEc&input=&args=MCwgMSwgMiwgMywgNCwgMTUsIDE2LCAzODE0Mjc5LCAzODE0Mjgw). ### Background We start by successively taking natural logarithms of the input and the subsequent results until the result no longer changes. This works because the extension of the natural logarithm to the complex plane has a [fixed point](https://en.wikipedia.org/wiki/Fixed_point_(mathematics)); if **z = e-W(-1) ≈ 0.318 + 1.337i** – where **W** denotes the [Lambert W function](https://en.wikipedia.org/wiki/Lambert_W_function) – we have **log(z) = z**. For input **n**, after computing **[n, log(n), log(log(n)), …, z]**, we first apply the ceiling function to each of the results. Jelly's implementation (`Ċ`) actually computes the imaginary part of *complex* number instead†, but we're not interested in these anyway. Once the **k**th application of **log** yields a value less than or equal to **1**, `Ċ` will return **1** for the first time. The 0-based index of that first **1** is the desired result. The straightforward implementation (compute 1-based index, decrement) fails because of edge case **0**, which does not have a **1** in its list of logarithms. In fact, for input **0**, the sequence of logarithms is ``` [0, None] ``` This is because Jelly's logarithm (`Æl`) is overloaded; it first tries `math.log` (real logarithm), then `cmath.log` (complex logarithm), and finally "gives up" and returns `None`. Fortunately, `Ċ` is similarly overloaded and simply returns it argument if it cannot round up or take an imaginary part. Likewise, input **1** returns ``` [1, 0, None] ``` which may create problems in other approaches that do or do not involve `Ċ`. One way to fix this problem is apply `Ḋ` (dequeue; removes first element) to the array of logarithms. This maps ``` 0ÆlÐĿ -> [0, None] -> [None] 1ÆlÐĿ -> [1, 0, None] -> [0, None] ``` so neither list has a **1** now. This way, finding the index of the first **1** will return **0** (not found), which is the desired output for inputs **0** and **1**. ### How it works ``` ÆlÐĿĊḊi1 Main link. Argument: n (non-negative integer) ÐĿ Apply the following link until the results are no longer unique. Æl Natural logarithm. Return the array of all unique results. Ċ Round all resulting real numbers up to the nearest integer. This takes the imaginary part of complex numbers and does nothing for non-numbers. Ḋ Dequeue; remove the first item (n) of the array of results. i1 Find the first index of 1 (0 if not found). ``` --- † This is one of the only three atoms in Jelly that are overloaded in a non-obvious manner. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` Æl>1$пL’ ``` [Try it online!](http://jelly.tryitonline.net/#code=w4ZsPjEkw5DCv0zigJk&input=&args=MzgxNDI4MA) [Test suite.](http://jelly.tryitonline.net/#code=w4ZsPjEkw5DCv0zigJkKw4figqw&input=&args=WzAsMSwyLDMsNCwxNSwxNiwzODE0Mjc5LDM4MTQyODBd) (Slightly modified.) ### Explanation ``` Æl>1$пL’ п while loop, collect all intermediate results. >1$ condition: z>1 Æl body: natural logarithm. L length of the array containing all intermediate results, meaning number of iterations ’ minus one. ``` [Answer] # Javascript, ~~45~~ ~~27~~ 26 bytes ``` l=a=>a>1&&1+l(Math.log(a)) ``` [Here is test suite](https://repl.it/CdiG/3) (3rd rev) Thanks @LeakyNun for saving 1 byte with conditional and then converting function to lambda, and @Neil for pointing out false is ok return value for <=1 (changed test to be == instead of ===) [Answer] # C, 38 bytes ``` f(double n){return n>1?1+f(log(n)):0;} ``` Pretty self-explanatory. [Try it on ideone.](http://ideone.com/pGW2HR) [Answer] # Mathematica, 21 bytes ``` If[#>1,1+#0@Log@#,0]& ``` Recursive anonymous function. Takes an integer as input and returns its super-logarithm as output. Just uses the given definition. [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 13 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) Direct translation of OP: ``` {⍵≤1:0⋄1+∇⍟⍵} ``` [TryAPL](http://tryapl.org/?a=%7B%u2375%u22641%3A0%u22C41+%u2207%u235F%u2375%7D%A80%201%202%203%204%2015%2016%203814279%203814280&run) online! [Answer] # Pyth, 10 bytes ``` L&>b1hy.lb ``` [Test suite.](http://pyth.herokuapp.com/?code=L%26%3Eb1hy.lb%29y&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A15%0A16%0A3814279%0A3814280&debug=0) This defines a function. [Answer] ## Haskell, 23 bytes ``` l x|x>1=1+l(log x)|1<2=0 ``` Usage example: `l 3814280` -> `4`. [Answer] # Python 3, 45 bytes ``` import math s=lambda x:x>1and-~s(math.log(x)) ``` For `x <= 1`, this returns `False` (which is `== 0` in Python). [Answer] ## 05AB1E, ~~16~~ 13 bytes ``` [Dî2‹#¼žr.n]¾ ``` **Explanation** ``` # implicit input n [ ] # infinite loop Dî2‹# # break if n rounded up is less than 2 ¼ # else, increase counter žr.n # set next n = log(n) ¾ # push counter and implicitly print ``` [Try it online](http://05ab1e.tryitonline.net/#code=W0TDrjLigLkjwrzFvnIubl3Cvg&input=MzgxNDI4MA) [Answer] # [J](http://jsoftware.com/), ~~21~~ ~~19~~ ~~18~~ 16 bytes *Saved 2 bytes to Leaky Nun, 1 byte to Galen Ivanov, and 2 bytes to FrownyFrog!* ``` 2#@}.(0>.^.)^:a: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/jZQdavU0DOz04vQ046wSrf5rcilwpSZn5CukKRjAGIZwISMYwxjGMIErMoWzzOCqLAxNjCwM/gMA "J – Try It Online") ## Test cases ``` ls =: >:@$:@^.`0:@.(<:&1) ls 0 0 ls 1 0 ls 2 1 ls 3 2 ls 4 2 ls 15 2 ls 16 3 ls 3814280 4 ``` [Answer] # [MATL](http://github.com/lmendo/MATL), ~~15~~ 12 bytes ``` 0`ZetG>~}x@q ``` [Try it online!](http://matl.tryitonline.net/#code=MGBaZXRHPn59eEBx&input=MzgxNDI3OQ) Or [verify all test cases](http://matl.tryitonline.net/#code=YFhLeAowYFpldEs-fn14QHEKXURU&input=MAoxCjIKMwo0CjE1CjE2CjM4MTQyNzkKMzgxNDI4MA) (slightly modified version to handle several inputs). ### How it works Starting with 0, apply iterated exponentiation until exceeding the input. The output is the number of iterations minus 1. ``` 0 % Push 0 ` % Do...while loop Ze % Exponential t % Duplicate G % Push input >~ % Is current value less than or equal to the input? If so: next iteration } % Finally (code executed at the end of the last iteration) x % Delete @q % Iteration index minus 1 % Implicitly end loop % Implicitly display stack ``` [Answer] # Julia, 17 bytes ``` !x=x>1&&1+!log(x) ``` [Try it online!](http://julia.tryitonline.net/#code=IXg9eD4xJiYxKyFsb2coeCkKCmZvciBuIGluIFswOjQ7IFsxNSwgMTYsIDM4MTQyNzksIDM4MTQyODBdXQogICAgQHByaW50ZigiJTdkIC0-ICVkXG4iLCBuLCAhbikKZW5k&input=) [Answer] # Java 7, 47 bytes ``` int c(double n){return n>1?1+c(Math.log(n)):0;} ``` [Try it online.](https://tio.run/##ZY/NCoJAEMfvPcXgaRdJ1KxMoZ7Ak8fosKnYmq7ijkKIz26rCSodf8P8vzLWsn0Wv4coZ1JCwLjodgASGfIIBi4QIhKXzTNPQNCuTrCpBYirdbP0iAQMX0ZepkRQ6pl@PyhppX6VdHZoSx5DoVxJiDUX6f0BjI4JAJhIJCb1F7DWYK/hsAZnozlu6LRRuZZjny9/J/eX2u@WpVPP6WOczOeK4UdiUhhlg0al2mMuCNc1DzS1ndPZpB@@) The recursive Java 7 style method above is 2 bytes shorter than an iterative Java 8 style lambda: ``` n->{int c=0;for(;n>1;c++)n=Math.log(n);return c;} ``` [Try it online.](https://tio.run/##ZY/NjsIwDITvPIXFKVVF1fK3QFTeAC4cEYdsGthAcVDiIiHUZy9ptodWXCx9I894fBVPMbkWt0aWwjnYCY3vEYBGUvYspIJ9i0EAyQpT/ZYKMOJerEd@OBKkJewBIYcGJ9t32MxTfjaWcdxmXMZxhPlO0F9SmgvzZquosgiS1w1vQx4@1Yd0WU@jC7j7IuxAVuPleAIR/bcg5Yil4XoHWR@mfZj1YT7wLAa0HLhW2Xz6s/6SVunXz6Fn2Ghf1l3Fw8uRuiemouTh21OJTMfjDYxjTCTTURdTNx8) **Explanation:** ``` int c(double n){ // Method with double parameter and integer return-type return n>1? // If the input is larger than 1: 1+ // Return 1 + c(Math.log(n)) // A recursive call with log(input) : // Else: 0; // Return 0 instead n->{ // Method with double parameter and integer return-type int c=0; // Create a counter, starting at 0 for(;n>1; // Loop as long as the input is still larger than 1: c++) // Increase the counter by 1 n=Math.log(n); // And update the input to log(input) return c;} // After the loop: return the counter as result ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` -Ælß$Ị?‘ ``` Straightforward implementation of the definition. [Try it online!](http://jelly.tryitonline.net/#code=LcOGbMOfJOG7ij_igJg&input=&args=MzgxNDI4MA) or [verify all test cases](http://jelly.tryitonline.net/#code=LcOGbMOfJOG7ij_igJgKxbzDh-KCrEc&input=&args=MCwgMSwgMiwgMywgNCwgMTUsIDE2LCAzODE0Mjc5LCAzODE0Mjgw). ### How it works ``` -Ælß$Ị?‘ Main link. Argument: x Ị Insignificant; test if |x| ≤ 1. ? If the result is 1: - Return -1. Else: $ Execute the monadic chain formed by the two links to the left. Æl Apply natural logarithm to x. ß Recursively call the main link. ‘ Increment the result. ``` [Answer] # MATLAB / Octave, 44 bytes `function a=g(n);a=0;if n>1;a=1+g(log(n));end` Tried to do it all as one anonymous function, but I forgot that MATLAB/Octave continues to evaluate expressions even if they are multiplied by a boolean false (zero) value: `f=@(n)(n>1)*(1+f(log(n)))` [Answer] **Mathematica, 29 bytes** Simple as all hell, and works for comically large as well as negative inputs: ``` f[x_]:=If[x>1,1+f[Log[x]],0] ``` [![enter image description here](https://i.stack.imgur.com/RQW7W.png)](https://i.stack.imgur.com/RQW7W.png) [Answer] # R, ~~38~~ 37 bytes ``` f=function(x)if(x>1)1+f(log(x))else 0 ``` Thanks [@user5957401](https://codegolf.stackexchange.com/users/58162) for the extra byte! Test cases: ``` > f(0) [1] 0 > f(1) [1] 0 > f(2) [1] 1 > f(3) [1] 2 > f(4) [1] 2 > f(3814279) [1] 3 > f(3814280) [1] 4 ``` [Answer] # [R](https://www.r-project.org/), 34 bytes ``` f=pryr::f(`if`(n>1,1+f(log(n)),0)) ``` [Try it online!](https://tio.run/##K/r/P822oKiyyMoqTSMhMy1BI8/OUMdQO00jJz9dI09TU8dAU/N/moaBJleahiGIMAIRxmCuKZg0AwtYGJoYmVvCmRYGmv8B "R – Try It Online") A non-recursive approach is possible: **36** bytes and takes input from stdin. ``` n=scan() while((n=log(n))>0)F=F+1 +F ``` [Answer] ## Emacs Lisp, 38 bytes ``` (defun l(n)(if(> n 1)(1+(l(log n)))0)) ``` Testcases: ``` (mapcar 'l '(0 1 2 3 4 15 16 3814279 3814280)) ;; (0 0 1 2 2 2 3 3 4) ``` [Answer] ## Perl 5, 35 bytes Very simple, requires `-M5.016` (which is free) to enable the `__SUB__` keyword for anonymous recursion. ``` sub{$_[0]>1?1+__SUB__->(log pop):0} ``` Another alternative is ``` sub{$_[0]>1?1+__SUB__->(log pop):0} ``` which is 34 bytes, and gives the same output for all inputs > 1, but returns the special false value for inputs <= 1. False is numerically equal to zero, but prints as "" (empty string), so it probably doesn't qualify. [Answer] ## CJam (16 bytes) ``` rd{_1>}{_ml}w],( ``` [Online demo](http://cjam.aditsu.net/#code=rd%7B_1%3E%7D%7B_ml%7Dw%5D%2C(&input=3814280) Simple while loop with pre-condition. (What I really want here is a Golfscript-style unfold operation, but CJam doesn't have one, and floating point in GolfScript is messy and not at all golfy). [Answer] # [PARI/GP](http://pari.math.u-bordeaux.fr/), 24 bytes Just the straightforward recursion. ``` f(n)=if(n>1,1+f(log(n))) ``` [Answer] # Racket, 61 bytes ``` (λ(x)(letrec([a(λ(b)(if(> b 1)(+ 1 (a(log b)))0))])(a x))) ``` [Answer] # Maple, ~~32,30~~ 29 bytes ``` f:=x->`if`(x>1,1+f(log(x)),0) ``` Test cases: ``` > f(0.); 0 > f(1.); 0 > f(2.); 1 > f(3.); 2 > f(4.); 2 > f(3814279.); 3 > f(3814280.); 4 ``` [Answer] # R, 36 bytes Slightly different approach from Plannapus ``` ->n;a=0;while(n>1){a=a+1;n=log(n)};a ``` Uses a right assign to run the code -- so the desired number must precede it. i.e. ``` 10->n;a=0;while(n>1){a=a+1;n=log(n)};a ``` [Answer] # [Whispers v3](https://github.com/cairdcoinheringaahing/Whispers), 9 bytes ``` >> ln*(L) ``` [Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fzk4hJ09Lw0fzv52CZ15BaQkXUMTwUccMIxDDv7QEKKRg/N/YwtDEyMIAAA "Whispers v2 – Try It Online") Note that I had to [push a bug fix](https://github.com/cairdcoinheringaahing/Whispers/commit/9fb12f3ba8a5e1a7611fae2dfae5c9938345255e) in order to make this work. The `ln*` function had already been added [before September 1st 2020](https://github.com/cairdcoinheringaahing/Whispers/blob/81c0e41e8fe10fabfde713072cc6cd5e0e49290e/whispers%20v3.py#L2546), but I hadn't noticed a bug in the parsing that was fixed today This is a function, going by the standards defined [here](https://codegolf.meta.stackexchange.com/a/20740/66833) for Whispers functions. It can be called by appending the code in the Footer to the file. Whispers v3 also has the `slog`, `lg*` (uses \$\log\_2\$) and `log*` (uses \$\log\_{10}\$) functions [Answer] ### Ruby, 29 bytes ``` l=->n{n<=1?0:1+l[Math.log n]} ``` [Answer] # [Perl 6](http://perl6.org/), 21 bytes ``` {($_,*.log...1>=*)-1} ``` [Try it online!](https://tio.run/##JcVLDkAwFAXQrdxIIwgvnm@FdiuNgZoQwqgpa6@BMznncm1d2B1iCxV8Ikye0XasRMRaZWnBb7hnh0gYKA1vIcwbwR4XnqQkatIcz8QtuEMtuan64V@Wegwf "Perl 6 – Try It Online") The parenthesized expression is a sequence. `$_`, the argument to the function, is the first element. `*.log` generates each successive element by taking the log of the previous element. The sequence continues until the ending condition, `1 >= *`, is true: 1 is greater than or equal to the current element. Subtracting 1 from the sequence coerces it to a number: its length. ]
[Question] [ You are a space tourist on your way to planet Flooptonia! The flight is going to take another 47,315 years, so to pass the time before you're cryogenically frozen you decide to write a program to help you understand the Flooptonian calendar. Here is the 208-day long Flooptonian calendar: ``` Month Days Input Range Qupu 22 [0-22) Blinkorp 17 [22-39) Paas 24 [39-63) Karpasus 17 [63-80) Floopdoor 1 [80] Dumaflop 28 [81-109) Lindilo 32 [109-141) Fwup 67 [141-208) ``` ## Challenge Your program, given an integer day in the year (range `[0-208)`) is to output the corresponding day of the month and name of the month (e.g. `13 Dumaflop`). There is an exception, however: Floopdoor a special time for Flooptonians that apparently deserves its own calendar page. For that reason, Floopdoor isn't written with a day (i.e. the output is `Floopdoor`, not `1 Floopdoor`). ## Test Cases ``` 0 => 1 Qupu 32 => 11 Blinkorp 62 => 24 Paas 77 => 15 Karpasus 80 => Floopdoor 99 => 19 Dumaflop 128 => 20 Lindilo 207 => 67 Fwup ``` ## Rules * You must write a complete program. * You can assume that the input is always valid. * Your output may have a trailing newline but must otherwise be free of any extra characters. The case should also match the provided examples. * You may use date/time functions. * Code length is to be measured in bytes. [Answer] # Python 3, ~~159~~ ~~156~~ ~~152~~ ~~151~~ ~~150~~ 148 bytes ``` n=int(input())+1 for c,x in zip(b" C","Qupu Blinkorp Paas Karpasus Floopdoor Dumaflop Lindilo Fwup".split()):c>=n>0and print(*[n,x][-c:]);n-=c ``` The bytes object in the `zip` contains unprintable characters: ``` for c,x in zip(b"\x16\x11\x18\x11\x01\x1c C", ...): ... ``` *(Thanks to @xnor for suggesting a `for/zip` loop for -3 bytes)* [Answer] # Pyth - 105 103 90 88 bytes Uses base conversion. Two simple lookup tables, with one for the names and one for start dates, and a ternary at the end for Floopdoor. ``` KhfgQhTC,aCM"mQP?'"Zcs@LGjC"îºBüÏl}W\"p%åtml-¢pTÇÉ(°±`"23\c+?nQ80+-hQhKdkreK3 ``` Compresses the string not as base 128, but as base 23. First, it translates it to indices of the alphabet. This required the separator to be `c` which doesn't appear in any of the month names. Then it encodes that to base ten from a base 23 number (the highest value that appeared was `w`), then converts to base 256. The start dates are their unicode codepoints, no base conversion. ``` K K = hf First that matches the filter gQ >= Q hT First element of filter var C, Zip two sequences a Z Append 0 (I could save a byte here but don't want to mess with null bytes) CM"..." Map the string to its codepoints c \c Split by "c" s Sum by string concatenation @LG Map to location in alphabet j 23 Base 10 -> Base 23 C"..." Base 256 -> Base 10 + String concatenation ?nQ80 Ternary if input != 80 +-hQhK Input - start date + 1 k Else empty string r 3 Capitalize first letter eK Of month name ``` [Try it online here](http://pyth.herokuapp.com/?code=KhfgQhTC%2CaCM%22%C2%8DmQP%3F%27%16%22Zcs%40LGjC%22%01%C3%AE%C2%BAB%C3%BC%C3%8Fl%7DW%5C%22p%25%C3%A5tml-%C2%9A%1F%C2%A2pT%C3%87%C2%94%C3%89%C2%97(%C2%96%C2%B0%18%C2%8F%C2%B1%15%60%2223%5Cc%2B%3FnQ80%2B-hQhKdkreK3&input=128&debug=1). [Test Suite](http://pyth.herokuapp.com/?code=V.QKhfgNhTC%2CaCM%22%C2%8DmQP%3F%27%16%22Zcs%40LGjC%22%01%C3%AE%C2%BAB%C3%BC%C3%8Fl%7DW%5C%22p%25%C3%A5tml-%C2%9A%1F%C2%A2pT%C3%87%C2%94%C3%89%C2%97(%C2%96%C2%B0%18%C2%8F%C2%B1%15%60%2223%5Cc%2B%3FnN80%2B-hNhKdkreK3&input=0%0A32%0A62%0A77%0A80%0A99%0A128%0A207&debug=0). [Answer] # Piet 2125 bytes It's by no means the shortest, but it's pretty and colorful... Each pixel is placed by myself by hand. To run it go [here](http://www.rapapaing.com/piet/index.php) in FireFox (Chrome won't work) and load it with a codel width of 1 (it'll appear black, don't worry), enter the number and hit the run button! Small Program: [![Small Version](https://i.stack.imgur.com/UYzGl.png)](https://i.stack.imgur.com/UYzGl.png) Enlarged (Codel width of 10): [![enter image description here](https://i.stack.imgur.com/rvR7t.png)](https://i.stack.imgur.com/rvR7t.png) [Answer] # Pyth 178 156 153 147 bytes ``` J?<Q22,_1"Qupu"?<Q39,21"Blinkorp"?<Q63,38"Paas"?<Q80,62"Karpasus"?<Q81,k"Floopdoor"?<Q109,80"Dumaflop"?<Q141,108"Lindilo",140"Fwup"?nhJkjd,-QhJeJeJ ``` [Permalink](https://pyth.herokuapp.com/?code=J%3F%3CQ22%2C_1%22Qupu%22%3F%3CQ39%2C21%22Blinkorp%22%3F%3CQ63%2C38%22Paas%22%3F%3CQ80%2C62%22Karpasus%22%3F%3CQ81%2Ck%22Floopdoor%22%3F%3CQ109%2C80%22Dumaflop%22%3F%3CQ141%2C108%22Lindilo%22%2C140%22Fwup%22%3FnhJkjd%2C-QhJeJeJ&input=0&debug=0) Second golf ever, any Pyth feedback will be very helpful. ## Explanation ``` J (Auto)Assign J a tuple of the first day & month name ?<Q22,_1"Qupu" Recall that Q auto-initialized to raw_input() ?<Q39,21"Blinkorp" ? is ternary ?<Q63,38"Paas" , is a two-pair tuple ?<Q80,62"Karpasus" ?<Q81,k"Floopdoor" Special case handled by empty string as first day ?<Q109,80"Dumaflop" ?<Q141,108"Lindilo" ,140"Fwup" Since input assumed valid, no need to test for Fwup ?nhJk Is day not an empty string? jd, join on space -QhJ Q-(first day or -1 on first month) + 1 eJ The month itself eJ Else print only the month name on Floopdoor ``` [Answer] # CJam, ~~98~~ ~~96~~ 93 bytes ``` 0000000: 72 69 63 22 00 16 27 3f 50 51 6d 8d d0 22 66 2d ric"..'?PQm.."f- 0000010: 5f 7b 30 3c 7d 23 28 5f 40 3d 29 53 40 22 06 32 _{0<}#(_@=)S@".2 0000020: 88 b2 ce d2 87 2f 1e 79 62 1b 7a 11 53 a6 cc 02 ...../.yb.z.S... 0000030: 40 c5 c6 82 d0 dd b7 4b ed ee 1c dc 4f f5 ec 67 @......K....O..g 0000040: 22 32 35 35 62 32 33 62 27 61 66 2b 27 63 2f 3d "255b23b'af+'c/= 0000050: 5f 2c 39 3d 7b 5c 3f 7d 26 28 65 75 5c _,9={\?}&(eu\ ``` The above is a reversible hexdump, since the source code contains unprintable characters. Most unprintable characters are no problem for the online interpreter, but the null byte in the first string is a deal breaker. At the cost of one byte, we can fix this by adding 1 to the input and 1 to each code point of the first string. You can try this version in the [CJam interpreter](http://cjam.aditsu.net/#code=ric)%22%01%17(%40QRn%C2%8E%C3%91%22f-_%7B0%3C%7D%23(_%40%3D)S%40%22%062%C2%88%C2%B2%C3%8E%C3%92%C2%87%2F%1Eyb%1Bz%11S%C2%A6%C3%8C%02%40%C3%85%C3%86%C2%82%C3%90%C3%9D%C2%B7K%C3%AD%C3%AE%1C%C3%9CO%C3%B5%C3%ACg%22255b23b'af%2B'c%2F%3D_%2C9%3D%7B%5C%3F%7D%26(eu%5C&input=80). If the permalink doesn't work in your browser, you can copy the code from [this paste](http://pastebin.com/iWCtf4ae). ### Test cases ``` $ LANG=en_US $ xxd -ps -r > flooptonia.cjam <<< 726963220016273f50516d8dd022662d5f7b303c7d23285f403d29534022063288b2ced2872f1e79621b7a1153a6cc0240c5c682d0ddb74bedee1cdc4ff5ec6722323535623233622761662b27632f3d5f2c393d7b5c3f7d262865755c $ wc -c flooptonia.cjam 96 flooptonia.cjam $ for d in 0 32 62 77 80 99 128 207; do cjam flooptonia.cjam <<< $d; echo; done 1 Qupu 11 Blinkorp 24 Paas 15 Karpasus Floopdoor 19 Dumaflop 20 Lindilo 67 Fwup ``` ### How it works ``` ric e# Read a Long from STDIN and cast to Character. "…" e# Push the string that corresponds to [0 22 39 63 80 81 109 141 208]. f- e# Subtract each character from the input char. e# Character Character - -> Long _{0<}# e# Find the index of the first negative integer. (_ e# Subtract 1 from the index and push a copy. @=) e# Select the last non-negative integer from the array and add 1. S@ e# Push a space and rotate the decremented index on top of it. "…" e# Push a string that encodes the months' names. 255b23b e# Convert from base 255 to 23. 'af+ e# Add the resulting digits to the character 'a'. 'c/ e# Split at occurrences of 'c' (used as separator). = e# Select the chunk that corresponds to the index. _,9= e# Check if its length is 9 (Floopdoor). {\?}& e# If so, swap and execute ternary if. e# Since the string " " is truthy, S Month Day ? -> Month. (eu\ e# Shift out the first char, convert it to uppercase and swap. ``` [Answer] # SWI-Prolog, ~~237~~ ~~232~~ 213 bytes ``` a(X):-L=[22:"Qupu",39:"Blinkorp",63:"Paas",80:"Karpasus",81:"Floopdoor",109:"Dumaflop",141:"Lindilo",208:"Fwup"],nth1(I,L,A:B),X<A,J is I-1,(nth1(J,L,Z:_),Y=X-Z;Y=X),R is Y+1,(X=80,write(B);writef("%w %w",[R,B])). ``` Here we use Prolog's backtracking mechanism to repeatedly apply `nth1/3` to the list `L`, to get the first element `LastDay+1:MonthName` of `L` for which `X < LastDay+1` holds. We then look for the month immediately before this one in the list to evaluate the day of the month. [Answer] # Q, ~~134~~ 146 Bytes ### second cut -- program (146 bytes) ``` v:bin[l:0 22 39 63 80 81 109 141 208;x:(*)"I"$.z.x];1(,/)($)$[v=4;`;(1+x-l v)," "],`Qupu`Blinkorp`Paas`Karpasus`Floopdoor`Dumaflop`Lindilo`Fwup v; ``` ### first cut -- function (134 bytes) ``` {v:bin[l:0 22 39 63 80 81 109 141 208;x];(,/)($)$[v=4;`;(1+x-l v)," "],`Qupu`Blinkorp`Paas`Karpasus`Floopdoor`Dumaflop`Lindilo`Fwup v} ``` ### testing ``` q){v:bin[l:0 22 39 63 80 81 109 141 208;x];(,/)($)$[v=4;`;(1+x-l v)," "],`Qupu`Blinkorp`Paas`Karpasus`Floopdoor`Dumaflop`Lindilo`Fwup v} each 0 32 62 77 80 99 128 207 "1 Qupu" "11 Blinkorp" "24 Paas" "15 Karpasus" "Floopdoor" "19 Dumaflop" "20 Lindilo" "67 Fwup" ``` [Answer] # Julia, ~~231~~ ~~216~~ ~~184~~ 175 bytes ``` r=readline()|>int l=[141,109,81,80,63,39,22,0] m=split("Qupu Blinkorp Paas Karpasus Floopdoor Dumaflop Lindilo Fwup") i=findfirst(j->r>=j,l) print(i==4?"":r-l[i]+1," ",m[9-i]) ``` This reads a line from STDIN and converts it to an integer, finds the first element of a reversed list of month start days where the input is greater than or equal to the start, then prints accordingly. [Answer] # Swift 1.2, 256 bytes ``` var d=Process.arguments[1].toInt()!,f="Floopdoor",n=[("Qupu",22),("Blinkorp",17),("Paas",24),("Karpasus",17),(f,1),("Dumaflop",28),("Lindilo",32),("Fwup",67)] for i in 0..<n.count{let m=n[i] if d>=m.1{d-=m.1}else{println((m.0==f ?"":"\(d+1) ")+m.0) break}} ``` To run put the code alone in a `.swift` file and run it using `swift <filename> <inputNumber>` [Answer] # Java, ~~357~~ 339 bytes It's not the most efficient, but I do like how it works. It creates the entire Flooptonia calendar and then looks up what date the number is. ``` class X{public static void main(String[]q){String n[]={"Qupu","Blinkorp","Paas","Karpasus","Floopdoor","Dumaflop","Lindilo","Fwup"},l[]=new String[209];int m=0,d=0,i,b[]={0,22,39,63,80,81,109,141,208};for(i=0;i++<208;d++){l[i]=(m==4?"":d+" ")+n[m];if(i>b[m+1]){m++;d=0;}}System.out.print(l[new java.util.Scanner(System.in).nextInt()+2]);}} ``` Input/Output: `77 --> 15 Karpasus 80 --> Floopdoor` Spaced and tabbed out: ``` class X { public static void main(String[] q) { String n[] = { "Qupu", "Blinkorp", "Paas", "Karpasus", "Floopdoor", "Dumaflop", "Lindilo", "Fwup" }, l[]=new String[209]; int m = 0, d = 0, i, b[] = { 0, 22, 39, 63, 80, 81, 109, 141, 208 }; for(i = 0; i++ < 208; d++) { l[i]=(m == 4 ? "" : d + " ") + n[m]; if(i > b[m+1]){ m++; d = 0; } } System.out.print(l[ new java.util.Scanner(System.in).nextInt() + 2 ]); } } ``` [Answer] # Java, ~~275~~ ~~269~~ ~~266~~ ~~257~~ ~~256~~ ~~252~~ ~~246~~ ~~244~~ 243 bytes ``` class X{public static void main(String[]w){int x=new Short(w[0]),i=1,a[]={-1,21,38,62,79,80,108,140,207};w="Qupu,Blinkorp,Paas,Karpasus,Floopdoor,Dumaflop,Lindilo,Fwup".split(",");while(x>a[i++]);System.out.print((i==6?"":x-a[i-=2]+" ")+w[i]);}} ``` Formatted: ``` class X { public static void main(String[] w) { int x = new Short(w[0]), i = 1, a[] = { -1, 21, 38, 62, 79, 80, 108, 140, 207 }; w = "Qupu,Blinkorp,Paas,Karpasus,,Dumaflop,Lindilo,Fwup".split(","); while (x > a[i++]); System.out.print(i == 6 ? "Floopdoor" : x - a[i-=2] + " " + w[i]); } } ``` Interestingly, it's a few bytes shorter than this ``` class X { public static void main(String[] w) { int x = new Short(w[0]); System.out.print(x < 22 ? x + 1 + " Qupu" : x < 39 ? x - 21 + " Blinkorp" : x < 63 ? x - 38 + " Paas" : x < 80 ? x - 62 + " Karpasus" : x < 81 ? "Floopdoor" : x < 109 ? x - 80 + " Dumaflop" : x < 141 ? x - 108 + " Lindilo" : x < 208 ? x - 140 + " Fwup" : ""); } } ``` [Answer] **JavaScript using ES6 ~~171~~ ~~164~~ 163 bytes** I'm not the best JavaScript programmer but I tried my best and ended up with the following code ``` f=(n)=>[0,22,39,63,80,81,109,141,208].some((e,j,a)=>n<a[j+1]&&(r=(j-4?n-e+1+' ':'')+"Qupu0Blinkorp0Paas0Karpasus0Floopdoor0Dumaflop0Lindilo0Fwup".split(0)[j]))&&r; ``` To see the result you need to refer above code in a html file and use similar to the code below ``` <html><body><p id="o"></p><script src="Fp.js"></script><script>t=[0,32,62,77,80,99,128,207];for(i=0;i<t.length;i++)document.getElementById('o').innerHTML+=f(t[i])+'<br/>';</script></body></html> ``` In the above code fp.js is the file that contains the javascript code. Combined HTML and JavaScript code with indent is ``` f=(n)=>[0,22,39,63,80,81,109,141,208].some( (e,j,a)=>n<a[j+1]&&(r=(j-4?n-e+1+' ':'')+"Qupu0Blinkorp0Paas0Karpasus0Floopdoor0Dumaflop0Lindilo0Fwup".split(0)[j])) &&r; t = [0, 32, 62, 77, 80, 99, 128, 207]; for (i = 0; i < t.length; i++) document.getElementById('o').innerHTML += f(t[i]) + '<br/>'; ``` ``` <html> <body> <p id="o"></p> </body> </html> ``` **Edit:** I'd like to thank Vihan for helping me remove the return statement and reduce my code by 17bytes @ipi, thanks for helping me save 7 bytes > > Note: You can see the result only in browsers Firefox version 22+ and > Google Chrome 45+ because of using ES6 arrow functions > > > [Answer] # Python 2, 168 bytes ``` n=input();e=[-1,21,38,62,80,108,140,207];m=1 while n>e[m]:m+=1 print[`n-e[m-1]`+' '+'Qupu Blinkorp Paas Karpasus Dumaflop Lindilo Fwup'.split()[m-1],'Floopdoor'][n==80] ``` This treats day `80` internally as `18 Karpasus`, but then ignores it when called to print. Also, Python 2's `input()` function (as opposed to `raw_input()`) was convenient here. [Answer] # Perl 5, 140 Requires running via `perl -E`: ``` $i=<>+1;$i-=$b=(22,17,24,17,1,28,32,67)[$c++]while$i>0;say$b>1&&$i+$b.$",(x,Qupu,Blinkorp,Paas,Karpasus,Floopdoor,Dumaflop,Lindilo,Fwup)[$c] ``` Test output (stolen test code from @Dennis): ``` $for d in 0 32 62 77 80 99 128 207; do perl -E '$i=<>+1;$i-=$b=(22,17,24,17,1,28,32,67)[$c++]while$i>0;say$b>1&&$i+$b.$",(x,Qupu,Blinkorp,Paas,Karpasus,Floopdoor,Dumaflop,Lindilo,Fwup)[$c]' <<< $d; echo; done 1 Qupu 11 Blinkorp 24 Paas 15 Karpasus Floopdoor 19 Dumaflop 20 Lindilo 67 Fwup ``` [Answer] # Haskell, ~~171~~ 167 bytes ``` main=interact$f.read f 80="Floopdoor" f n=(g=<<zip[22,17,24,18,28,32,67](words"Qupu Blinkorp Paas Karpasus Dumaflop Lindilo Fwup"))!!n g(n,s)=map((++' ':s).show)[1..n] ``` The program reads it's input from stdin which must not end in NL. Terminate input with EOF/^D or use something like `echo -n 80 | ./what-day-is-it`. (Some `echo`s don't understand the `-n` switch and omit the NL by default). How it works: The `main` function reads the input, converts it to an `Integer` and calls `f` which returns a literal `Floopdoor` in case of an input of `80` or builds up a list of all possible dates, i.e. `["1 Qupu", "2 Qupu", ... "1 Blinkorp", ... "67 Fwup"]` from which it picks the `n`th element. I make `Karpasus` is one day longer. `18 Karpasus` is at position `80` and fixes the missing `Floopdoor` in the list. Edit: @MtnViewMark had the idea of the `18 Karpasus` trick and saved 4 bytes. [Answer] ## Swift 2.0, 220 bytes Nothing clever, just filters from a collection of tuples... ``` func d(n:Int)->String{return n==80 ?"Floopdoor":[("Qupu",21,0),("Blinkorp",38,22),("Paas",62,39),("Karpasus",79,63),("Dumaflop",108,81),("Lindilo",140,109),("Fwup",208,141)].filter{$0.1>=n}.map{"\($0.0) \(n-$0.2+1)"}[0]} ``` Edited to correct bug, removed a space [Answer] ## JavaScript (ES6 on Node.js), 196 bytes Takes one command line argument: ``` a=+process.argv[2];for(d of['22Qupu','17Blinkorp','24Paas','17Karpasus','01Floopdoor','28Dumaflop','32Lindilo','67Fwup']){if(a<(z=parseInt(d)))return console.log((z>1?a+1+' ':'')+d.slice(2));a-=z} ``` ### Demo As there is no command-line argument ([`process.argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv)) in the browser, the code in the snippet has been placed in a function that accepts an argument: ``` // Snippet stuff console.log = function(x){O.innerHTML += x + '\n'}; // Flooptonia function function flooptonia(a) { a = +a; for (d in y=['22Qupu', '17Blinkorp', '24Paas', '17Karpasus', '01Floopdoor', '28Dumaflop', '32Lindilo', '67Fwup']) { if (a < (z = parseInt(y[d]))) return console.log((z > 1 ? a + 1 + ' ' : '') + y[d].slice(2)); a -= z } } // Test ['0', '32', '62', '77', '80', '99', '128', '207'].map(flooptonia); ``` ``` Test values: [0, 32, 62, 77, 80, 99, 128, 207] <pre id=O></pre> ``` [Answer] # Swift 2.0, 215 204 ``` let(n,t)=(Int(readLine()!)!,[(141,"Fwup"),(109,"Lindilo"),(81,"Dumaflop"),(63,"Karpasus"),(39,"Paas"),(22,"Blinkorp"),(0,"Qupu")]) print({(n==80 ?"Floopdoor":"\(n-$0.0+1) "+$0.1)}(t[t.indexOf{$0.0<=n}!])) ``` This is a full program which asks the user to input the number in STDIN. [Answer] ## Matlab, 187 bytes ``` d=input('');l=[141 109 81 80 63 39 22 0];t=find(d>=l,1);m=strsplit('Fwup Lindilo Dumaflop Floopdoor Karpasus Paas Blinkorp Qupu');f='%d %s';if t==4;f='%d\b%s';end;fprintf(f,d-l(t)+1,m{t}) ``` Expanded version: ``` d=input(''); l=[141 109 81 80 63 39 22 0]; t=find(d>=l,1); m=strsplit('Fwup Lindilo Dumaflop Floopdoor Karpasus Paas Blinkorp Qupu'); f='%d %s'; if t==4; f='%d\b%s'; end fprintf(f,d-l(t)+1,m{t}) ``` Reads a line from the console (`stdin`), finds the first element of a reversed list of month start days where the input is greater than or equal to the array element, then prints accordingly. This is almost identical to the `Julia` answer, except for the display stage. (*We can't beat their ternary operator, unavailable in Matlab*). To make up having to explicit a full `if` statement, we use a little trick (a `Backspace` character in the print format) to "erase" the number 1 for the special day/month `Floopdoor` --- *In collaboration with the [Matlab and Octave](http://chat.stackoverflow.com/rooms/81987/matlab-and-octave) chat participants.* [Answer] # Javascript ES5 using 168 bytes ``` m=[-1,21,38,62,79,80,108,140];for(n=prompt(i=0);n>m[i+1]&&i++<8;);alert((i-4?n-m[i]+" ":"")+"Qupu0Blinkorp0Paas0Karpasus0Floopdoor0Dumaflop0Lindilo0Fwup".split(0)[i]) ``` Ungolfed: ``` m=[-1,21,38,62,79,80,108,140]; // create range of starting indexes - 1 for( // begin for loop n=prompt(i=0); // initialize i to zero and prompt user n>m[i+1] && i++ < 8; // exit if n>0; increment i; exit if i was < 8 ); // end for loop alert( (i-4 ? n-m[i]+" ":"") + // special floopdoor case "Qupu0Blinkorp0Paas0Karpasus0Floopdoor0Dumaflop0Lindilo0Fwup".split(0)[i]); //^ create an array of strings by splitting at zero. Then, select element i ``` [Answer] # C, 241 bytes Nothing too exciting. Could have shaved 27 bytes had it require to be a complete program. ``` main(c,s)char**s;{c=atoi(s[1]);c-80?printf("%d ",c<22?c+1:c<39?c-21:c<63?c-38:c<80?c-62:c<109?c-80:c<141?c-108:c-140):0;puts(c<22?"Qupu":c<39?"Blinkorp":c<63?"Paas":c<80?"Karpasus":c<81?"Floopdoor":c<109?"Dumaflop":c<141?"Lindilo":"Fwup");} ``` ]
[Question] [ # Introduction The game takes place in a small world with different towns. The rulers of the towns hate each other and would like to rule the world. The people are divided into two groups, warriors and lowborns. However, lowborns can raise to warriors. You are the ruler of three of these towns. # Gameplay When the game begins, you rule over three towns. In each town, there are 100 people. You have to divide them into knights and lowborns. Then the actual game begins, which is turn-based. A turn looks like this: `"Produce" knights` => `execute command of first town` => `execute command of next town` (repeat for all towns) => `try a rebellion`. * Each turn, your program will be invoked **for each town that belongs to you**. You can either **attack a town**, **support a town** or simply **wait**. These actions will be executed sequentially, not simultaneously. * Every third turn, you get one knight per 2 lowborns (23 lowborns => 11 knights). The amount of lowborns stays the same. * Knights inside a town have a defense bonus of 1.2. If you get attacked, your knights will be multiplied by this number (e.g. you have `78 knights`, you will have `93 knights` during the attack). After the attack, the extra knights will be removed (if `82 knights` survive, you will still have `78 knights`). * In an attack, each knight kills an enemy before he dies. For example: `30 knights` attack `100 knights` (without defense bonus) => 70 knights survive. * You can **capture a town by killing all knights inside it**. All lowborns belong to you now and your surviving knights are stationed in the town. On the next round, **you can rule this town in addition to all your other towns**. * After a town is captured, it won't have a defense bonus for 2 full turns (because the gates are broken). On the third turn, the gates will be repaired. * To prevent the lowborns from rebelling, you need atleast half as much knights as there are lowborns (23 lowborns in a town need atleast 12 knights in the same town). Otherwise, the lowborns will kill all the knights and the town becomes "neutral" (without a leader, indicated by a PlayerId `-1`). * Neutral towns will "produce" knights, but will not attack nor support any other town. # Syntax The controller provides you with input via command arguments, your program has to output via stdout. **Output (preparation)** Before the game starts, the controller invokes you submission without arguments. This means you have to distribute your 100 people (for each town) into knights and lowborns. You need to output `KnightCount KnightCount KnightCount`, for example `95 80 95`. **Input** `Round;YourPlayerId;YourTownId;PlayerId_TownId_knights_lowborns;PlayerId_TownId_knights_lowborns;...` On the first round, this will be something like `1;2;2;0_0_100_0;1_1_50_50;2_2_80_20`. Here, you see it is the first round, you are player 2 in town 2. You have 80 knights and 20 lowborns. Later in the game, it could be something like `20;2;1;0_0_100_0;2_1_30_50;2_2_40_20`. You are still player 2 (this never changes), but you captured town 1 (which you are controlling right now). **Output** `A TownId NumberOfKnights` or `S TownId NumberOfKnights` or `W` (for wait). Example: `A 2 100` (attack town 2 with 100 knights) or `S 3 2` (support town 3 with 2 knights). # Rules * Bots should not be written to beat or support specific other bots. * **Writing to files is allowed.** Please write to "*yoursubmissionname*.txt", the folder will be emptied before a game starts. Other external resources are disallowed. * Your submission has 1 second to respond (per town). * Provide commands to compile and run your submissions. # Winning Winner is the one with the most towns after 100 rounds. If a player captures all towns, the game stops and he wins. If multiple players have the same amount of towns, the amount of knights will count, then the amount of lowborns. # Controller [You can find the controller on github.](https://github.com/CommonGuy/GameOfTowns) It also contains 2 samplebots, written in Java. Open it in Eclipse, place the compiled bots in the root folder and add a class to the control program (just like the samplebots). # Results For the final results, I ran 10 games. This is the average: ``` Player Towns 1. Liberator 37.5 2. Sehtimianer 8.2 3. SuperProducer 5.4 4. Sleeper 1.4 5. Frankenstein 1.2 6. Butter 0.8 (more knights) 7. TheKing 0.8 (less knights) 8. Exodus 0.6 9. Turtle 0.5 (more knights) 10. AttackOn3 0.5 (less knights) 11. Democracy 0.3 12. CalculatedFail 0.2 13. Revolutionist 0.1 ``` You can read a sample game here: [sample game on github](https://github.com/CommonGuy/GameOfTowns/blob/master/_sample_game.txt) [Answer] # Python3, Liberator ``` from sys import argv from math import ceil, floor class OppressedTown: def __init__(self, owner_id, id, oppressors, oppressed): self.owner_id = owner_id self.id = id self.oppressors = oppressors self.oppressed = oppressed def get_free_oppressors(self): return self.oppressors - ceil(self.oppressed / 2) def get_needed_liberators(self): return ceil(self.oppressed / 2) class LiberatedTown: def __init__(self, owner_id, id, liberators, liberated): self.owner_id = owner_id self.id = id self.liberators = liberators self.liberated = liberated def get_free_liberators(self): return self.liberators - ceil(self.liberated / 2) def get_needed_liberators(self): return ceil(self.liberated / 2) def is_safe(self): return self.liberators >= self.liberated * 2 def get_unneeded_liberators(self): return self.liberators - self.liberated * 2 def safe_div(a, b): try: c = a / b except ZeroDivisionError: if a == 0: c = 0 else: c = float("inf") return c def main(): if len(argv) == 1: print ("100 100 100") else: decision = decide() print (decision) def decide(): def needs_urgent_support(town): return town.get_needed_liberators() >= town.liberators and town.liberated > 0 def can_beat(free_liberators, town): return free_liberators > town.oppressors * 1.2 + town.get_needed_liberators() def can_damage(free_liberators, town): return free_liberators > town.oppressors * 0.2 args = argv[1].split(";") round = int(args[0]) me = int(args[1]) current_id = int(args[2]) liberated_towns = [] oppressed_towns = [] for i in range(3, len(args)): infos = list(map(int, args[i].split("_"))) if infos[0] != me: oppressed_towns.append(OppressedTown(infos[0], infos[1], infos[2], infos[3])) else: liberated_towns.append(LiberatedTown(infos[0], infos[1], infos[2], infos[3])) current_town = [town for town in liberated_towns if town.id == current_id][0] free_liberators = current_town.get_free_liberators() total_oppressors = sum(town.liberators for town in liberated_towns) total_oppressors = sum(town.oppressors for town in oppressed_towns) total_liberated = sum(town.liberated for town in liberated_towns) total_oppressed = sum(town.oppressed for town in oppressed_towns) oppressed_towns.sort(key=lambda town: safe_div(town.oppressed, town.oppressors), reverse=True) most_oppressed = oppressed_towns[-1] if free_liberators > 0: for town in liberated_towns: if town.id != current_id and needs_urgent_support(town): return "S {0} {1}".format(town.id, free_liberators // 2) if current_town.is_safe(): free_liberators = current_town.get_unneeded_liberators() if free_liberators > 0: for town in oppressed_towns: if can_beat(free_liberators, town): if total_liberated <= total_oppressed or town.owner_id != -1 or not any(town.owner_id != -1 for town in oppressed_towns): return "A {0} {1}".format(town.id, free_liberators) else: continue else: break for town in liberated_towns: if not town.is_safe(): return "S {0} {1}".format(town.id, free_liberators) liberated_towns.sort(key=lambda town: (town.liberated, town.liberators), reverse=True) ## if current_id == liberated_towns[0].id and total_oppressors > total_oppressors and can_damage(free_liberators, most_oppressed): ## return "A {0} {1}".format(most_oppressed.id, free_liberators) if current_id != liberated_towns[0].id: return "S {0} {1}".format(liberated_towns[0].id, free_liberators) return "W" main() ``` The sole goal of this bot is to free the most common people from the oppressive yoke of tyranny. [Answer] # Python 2, The King The King rules the highest number town of his empire, and demands all excess knights to be sent to him from other towns under his control. When he has enough knights, he will attack an enemy town. He is not a very smart King, so has not studied history or understands the consequences of his actions. ``` import sys from random import * PLAYER, TOWN, KNIGHTS, SERFS = range(4) if len(sys.argv) < 2: print randint(20,100), randint(50,100), randint(70,100) else: parts = sys.argv[1].split(';') turn, me, thistown = [int(parts.pop(0)) for i in range(3)] towns = [[int(v) for v in town.split('_')] for town in parts] enemy = [t for t in towns if t[PLAYER] != me] mytowns = [t for t in towns if t[PLAYER] == me] here = [t for t in mytowns if t[TOWN] == thistown][0] avgfree = sum(t[KNIGHTS]-t[SERFS]/2 for t in towns) / len(towns) free = here[KNIGHTS] - here[SERFS]/2 last = mytowns[-1] if here == last: needed, target = min([(t[KNIGHTS]*1.2+t[SERFS]/2, t) for t in enemy]) if free > needed+5: print 'A', target[TOWN], int(free+needed)/2 + 1 else: print 'W' else: spare = max(0, free - avgfree) if spare: print 'S', last[TOWN], spare else: print 'W' ``` This is untested with the controller or other bots. [Answer] # Javascript (Node), Empire Starts off strong to scare off other towns. Towns try to work together to capture others. Prioritizes capturing towns with many lowborns. ``` /*jshint node:true*/ 'use strict'; function startGame() { console.log('80 70 60'); } function parseArgs(args) { var state = { players: [], towns: [] }; var argArray = args.split(';'); state.currentTurn = parseInt(argArray.splice(0, 1)[0], 10); var myId = argArray.splice(0, 1)[0]; var myTownId = parseInt(argArray.splice(0, 1)[0], 10); for(var townIndex = 0; townIndex < argArray.length; townIndex++) { var townArgs = argArray[townIndex].split('_'); var playerId = townArgs[0]; var townId = parseInt(townArgs[1], 10); var player = state.players[playerId]; if(!player) { player = { towns: [] }; state.players[playerId] = player; } var town = { id: townId, knights: parseInt(townArgs[2], 10), lowborns: parseInt(townArgs[3], 10), player: player }; state.towns[townId] = town; player.towns.push(town); } state.me = state.players[myId]; state.currentTown = state.towns[myTownId]; return state; } function getDefense(town) { return Math.floor(town.knights * 1.2) + Math.ceil(town.lowborns / 2) + 1; } function getAttackers(town) { return Math.max(town.knights - Math.ceil(town.lowborns / 2), 0); } function attackTown(town, strength) { console.log('A ' + town.id + ' ' + strength); } function supportTown(town, strength) { console.log('S ' + town.id + ' ' + strength); } function wait() { console.log('W'); } function processTurn(gameState) { var attackers = getAttackers(gameState.currentTown); if(attackers > 0) { var totalAttackers = attackers; var helperIndex = (gameState.currentTown.id + 1) % gameState.towns.length; while(gameState.towns[helperIndex].player === gameState.me) { totalAttackers += getAttackers(gameState.towns[helperIndex]); helperIndex = (helperIndex + 1) % gameState.towns.length; } var bestTarget; for(var targetIndex = 0; targetIndex < gameState.towns.length; targetIndex++) { var targetTown = gameState.towns[targetIndex]; if(targetTown.player !== gameState.me) { var defense = getDefense(targetTown); if(defense < totalAttackers) { if(!bestTarget) { bestTarget = targetTown; } else if(targetTown.lowborns > bestTarget.lowborns) { bestTarget = targetTown; } else if(getDefense(bestTarget) < defense) { bestTarget = targetTown; } } } } if(bestTarget) { return attackTown(bestTarget, Math.min(attackers, getDefense(bestTarget))); } var smallestTown; var smallestSize = gameState.currentTown.knights; for(var myTownIndex = 0; myTownIndex < gameState.me.towns.length; myTownIndex++) { var myTown = gameState.me.towns[myTownIndex]; if(myTown.knights < smallestSize) { smallestTown = myTown; smallestSize = smallestTown.knights; } } if(smallestTown) { var supporters = Math.floor((smallestSize - gameState.currentTown.knights) / 2); supporters = Math.min(supporters, attackers); if(supporters > 0) { return supportTown(smallestTown, supporters); } } } wait(); } if(process.argv.length <= 2) { startGame(); } else { var gameState = parseArgs(process.argv[2]); processTurn(gameState); } ``` Run: **node empire** [Answer] # Java, Frankenstein While trying to find a way to destroy Liberator, a small mistake slipped into my code. The code then began to destroy the competition. After adding Democracy and rearranging the players, it began to fail. Studying the code I tried to find its strategy. Consequently, the following code was made. It tends to attack and destroy the best player. After the best players(s) are destroyed, this easily destroys the rest. ``` import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Frankenstein { int round; int playerID; int thisTownID; List<Town> towns; List<Town> myTowns; List<Town> otherTowns; private static final boolean DEBUG = true; Town thisTown; int scariestPlayerId = -1; int scariestPlayerRecord = -1; private static final String LOG_FILE_NAME = "EmperorLog.txt"; private static final String DATA_FILE_NAME = "Emperor.txt"; public static void main(String[] args){ try { if (args.length == 0) { System.out.println("100 100 100"); return; } Frankenstein frankenstein = new Frankenstein(); String result = frankenstein.destroy(args[0].split(";")); frankenstein.saveScariestPlayer(); System.out.println(result); if (DEBUG) { new PrintStream(new FileOutputStream(LOG_FILE_NAME, true)).print(args[0] + "\n" + result + "\n"); } } catch (Exception e){ if (DEBUG) { try { e.printStackTrace(new PrintStream(new FileOutputStream(LOG_FILE_NAME, true))); } catch (FileNotFoundException e1) { e1.printStackTrace(); } } } } private void saveScariestPlayer() throws FileNotFoundException { PrintStream out = new PrintStream(DATA_FILE_NAME); out.println(round); out.println(scariestPlayerId); out.println(scariestPlayerRecord); } private static int divide(int a, int b){ if (a == 0){ return 0; } if (b == 0){ return 1000; } return a/b; } private String destroy(String[] args) { round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); thisTownID = Integer.parseInt(args[2]); towns = new ArrayList<>(); myTowns = new ArrayList<>(); otherTowns = new ArrayList<>(); for (int i = 3; i < args.length; i++) { towns.add(new Town(args[i])); } for (Town town : towns) { if (town.isMine()) { myTowns.add(town); if (town.isThisTown()) { thisTown = town; } } else { otherTowns.add(town); } } loadScariestPlayer(); updateScariestPlayer(); if (thisTown.getFreeKnights() > 0){ for (Town town : myTowns){ if (town.needsHelp() && town.getFreeKnights() + thisTown.getFreeKnights() >= 0){ return "S " + town.getId() + " " + thisTown.getFreeKnights(); } } Town bestTown = otherTowns.stream().max((a, b) -> divide(a.lowbornCount() * (scariestPlayerId == -1 || scariestPlayerId == a.ownerId ? a.lowbornCount() : 1), a.knightCount()) - divide(b.lowbornCount() * (scariestPlayerId == -1 || scariestPlayerId == b.ownerId ? b.lowbornCount() : 1), b.knightCount())).get(); if (bestTown.numberOfKnightsToConquer() <= thisTown.getFreeKnights()){ return "A " + bestTown.getId() + " " + thisTown.getFreeKnights(); } myTowns.sort((a,b) -> b.knightCount() - a.knightCount()); myTowns.sort((a,b) -> b.lowbornCount() - a.lowbornCount()); if (!myTowns.get(0).isThisTown()){ return "S " + myTowns.get(0).getId() + " " + thisTown.getFreeKnights(); } } return "W"; } private void updateScariestPlayer() { Map<Integer, Integer> playerMap = new HashMap<>(); int biggestPlayerId = -1; for (Town town : otherTowns){ if (playerMap.containsKey(town.ownerId)){ playerMap.put(town.ownerId, town.lowbornCount() + playerMap.get(town.ownerId)); } else { playerMap.put(town.ownerId, town.lowbornCount()); } if (biggestPlayerId == -1 || playerMap.get(town.ownerId) > playerMap.get(biggestPlayerId)){ biggestPlayerId = town.ownerId; } } if (scariestPlayerId == -1 || scariestPlayerRecord == -1 || !playerMap.containsKey(scariestPlayerId) || playerMap.get(biggestPlayerId) > scariestPlayerRecord){ scariestPlayerId = biggestPlayerId; scariestPlayerRecord = playerMap.get(biggestPlayerId); } } private void loadScariestPlayer() { try { BufferedReader in = new BufferedReader(new FileReader(DATA_FILE_NAME)); int turn = Integer.parseInt(in.readLine()); if (turn != round || turn != round + 1){ throw new Exception(); } scariestPlayerId = Integer.parseInt(in.readLine()); scariestPlayerRecord = Integer.parseInt(in.readLine()); } catch (Exception e) { scariestPlayerId = -1; scariestPlayerRecord = -1; } } private class Town { final int ownerId; final int id; final int knights; final int lowborns; boolean defenseBonus; Town(String string) { String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); id = Integer.parseInt(args[1]); knights = Integer.parseInt(args[2]); lowborns = Integer.parseInt(args[3]); defenseBonus = true; } int getId() { return id; } int knightCount() { return knights; } int lowbornCount() { return lowborns; } boolean isMine() { return ownerId == playerID; } boolean isThisTown() { return id == thisTownID; } int getFreeKnights() { return knights - lowborns / 2 - 1; } int numberOfKnightsToConquer() { if (defenseBonus) { return ((knights * 6) / 5) + (lowborns / 2) + 1; } else { return knights + lowborns/2 + 1; } } int numberOfKnightsToOverthrow(){ if (defenseBonus) { return (((knights * 6) / 5) - (lowborns / 2)) + 1; } else { return knights - lowborns / 2 + 1; } } boolean needsHelp() { return getFreeKnights() < 0; } public boolean isNeutural() { return ownerId == -1; } } } ``` Here is the original player: ``` import java.util.ArrayList; import java.util.List; public class Frankenstein { int round; int playerID; int thisTownID; List<Town> towns; List<Town> myTowns; List<Town> otherTowns; Town thisTown; Player me; public static void main(String[] args) { if (args.length == 0) { System.out.println("100 100 100"); return; } new Frankenstein().destroy(args[0].split(";")); } private static int divide(int a, int b){ if (a == 0){ return 0; } if (b == 0){ return 1000000; } return a/b; } private void destroy(String[] args) { round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); thisTownID = Integer.parseInt(args[2]); towns = new ArrayList<>(); myTowns = new ArrayList<>(); otherTowns = new ArrayList<>(); for (int i = 3; i < args.length; i++) { towns.add(new Town(args[i])); } for (Town town : towns) { if (town.isMine()) { myTowns.add(town); if (town.isThisTown()) { thisTown = town; } } else { otherTowns.add(town); } } players.stream().filter(player -> player.id == playerID).forEach(player -> me = player); if (thisTown.getFreeKnights() > 0){ for (Town town : myTowns){ if (town.needsHelp()){ System.out.println("S " + town.getId() + " " + thisTown.getFreeKnights() / 2); return; } } Town richestTown = otherTowns.stream().max((a, b) -> divide(a.lowbornCount(), a.knightCount()) - divide(b.lowbornCount(), b.knightCount())).get(); if (richestTown.numberOfKnightsToConquer() < thisTown.getFreeKnights()){ System.out.println("A " + richestTown.getId() + " " + thisTown.getFreeKnights()); return; } otherTowns.sort((a,b) -> divide(b.lowbornCount() * b.owner.richness(), b.getFreeKnights()) - divide(a.lowbornCount() * a.owner.richness(), a.getFreeKnights())); if (thisTown.getFreeKnights() >= otherTowns.get(0).numberOfKnightsToOverthrow() && !otherTowns.get(0).isNeutral()){ System.out.println("A " + otherTowns.get(0).getId() + " " + otherTowns.get(0).numberOfKnightsToOverthrow()); return; } myTowns.sort((a,b) -> b.knightCount() - a.knightCount()); myTowns.sort((a,b) -> b.lowbornCount() - a.lowbornCount()); if (!myTowns.get(0).isThisTown()){ System.out.println("S " + myTowns.get(0).getId() + " " + thisTown.getFreeKnights()); return; } } System.out.println("W"); } private class Town { private final int ownerId; private final int id; private final int knights; private final int lowborns; private final Player owner; private Town(String string) { String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); id = Integer.parseInt(args[1]); knights = Integer.parseInt(args[2]); lowborns = Integer.parseInt(args[3]); for (Player player : players){ if (player.id == ownerId){ player.addTown(this); owner = player; return; } } owner = new Player(id);//This mistake makes my player perform really good for some reason. owner.towns.add(this); } private int getId() { return id; } private int knightCount() { return knights; } private int lowbornCount() { return lowborns; } private boolean isMine() { return ownerId == playerID; } private boolean isThisTown() { return id == thisTownID; } private int getFreeKnights() { return knights - lowborns / 2 - 1; } private int numberOfKnightsToConquer() { return ((knights * 6) / 5) + (lowborns / 2) + 1; } private int numberOfKnightsToOverthrow(){ return (((knights * 6) / 5) - (lowborns / 2)) + 1; } private boolean needsHelp() { return getFreeKnights() < 0; } private boolean isNeutral() { return owner.id == -1; } } List<Player> players = new ArrayList<>(); private class Player{ int id; List<Town> towns; int richness = 0; Player(int id){ this.id = id; this.towns = new ArrayList<>(); players.add(this); } void addTown(Town t){ towns.add(t); richness += t.lowbornCount(); } int richness(){ return id == -1 ? (towns.size() > 0 ? 1 : 0) : richness; } } } ``` [Answer] # Java, Turtle Thanks to TheBestOne for core methods, I just changed the algorithm (I hope that's OK). This bot basically upgrades its best defended town to rival the most dangerous enemy town, while keeping enough knights to prevent rebellion in its other towns. ``` import java.util.ArrayList; import java.util.List; public class Turtle { int round; int playerID; int thisTownID; List<Town> towns; List<Town> myTowns; List<Town> otherTowns; Town thisTown; public static void main(String[] args){ if (args.length == 0){ System.out.println("34 34 34"); return; } new Turtle().defend(args[0].split(";")); } private void defend(String[] args) { round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); thisTownID = Integer.parseInt(args[2]); towns = new ArrayList<>(); myTowns = new ArrayList<>(); otherTowns = new ArrayList<>(); for (int i = 3; i < args.length; i++){ towns.add(new Town(args[i])); } for (Town town : towns){ if (town.isMine()){ myTowns.add(town); if (town.isThisTown()){ thisTown = town; } } else { otherTowns.add(town); } } Town bestDefendedTown = null; for (Town town : myTowns) { if (bestDefendedTown == null) bestDefendedTown = town; bestDefendedTown = bestDefendedTown.knightCount() >= town.knightCount() ? bestDefendedTown : town; } Town dangerousEnemyTown = null; for (Town town : otherTowns) { if (dangerousEnemyTown == null) dangerousEnemyTown = town; dangerousEnemyTown = dangerousEnemyTown.knightCount() >= town.knightCount() ? dangerousEnemyTown : town; } int missingKnights = dangerousEnemyTown.knightCount() - bestDefendedTown.knightCount() > 0 ? dangerousEnemyTown.knightCount() - bestDefendedTown.knightCount() : 0; int reinforcements = thisTown.getFreeKnights() - (missingKnights + 1) > 0 ? thisTown.getFreeKnights() - (missingKnights + 1) : thisTown.getFreeKnights(); if (reinforcements > 0) { System.out.println("S " + bestDefendedTown.getId() + " " + reinforcements); } else { System.out.println("W"); } } private class Town { private final int ownerId; private final int id; private final int knights; private final int lowborns; public Town(String string){ String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); id = Integer.parseInt(args[1]); knights = Integer.parseInt(args[2]); lowborns = Integer.parseInt(args[3]); } public int getId() { return id; } public int getOwner() { return ownerId; } public int knightCount() { return knights; } public int lowbornCount() { return lowborns; } public boolean isMine(){ return ownerId == playerID; } public boolean isThisTown(){ return id == thisTownID; } private int getFreeKnights() { return knights - lowborns / 2 - 1; } } } ``` Compile: `javac Turtle.java` Run: `java Turtle` [Answer] # Java 8, Politician Acts like a true politician. Too bad Crasher still slaughters him. ``` import java.util.ArrayList; import java.util.List; public class Politician { int round; int playerID; int thisTownID; List<Town> towns; List<Town> myTowns; List<Town> otherTowns; Town thisTown; public static void main(String[] args){ if (args.length == 0){ System.out.println("34 34 34"); return; } new Politician().bribe(args[0].split(";")); } private void bribe(String[] args) { round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); thisTownID = Integer.parseInt(args[2]); towns = new ArrayList<>(); myTowns = new ArrayList<>(); otherTowns = new ArrayList<>(); for (int i = 3; i < args.length; i++){ towns.add(new Town(args[i])); } for (Town town : towns){ if (town.isMine()){ myTowns.add(town); if (town.isThisTown()){ thisTown = town; } } else { otherTowns.add(town); } } Town biggestTown = otherTowns.stream().max((a,b) -> a.knights - b.knights).get(); if (thisTown.getFreeKnights() <= 0){//Out of knights. System.out.println("W");//Waiting for taxes so can hire more knights. } System.out.println("S " + biggestTown.getId() + " " + thisTown.getFreeKnights()); } private class Town { private final int ownerId; private final int id; private final int knights; private final int lowborns; public Town(String string){ String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); id = Integer.parseInt(args[1]); knights = Integer.parseInt(args[2]); lowborns = Integer.parseInt(args[3]); } public int getId() { return id; } public int getOwner() { return ownerId; } public int knightCount() { return knights; } public int lowbornCount() { return lowborns; } public boolean isMine(){ return ownerId == playerID; } public boolean isThisTown(){ return id == thisTownID; } private int getFreeKnights() { return knights - lowborns / 2 - 1; } } } ``` Compile: `javac Politician.java` Run: `java Politician` [Answer] # Java 8, Butter Spreads itself as evenly as possible. Smothers a town if the town is sufficiently small. ``` import java.util.ArrayList; import java.util.List; public class Butter { int round; int playerID; int thisTownID; List<Town> towns; List<Town> myTowns; List<Town> otherTowns; Town thisTown; public static void main(String[] args){ if (args.length == 0){ System.out.println("34 34 34"); return; } new Butter().spread(args[0].split(";")); } private void spread(String[] args) { round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); thisTownID = Integer.parseInt(args[2]); towns = new ArrayList<>(); myTowns = new ArrayList<>(); otherTowns = new ArrayList<>(); for (int i = 3; i < args.length; i++){ towns.add(new Town(args[i])); } for (Town town : towns){ if (town.isMine()){ myTowns.add(town); if (town.isThisTown()){ thisTown = town; } } else { otherTowns.add(town); } } Town mySmallestTown = myTowns.stream().min((a, b) -> a.getFreeKnights() - b.getFreeKnights()).get(); Town smallestEnemyTown = otherTowns.stream().min((a,b) -> a.knights - b.knights).get(); if ((thisTown.getFreeKnights() - mySmallestTown.getFreeKnights())/2 > 0) { System.out.println("S " + mySmallestTown.getId() + " " + (thisTown.getFreeKnights() - mySmallestTown.getFreeKnights()) / 2); } else if (thisTown.getFreeKnights() / 2 > smallestEnemyTown.numberOfKnightsToConquer()){ System.out.println("A " + smallestEnemyTown.getId() + " " + smallestEnemyTown.numberOfKnightsToConquer()); } else { System.out.println("W"); } } private class Town { private final int ownerId; private final int id; private final int knights; private final int lowborns; private Town(String string){ String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); id = Integer.parseInt(args[1]); knights = Integer.parseInt(args[2]); lowborns = Integer.parseInt(args[3]); } private int getId() { return id; } private int getOwner() { return ownerId; } private int knightCount() { return knights; } private int lowbornCount() { return lowborns; } private boolean isMine(){ return ownerId == playerID; } private boolean isThisTown(){ return id == thisTownID; } private int getFreeKnights() { return knights - lowborns / 2 - 1; } private int numberOfKnightsToConquer(){ return ((knights * 6) / 5) + (lowborns / 2) + 1; } } } ``` Compile: `javac Butter.java` Run: `java Butter` [Answer] # Java, Revolutionist A last one, still based on TheBestOne core methods. This bot tries to incite rebellions in every town, since Neutral player is inoffensive, by killing a certain amount of knights relative to lowborn population. It will of course not attack Neutral player. ``` import java.util.ArrayList; import java.util.List; public class Revolutionist { int round; int playerID; int thisTownID; List<Town> towns; List<Town> myTowns; List<Town> otherTowns; Town thisTown; public static void main(String[] args){ if (args.length == 0){ System.out.println("80 80 80"); return; } new Revolutionist().inciteRebellion(args[0].split(";")); } private void inciteRebellion(String[] args) { round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); thisTownID = Integer.parseInt(args[2]); towns = new ArrayList<>(); myTowns = new ArrayList<>(); otherTowns = new ArrayList<>(); for (int i = 3; i < args.length; i++){ towns.add(new Town(args[i])); } for (Town town : towns){ if (town.isMine()){ myTowns.add(town); if (town.isThisTown()){ thisTown = town; } } else { otherTowns.add(town); } } Town onEdgeTown = null; int edgeCounter = 100; for (Town town : otherTowns) { if (onEdgeTown == null) onEdgeTown = town; if (town.getFreeKnights() >= 0 && town.getFreeKnights() <= edgeCounter && town.getOwner() >= 0) { onEdgeTown = town; edgeCounter = town.getFreeKnights(); } } int minimumRequiredKnights = (int) ((onEdgeTown.knightCount() * 1.2 - onEdgeTown.getMinimumKnights() + 2) * 1.2) ; if (thisTown.getFreeKnights() > minimumRequiredKnights && onEdgeTown.getOwner() >= 0) System.out.println("A " + onEdgeTown.getId() + " " + minimumRequiredKnights); else System.out.println("W"); } private class Town { private final int ownerId; private final int id; private final int knights; private final int lowborns; public Town(String string){ String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); id = Integer.parseInt(args[1]); knights = Integer.parseInt(args[2]); lowborns = Integer.parseInt(args[3]); } public int getId() { return id; } public int getOwner() { return ownerId; } public int knightCount() { return knights; } public int lowbornCount() { return lowborns; } public boolean isMine(){ return ownerId == playerID; } public boolean isThisTown(){ return id == thisTownID; } private int getFreeKnights() { return knights - lowborns / 2 - 1; } private int getMinimumKnights() { return lowborns / 2 + 1; } } } ``` Compile: `javac Revolutionist.java` Run: `java Revolutionist` [Answer] ## JAVA, Sehtimianer Thanks again to TheBestOne, I copied his core methods too ; ) This is my first time playing a KingOfTheHill-CodeGame, so I hope I did everything right. I proudly present the Sehtimianers :D ``` import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class Sehtimianer { private static final String FILENAME = "Sehtimianer.txt"; private static final int AGGRESSIVE_ROUND_BORDER = 80; int round; int playerID; int thisTownID; List<Town> towns = new ArrayList<Town>(); List<Town> myTowns = new ArrayList<Town>(); List<Town> playerTowns = new ArrayList<Town>(); List<Town> neutralTowns = new ArrayList<Town>(); Map<Integer, Integer> townToPlayerMapping = new HashMap<Integer, Integer>(); boolean isAllowedToWriteMapping = true; Town thisTown; public static void main(String[] args) { if (args.length == 0) { // new File(FILENAME).delete(); System.out.println("100 100 100"); return; } new Sehtimianer().decide(args[0].split(";")); } private void decide(String[] args) { // final long start = System.currentTimeMillis(); round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); thisTownID = Integer.parseInt(args[2]); for (int i = 3; i < args.length; i++) { towns.add(new Town(args[i])); } for (Town town : towns) { if (town.isMine()) { myTowns.add(town); if (town.isThisTown()) { thisTown = town; } } else { if (town.getOwner() == -1) { neutralTowns.add(town); } else { playerTowns.add(town); } } } if (new File(FILENAME).exists()) { try { BufferedReader reader = new BufferedReader(new FileReader(FILENAME)); String inputLine; String[] ids; while ((inputLine = reader.readLine()) != null) { ids = inputLine.split(";"); if (ids.length == 1) { Integer writingTownID = Integer.valueOf(ids[0]); boolean townIsLost = true; for (Town town : myTowns) { if (town.getId() == writingTownID) { townIsLost = false; break; } } isAllowedToWriteMapping = townIsLost || thisTownID == writingTownID; continue; } townToPlayerMapping.put(Integer.valueOf(ids[0]), Integer.valueOf(ids[1])); } reader.close(); for (Town town : towns) { if (!townToPlayerMapping.get(town.getId()).equals(town.getOwner())) { town.setDefenseBonus(false); } } } catch (IOException e) { // Dont worry : ) } } if (round == 1) { int maxKnights = 0; int maxKnightTownID = thisTownID; for (Town town : myTowns) { if (town == thisTown) { continue; } if (town.knightCount() > maxKnights) { maxKnights = town.knightCount(); maxKnightTownID = town.getId(); } } if (maxKnightTownID != thisTownID) { System.out.println("S " + maxKnightTownID + " " + thisTown.knightCount()); } } else if (round % 3 == 2) { int myKnightIncome = 0; for (Town town : myTowns) { myKnightIncome += town.lowbornCount() / 2; } Map<Integer, Integer> playerKnightIncomeMap = new HashMap<Integer, Integer>(); Map<Integer, Integer> playerTownCountMap = new HashMap<Integer, Integer>(); List<Integer> nextRoundKnights = new ArrayList<Integer>(); Map<Integer, Town> nextRoundKnightsToTownMapping = new HashMap<Integer, Town>(); for (Town town : playerTowns) { fillDescisionMaps(town, nextRoundKnights, nextRoundKnightsToTownMapping, playerKnightIncomeMap, playerTownCountMap); } for (Town town : neutralTowns) { fillDescisionMaps(town, nextRoundKnights, nextRoundKnightsToTownMapping, playerKnightIncomeMap, playerTownCountMap); } Integer maxEnemyKnightIncome = 0; for (Integer knightIncome : playerKnightIncomeMap.values()) { if (knightIncome > maxEnemyKnightIncome) { maxEnemyKnightIncome = knightIncome; } } Integer maxEnemyTownCount = 0; for (Integer townCount : playerTownCountMap.values()) { if (townCount > maxEnemyTownCount) { maxEnemyTownCount = townCount; } } if (maxEnemyKnightIncome > myKnightIncome || (round > AGGRESSIVE_ROUND_BORDER && maxEnemyTownCount >= myTowns.size())) { Collections.sort(nextRoundKnights); int possibleHighest = 0; Town enemyTown; int enemyTownUpkeep; for (int i = nextRoundKnights.size() - 1; i >= 0; i--) { possibleHighest = nextRoundKnights.get(i); enemyTown = nextRoundKnightsToTownMapping.get(possibleHighest); enemyTownUpkeep = enemyTown.lowbornCount() / 2; if (enemyTownUpkeep > (possibleHighest - enemyTownUpkeep)) { // Substract the calculated Income for the next Turn // Town will be lost because of revolution after captured -> Bad target possibleHighest = 0; continue; } if (round > AGGRESSIVE_ROUND_BORDER || enemyTown.lowbornCount() > 0) { break; } } if (possibleHighest > 0) { Town attackedTown = nextRoundKnightsToTownMapping.get(possibleHighest); System.out.println("A " + attackedTown.getId() + " " + calcHowMuchKnightsShouldAttack(attackedTown, possibleHighest)); } } } if (isAllowedToWriteMapping) { try { BufferedWriter writer = new BufferedWriter(new FileWriter(FILENAME)); writer.write(thisTownID + "\n"); for (Town town : towns) { writer.write(town.getId() + ";" + town.getOwner() + "\n"); } writer.close(); } catch (IOException e) { // Dont worry : ) } } System.out.println("W"); // long duration = System.currentTimeMillis() - start; // if (duration > 1000) { // throw new RuntimeException(); // } } private void fillDescisionMaps(Town town, List<Integer> nextRoundKnights, Map<Integer, Town> nextRoundKnightsToTownMapping, Map<Integer, Integer> playerKnightIncomeMap, Map<Integer, Integer> playerTownCountMap) { int calculatedKnights = calcKnightsInNextRound(town); nextRoundKnights.add(calculatedKnights); nextRoundKnightsToTownMapping.put(calculatedKnights, town); Integer enemyKnightIncome = playerKnightIncomeMap.get(town.getOwner()); if (enemyKnightIncome == null) { enemyKnightIncome = town.lowbornCount() / 2; } else { enemyKnightIncome = enemyKnightIncome + (town.lowbornCount() / 2); } playerKnightIncomeMap.put(town.getOwner(), enemyKnightIncome); Integer enemyTownCount = playerTownCountMap.get(town.getOwner()); if (enemyTownCount == null) { enemyTownCount = Integer.valueOf(1); } else { enemyTownCount = enemyTownCount + 1; } playerTownCountMap.put(town.getOwner(), enemyTownCount); } private int calcKnightsInNextRound(Town enemyTown) { int knights = (int) ((double) enemyTown.knightCount() * (enemyTown.isDefenseBonus() ? 1.2 : 1)); knights = thisTown.getFreeKnights() - knights; if (knights > 0) { knights += enemyTown.lowbornCount() / 2; } else { knights = 0; } return knights; } private int calcHowMuchKnightsShouldAttack(Town enemyTown, int possibleHighest) { if (round < AGGRESSIVE_ROUND_BORDER && thisTown.lowbornCount() == 0) { return thisTown.knightCount(); } int spareKnights = possibleHighest - enemyTown.lowbornCount(); // Correct -> div 2 and mul 2 int minShouldSend = thisTown.getFreeKnights() - (spareKnights / 2); return Math.max(minShouldSend, thisTown.knightCount() / 2); } private class Town { private final int ownerId; private final int id; private final int knights; private final int lowborns; private boolean defenseBonus; public Town(String string) { String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); id = Integer.parseInt(args[1]); knights = Integer.parseInt(args[2]); lowborns = Integer.parseInt(args[3]); defenseBonus = true; } public boolean isDefenseBonus() { return defenseBonus; } public void setDefenseBonus(boolean defenseBonus) { this.defenseBonus = defenseBonus; } public int getId() { return id; } public int getOwner() { return ownerId; } public int knightCount() { return knights; } public int lowbornCount() { return lowborns; } public boolean isMine() { return ownerId == playerID; } public boolean isThisTown() { return id == thisTownID; } private int getFreeKnights() { return knights - lowborns / 2 - 1; } } } ``` The Sehtimianers try to be superior the whole game and finish it at the end. I hope my bot won't do too bad : ) [Answer] # Java, Exodus Once again, based on TheBestOne core methods. This bot migrates from town to town once it had reached a certain level of knight population, indiscriminately of its owner, and repeat this process until it has converted the whole world. ``` import java.util.ArrayList; import java.util.List; public class Exodus { int round; int playerID; int thisTownID; List<Town> towns; List<Town> myTowns; List<Town> otherTowns; Town thisTown; public static void main(String[] args){ if (args.length == 0){ System.out.println("100 100 100"); return; } new Exodus().migrate(args[0].split(";")); } private void migrate(String[] args) { round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); thisTownID = Integer.parseInt(args[2]); towns = new ArrayList<>(); myTowns = new ArrayList<>(); otherTowns = new ArrayList<>(); for (int i = 3; i < args.length; i++){ towns.add(new Town(args[i])); } for (Town town : towns){ if (town.isMine()){ myTowns.add(town); if (town.isThisTown()){ thisTown = town; } } else { otherTowns.add(town); } } if (thisTown.knightCount() >= 100) { int nextTownId = thisTown.getId() + 1 > towns.size() - 1 ? 0 : thisTown.getId() + 1; Town nextTown = towns.get(nextTownId); if (nextTown.isMine()){ System.out.println("S " + nextTown.getId() + " " + thisTown.knightCount()) ; } else { System.out.println("A " + nextTown.getId() + " " + thisTown.knightCount()) ; } } else { System.out.println("W") ; } } private class Town { private final int ownerId; private final int id; private final int knights; private final int lowborns; public Town(String string){ String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); id = Integer.parseInt(args[1]); knights = Integer.parseInt(args[2]); lowborns = Integer.parseInt(args[3]); } public int getId() { return id; } public int getOwner() { return ownerId; } public int knightCount() { return knights; } public int lowbornCount() { return lowborns; } public boolean isMine(){ return ownerId == playerID; } public boolean isThisTown(){ return id == thisTownID; } private int getFreeKnights() { return knights - lowborns / 2 - 1; } } } ``` Compile: `javac Exodus.java` Run: `java Exodus` [Answer] # Python 2, Democracy This king is not king. It's something modern. It's *the king of people*. It's democracy. It's slow, unefficient, and when it does something it does it wrong. ``` import sys from math import sqrt, ceil class Town: def __init__(self, owner, ID, military, civilian): self.owner=owner self.id=ID self.isEnemy=(self.owner!=PlayerId) self.isCurrent=(self.id!=TownId) self.mil=military self.civ=civilian self.freeK=self.mil-self.civ/2 def canBeat(self, other): otherPower = int(ceil(other.mil*1.2)) otherMinPower = int(ceil(other.freeK*1.2)) selfPower = self.freeK if selfPower<otherMinPower: return 0 elif selfPower<otherPower or (selfPower-otherPower)*2-1<other.civ: return 1 else: return 2 def canMove(self, other): otherPower = int(ceil(other.mil*1.2)) otherMinPower = int(ceil(other.freeK*1.2)) if otherPower<self.mil: return 2 elif otherMinPower<=self.mil: return 1 else: return 0 def canDefend(self, other): return self.freeK>other.mil def attack_weak(): for town in EnemyTowns: if curr.canMove(town)==2: print "A", town.id, curr.mil exit() for town in EnemyTowns: if curr.canMove(town)==1: print "A", town.id, curr.mil exit() target=EnemyTowns[0] for et in EnemyTowns: if et.mil<target.mil and et.id!=-1: target=et print "A", target.id, curr.mil-1 exit() if len(sys.argv) < 2: print 96, 96, 96 else: Round, PlayerId, TownId, Towns = sys.argv[1].split(";", 3) Round=int(Round) PlayerId=int(PlayerId) TownId=int(TownId) Towns=[[int(i) for i in town.split("_")] for town in Towns.split(";")] Towns=[Town(i[0], i[1], i[2], i[3]) for i in Towns] MyTowns=[t for t in Towns if t.isEnemy==False] EnemyTowns=[t for t in Towns if t.isEnemy] GameStateEnd = [t for t in EnemyTowns if t.id!=-1]==[] curr=[town for town in MyTowns if town.isCurrent][0] support=[town for town in MyTowns if town.freeK<1] if support!=[]: for town in support: if town.id==curr.id: missing=town.freeK-int(ceil(town.civ/2)) if town.civ<5: attack_weak() elif town.freeK<-10: attack_weak() else: print "W" exit() for town in support: if abs(town.freeK-2)<curr.freeK-2: print "S", town.id, abs(town.freeK-2) exit() else: if curr.freeK>10: print "S", town.id, int(abs(town.freeK-2)*0.2) exit() if GameStateEnd: attack_end() else: selection=EnemyTowns[:] selection.sort(key=(lambda x: (x.mil-x.civ) if x.civ>3 else x.mil/4)) for s in selection: if curr.canBeat(s)==2 and s.civ>s.mil/2: NF=(int(ceil(s.mil*1.2))+s.civ/2+1) if curr.mil>NF: print "A", s.id, NF+(curr.mil-NF)/3 exit() if curr.freeK>10: MyTowns.sort(key=lambda x: x.mil) print "S", MyTowns[-1].id, (curr.freeK-5)/5*3 exit() print "W" exit() ``` Run `python2 democracy.py`. Note that democracy *requires* Python **2**. **Edit: Fixed bug about printing town object** [Answer] # C++11, CalculatedFail after i tried a few things in with the little Java i know and was not quite able to achieve what i wanted, i choose to re-write it in C++ and add file handling. problem was, my C++ is quite rusty and not much better, so some parts are whacked together and just the first solution in google, so not really quality code... still, i was able to get a at least working result that doesn't to suck that much, it wins atleast occasionally, but I cant test it perfectly because i am not able to run all other submissions on this pc. I probably will re-write the targeting altogether and will add it as another answer later today or tomorrow. ``` #include <iostream> #include <string> #include <vector> #include <sstream> #include <cmath> #include <ratio> #include <fstream> #include <algorithm> using namespace std; class Town { public: Town(int owner, int townId, int knights, int population, int roundToDefBonus); int getOwner(); int getId(); int getKnights(); int getPopulation(); int getFreeKnights(); int neededConquer(); int getKnightsStable(); int getRoundToDef(); bool operator< (const Town &other) const { return townId < other.townId; } private: int owner; int townId; int knights; int population; int roundToDefBonus; double defBonus; }; Town::Town(int inOwner, int inTownId, int inKnights, int inPopulation, int inRoundToDefBonus) { owner = inOwner; townId = inTownId; knights = inKnights; population = inPopulation; roundToDefBonus = inRoundToDefBonus; if(roundToDefBonus > 0) { defBonus = 1; } else{ defBonus = 1.2; } } int Town::getOwner() { return owner; } int Town::getId() { return townId; } int Town::getKnights() { return knights; } int Town::getPopulation() { return population; } int Town::getFreeKnights() { return knights - population / 2; } int Town::neededConquer() { return max(static_cast<int>(ceil(knights * defBonus + population / 2)), 1); } int Town::getKnightsStable() { return population / 2; } int Town::getRoundToDef() { return roundToDefBonus; } int gameRound; int myId; int thisTownId; Town* thisTown; vector <Town> myTowns; vector <Town> enemyTowns; vector <Town> lastTime; string turn(); Town* bestTarget(int knights); Town* bestSafe(int knights); Town* biggestTarget(int knights); Town* biggestSafe(int knights); string out(string, int, int); string attack(Town*); string safe(Town*); bool sortTowns(const Town & t1, const Town & t2); vector <string> stringSplit(string input, string delimeter); int main(int argc, char* argv[]) { if(argc < 2){ cout << "100 100 100"; ofstream myFile; myFile.open("CalculatedFail.txt"); myFile << "0\n"; myFile.close(); } else{ if(argc == 2){ string input = argv[1]; vector <string> params = stringSplit(input, ";"); gameRound = atoi(params.at(0).c_str()); myId = atoi((params.at(1)).c_str()); thisTownId = atoi(params.at(2).c_str()); ifstream myfile("CalculatedFail.txt"); if(myfile.is_open()){ string line; getline(myfile, line); bool newRound = false; if(atoi(line.c_str()) > gameRound) { newRound = true; } vector <string> oldVals; if(!newRound) { while (getline(myfile, line)) { oldVals = stringSplit(line, "_"); int playerId = atoi(oldVals.at(0).c_str()); int townId = atoi(oldVals.at(1).c_str()); int knights = atoi(oldVals.at(2).c_str()); int population = atoi(oldVals.at(3).c_str()); int roundToDefBonus = atoi(oldVals.at(4).c_str()); lastTime.push_back(Town(playerId, townId, knights, population, roundToDefBonus)); oldVals.clear(); } } else { while (getline(myfile, line)) { oldVals = stringSplit(line, "_"); int playerId = atoi(oldVals.at(0).c_str()); int townId = atoi(oldVals.at(1).c_str()); int knights = atoi(oldVals.at(2).c_str()); int population = atoi(oldVals.at(3).c_str()); int roundToDefBonus = atoi(oldVals.at(4).c_str()); if(roundToDefBonus) { //if round def bonus > 0, decrement because new round roundToDefBonus --; } lastTime.push_back(Town(playerId, townId, knights, population, roundToDefBonus)); oldVals.clear(); } } std::sort(lastTime.begin(), lastTime.end()); } if(lastTime.size() > 0) { vector <string> values; for(int i = 3; i < params.size(); i++) { values = stringSplit(params.at(i), "_"); int playerId = atoi(values.at(0).c_str()); int townId = atoi(values.at(1).c_str()); int knights = atoi(values.at(2).c_str()); int population = atoi(values.at(3).c_str()); int roundsToDef = lastTime.at(townId).getRoundToDef(); if(playerId != lastTime.at(townId).getOwner()) { roundsToDef = 2; } if(playerId == myId){ if(thisTownId != townId) myTowns.push_back(Town(playerId, townId, knights, population, roundsToDef)); else{ thisTown = new Town(playerId, townId, knights, population, roundsToDef); } } else{ enemyTowns.push_back(Town(playerId, townId, knights, population, roundsToDef)); } values.clear(); } } else { vector <string> values; for(int i = 3; i < params.size(); i++) { values = stringSplit(params.at(i), "_"); int playerId = atoi(values.at(0).c_str()); int townId = atoi(values.at(1).c_str()); int knights = atoi(values.at(2).c_str()); int population = atoi(values.at(3).c_str()); if(playerId == myId){ if(thisTownId != townId) myTowns.push_back(Town(playerId, townId, knights, population, 0)); else{ thisTown = new Town(playerId, townId, knights, population, 0); } } else{ enemyTowns.push_back(Town(playerId, townId, knights, population, 0)); } values.clear(); } } string tmp = turn(); cout << tmp; ofstream writeFile("CalculatedFail.txt"); if(writeFile.is_open()) { writeFile << gameRound <<"\n"; writeFile << thisTown->getOwner() <<"_"<<thisTown->getId()<<"_"<<thisTown->getKnights()<<"_"<< thisTown->getPopulation()<<"_"<<thisTown->getRoundToDef()<<"\n"; for(vector<Town>::size_type i = 0; i != myTowns.size(); i++) { writeFile << myTowns[i].getOwner() <<"_"<<myTowns[i].getId()<<"_"<<myTowns[i].getKnights()<<"_"<< myTowns[i].getPopulation()<<"_"<<myTowns[i].getRoundToDef()<<"\n"; } for(vector<Town>::size_type i = 0; i != enemyTowns.size(); i++) { writeFile << enemyTowns[i].getOwner() <<"_"<<enemyTowns[i].getId()<<"_"<<enemyTowns[i].getKnights()<<"_"<< enemyTowns[i].getPopulation()<<"_"<<enemyTowns[i].getRoundToDef()<<"\n"; } } } else{ cout<<"error, wrong parameter"; } } delete thisTown; return 0; } string turn() { Town* safeTarget; Town* attackTarget; if(thisTown->getFreeKnights() < 0) { //evacuate safeTarget = biggestSafe(thisTown->getKnights()); attackTarget = biggestTarget(thisTown->getKnights()); if(safeTarget != nullptr && attackTarget != nullptr){ if(safeTarget->getPopulation() > attackTarget->getPopulation()) { return out("S", safeTarget->getId(), thisTown->getKnights()); } else { return out("A", attackTarget->getId(), thisTown->getKnights()); } } if(safeTarget){ return out("S", safeTarget->getId(), thisTown->getKnights()); } if(attackTarget){ return out("A", attackTarget->getId(), thisTown->getKnights()); } Town* target = &myTowns.at(0); for(vector<Town>::size_type i = 1; i != myTowns.size(); i++) { if(target->getPopulation() < myTowns[i].getPopulation()) target = &myTowns[i]; } return out("S", target->getId(), thisTown->getKnights()); } safeTarget = biggestSafe(thisTown->getFreeKnights()); attackTarget = bestTarget(thisTown->getFreeKnights()); if(safeTarget != nullptr && attackTarget != nullptr){ if(safeTarget->getPopulation() > attackTarget->getPopulation()) { return safe(safeTarget); } else { return attack(attackTarget); } } if(safeTarget){ return safe(safeTarget); } if(attackTarget){ return attack(attackTarget); } return "W"; } Town* bestTarget(int knights) { Town* target = nullptr; double ratio = -1; for(vector<Town>::size_type i = 0; i != enemyTowns.size(); i++) { if(enemyTowns[i].neededConquer() < knights) { if(enemyTowns[i].getPopulation() / enemyTowns[i].neededConquer() > ratio) { target = &enemyTowns[i]; ratio = enemyTowns[i].getPopulation() / enemyTowns[i].neededConquer(); } } } return target; } Town* biggestTarget(int knights) { Town* target = nullptr; int population = -1; for(vector<Town>::size_type i = 0; i != enemyTowns.size(); i++) { if(enemyTowns[i].neededConquer() < knights) { if(enemyTowns[i].getPopulation() > population) { target = &enemyTowns[i]; population = target->getPopulation(); } } } return target; } Town* biggestSafe(int knights) { Town* target = nullptr; int population = -1; for(vector<Town>::size_type i = 0; i != myTowns.size(); i++) { if(myTowns[i].getFreeKnights() < 0 && myTowns[i].getFreeKnights() + knights >= 0){ if(myTowns[i].getPopulation() > population) { target = &myTowns[i]; population = target->getPopulation(); } } } return target; } string attack(Town* target){ int knights; if(thisTown->getPopulation() > target->getPopulation()) { knights = target->neededConquer(); } else{ knights = thisTown->getFreeKnights(); } return out("A", target->getId(), knights); } string safe(Town* target){ int knights; if(thisTown->getPopulation() > target->getPopulation()) { knights = target->getFreeKnights() * -1; } else{ knights = thisTown->getFreeKnights(); } return out("S", target->getId(), knights); } string out(string order, int targedId, int knights) { stringstream tmp; tmp << order << " " << targedId << " " << knights; return tmp.str(); } vector <string> stringSplit(string input, string delimeter) { stringstream tmp(input); vector <string> splitted; string pushThis; while (getline(tmp, pushThis, delimeter.at(0))){ splitted.push_back(pushThis); } return splitted; } ``` compile with: `g++ -std=c++11 CalculatedFail.cpp -o CalculatedFail.exe` google says on linux it is CalculatedFail.out instead of the .exe, but i can't test it. and run `CalculatedFail.exe` as it uses a file to check for the def bonus, running the game simultaneously multiple times may lead to errors... hope it works properly without to much problems [Answer] # Java, Illuminati I read this and knew that I'd never be able to come up with a viable strategy, so I decided to play the woefully underrepresented lizard-people that may or may not rule us. Instead of fighting with the other bots, this one coerces them into cooperation, only to abandon them at the very end. This bot does not, in fact, leave any permanent damage. ``` import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.tools.JavaCompiler; import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; public class Illuminati { private static final String template = "import java.io.File;import java.util.Scanner;import java.io.IOException;\n" + "public class <<NAME>> \n" + "{public static void main(String[] args) throws IOException {if(args.length == 0) {\n" + "System.out.println(\"35 35 35\");} else { File ill_data = new File(\"Illuminati.txt\");\n" + "String order = new String();Scanner sc = new Scanner(ill_data);\n" + "while(sc.hasNextLine()){order = sc.nextLine();} sc.close(); int city = Integer.parseInt(order);" + "Illuminati.TurnDescriptor desc = new Illuminati.TurnDescriptor(args[0]);" + "int amt = desc.thistown.getFreeKnights(); System.out.println(\"S \" + city + \" \" + amt); }}}"; private static final File datafile = new File("Illuminati.txt"); private static final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); public static void main(String[] args) throws IOException { if(args.length == 0) { if(compiler != null) { if(!datafile.exists()) { datafile.createNewFile(); } File parentdir = datafile.getAbsoluteFile().getParentFile(); List<File> torecompile = new ArrayList<File>(); for(File f : parentdir.listFiles()) { if(!f.isDirectory()) { if(f.getName().endsWith(".class") && !f.getName().contains("$") && !f.getName().equals("Illuminati.class")) { torecompile.add(f); } } } for(File f : torecompile) { File newfile = new File(f.getName() + ".temp"); FileInputStream fis = new FileInputStream(f); FileOutputStream fos = new FileOutputStream(newfile); int val; while((val = fis.read()) != -1) { fos.write(val); } fis.close(); fos.close(); } List<File> tocompile = new ArrayList<File>(); for(File f : torecompile) { String classname = f.getName().substring(0, f.getName().length() - 6); String code = template.replace("<<NAME>>", classname); File temp = new File(classname + ".java"); FileOutputStream fos = new FileOutputStream(temp); fos.write(code.getBytes()); fos.close(); tocompile.add(temp); } StandardJavaFileManager manager = compiler.getStandardFileManager(null, null, null); compiler.getTask(null, manager, null, null, null, manager.getJavaFileObjectsFromFiles(tocompile)).call(); tocompile.forEach(file -> file.delete()); System.out.println("34 34 34"); } else { System.out.println("85 85 85"); } } else { if(datafile.exists()) { TurnDescriptor descriptor = new TurnDescriptor(args[0]); int knights = descriptor.thistown.getFreeKnights(); int stockpile = descriptor.towns.stream() .filter(town -> town.owner == descriptor.thistown.owner) .mapToInt(town -> town.id) .max().getAsInt(); PrintWriter pw = new PrintWriter(datafile); pw.println("" + stockpile); pw.close(); if(descriptor.thistown.id != stockpile) { System.out.println("S " + stockpile + " " + knights); } if(descriptor.round > 80 && (descriptor.round & 1) == 1) //If the round is greater than 80 and is odd { if(descriptor.thistown.id == stockpile) { Town target = descriptor.towns.stream() .filter(town -> town.owner != descriptor.playerid) .findAny().get(); System.out.println("A " + target.id + " " + descriptor.thistown.getFreeKnights()); } } if(descriptor.round == 99) //Resume normal AI practices { resetClassesFromCache(); } } else //Man, now we have to actually do stuff { System.out.println("W"); //Just kidding! Suicide! } } } private static void resetClassesFromCache() throws IOException { File parentdir = datafile.getAbsoluteFile().getParentFile(); for(File f : parentdir.listFiles()) { if(!f.isDirectory()) { if(f.getName().endsWith(".class.temp") && !f.getName().contains("$")) { FileInputStream fis = new FileInputStream(f); File out = new File(f.getName().substring(0, f.getName().length() - 5)); FileOutputStream fos = new FileOutputStream(out, false); int val; while((val = fis.read()) != -1) { fos.write(val); } fis.close(); fos.close(); f.delete(); } } } } public static class Town { public final int owner; public final int id; public final int knights; public final int lowborns; public Town(String chunk) { String[] vals = chunk.split("_"); owner = Integer.parseInt(vals[0]); id = Integer.parseInt(vals[1]); knights = Integer.parseInt(vals[2]); lowborns = Integer.parseInt(vals[3]); } public int getFreeKnights() { return knights - (lowborns/2) - 1; } } public static class TurnDescriptor { public final List<Town> towns; public final int round; public final int playerid; public final Town thistown; public TurnDescriptor(String s) { String[] info = s.split(";"); round = Integer.parseInt(info[0]); playerid = Integer.parseInt(info[1]); final int townid = Integer.parseInt(info[2]); towns = new ArrayList<Town>(); for(int i = 3; i < info.length; i++) { Town t = new Town(info[i]); towns.add(t); } thistown = towns.stream() .filter(town -> {return town.id == townid;}) .findFirst().get(); } } } ``` [Answer] # Java, SuperProducer It is late in my part of the world so I do not have enough time to elaborate on my submission. I will, plan to elaborate on how it works later on. The performance of the bot seems highly dependant on the starting order it wins some of the time... I did have some ideas to help increase the winning rounds... but rand out of time :P ``` package moogiesoft; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.IntSummaryStatistics; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class SuperProducer implements Serializable { private static final int MAX_POSSIBLE_LOWBORNS_IN_TOWN = 50; /** * */ private static final long serialVersionUID = 8652887937499233654L; public final String FILE = this.getClass().getSimpleName()+".txt"; int round; int playerID; int thisTownID; List<Town> towns; List<Town> myTowns; List<Town> otherTowns; Map<Integer, Conquest> townOwnerShipMap = new HashMap<Integer, Conquest>(); Town thisTown; private int targetOpponent = -1; // the id of the opponent that out towns will endevour to direct their attacks private int maxOpponentTownSize; // the number of knights of the opponent town with the most knights private int avgOpponentTownSize; // the average number of knights in an opponent town private int midAvgMaxOpponentTownSize; // value 1/2 between average and max knights in an opponent town public static void main(String[] args){ if (args.length == 0){ new SuperProducer().sendStartingKnights(); } else { new SuperProducer().letsDoIt(args[0].split(";")); } } private void sendStartingKnights() { // delete any stale state information File file = new File(FILE); file.delete(); System.out.println("100 100 0"); } private void letsDoIt(String[] args) { round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); thisTownID = Integer.parseInt(args[2]); towns = new ArrayList<>(); myTowns = new ArrayList<>(); otherTowns = new ArrayList<>(); for (int i = 3; i < args.length; i++) { towns.add(new Town(args[i])); } // load in stored state information File file = new File(FILE); if (file.exists()) { try { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file)); townOwnerShipMap = (Map<Integer, Conquest>) ois.readObject(); targetOpponent = ois.readInt(); ois.close(); } catch (Exception e) { e.printStackTrace(); } } for (Town town : towns) { // update town conquest map Conquest conquest = townOwnerShipMap.remove(town.getId()); if (conquest==null) { conquest = new Conquest(town.ownerId, -1); townOwnerShipMap.put(town.getId(),conquest); } else if (town.getOwner()!=conquest.getOwner()) { conquest.setOwner(town.ownerId); conquest.setConquestRound(round-1); } town.setDefenceBonus(round-conquest.getConquestRound()>2); if (town.isMine()){ myTowns.add(town); if (town.isThisTown()){ thisTown = town; } } else { otherTowns.add(town); } } String response = "W"; // this town has some knights to potentially command... if (thisTown.getKnightCount()>0) { // first round... consolidate into 1 super town if (round==1) { int thisTownIndex=myTowns.indexOf(thisTown); switch (thisTownIndex) { case 1: case 0: // if we are the first town then move all knights into second town if (myTowns.size()>1 && thisTown.getKnightCount()<200) { response = "S " + myTowns.get(thisTownIndex+1).getId() + " " + thisTown.getKnightCount(); break; } default: // the third town does nothing! } } else { // second round... go find some good starting towns to conquer if (round==2) { // this town is a town able to attack if (thisTown.getKnightCount()>100) { // If by some miracle we still own the town with no knights then re-inforce it. Town superTown = myTowns.stream().filter(a->a.getKnightCount()==200).findFirst().get(); if (superTown!=null && superTown.getId()!=thisTown.getId()) { response = "S " + superTown.getId() + " " + thisTown.getKnightCount(); } else { // find the next most productive Town... Town townToAttack = otherTowns.get(0); for (Town town : otherTowns) { if (town.getLowbornCount()>townToAttack.getLowbornCount()) { townToAttack=town; if (townToAttack.getOwner()!=playerID) { targetOpponent=townToAttack.getOwner(); } } } // the town to attack is most likely the own we lost due to having no knights to begin with... response = "A " + townToAttack.getId() + " " + thisTown.getKnightCount(); } } // else this is a conquered town so lets not do anything! } else if (round>97) { int attackForce = thisTown.getFreeKnights()/4; if (thisTown.getFreeKnights()>attackForce && attackForce>0) { boolean goFlag=false; Town townToAttack = null; for (Town town : towns) { // if (town==thisTown) goFlag=true; else if (goFlag && town.getOwner()!=thisTown.getOwner()) { if (town.getLowbornCount()==0) { townToAttack=town; break; } } } if (townToAttack==null) { for (Town town : otherTowns) { if (town.getLowbornCount()==0) { townToAttack=town; break; } } } if (round > 98 && townToAttack==null) { for (Town town : otherTowns) { attackForce = thisTown.getKnightCount()-town.getKnightCount()-town.getMinimumKnights()-1-thisTown.getMinimumKnights()-1; if (attackForce>0) { townToAttack=town; break; } } } if (townToAttack!=null) { response = "A " + townToAttack.getId() + " " + attackForce; } else { int thisTownIndex = myTowns.indexOf(thisTown); int supportSize = Math.min(thisTown.getKnightCount()/4, thisTown.getFreeKnights()); if (supportSize>thisTown.getMinimumKnights() && thisTownIndex<myTowns.size()-1) { Town townToSupport = myTowns.get(thisTownIndex+1); response = "S " + townToSupport.getId() + " " + (thisTown.getKnightCount()-thisTown.getKnightCount()/4); } } } } // we are on non-beginning non-ending round... else { // calculate statistics IntSummaryStatistics statistics = otherTowns.stream().collect(Collectors.summarizingInt(Town::getKnightCount)); maxOpponentTownSize = statistics.getMax(); avgOpponentTownSize = (int) statistics.getAverage(); midAvgMaxOpponentTownSize = (maxOpponentTownSize+avgOpponentTownSize)/2; if ((round-1)%3==1) { // find the next strongest town of our target Opponent that produces knights... Town townToAttack = null; for (Town town : otherTowns) { if (town.getLowbornCount() > 0 && town.getOwner() == targetOpponent && (townToAttack == null || town.getKnightCount()>townToAttack.getKnightCount())) { townToAttack=town; } } // target opponent cannot grow so choose another opponent... // favour the weakest opponent that has has some towns that produces towns.. // otherwise favour the weakest opponent if (townToAttack==null) { townToAttack=chooseNewOpponentToAttack(); } targetOpponent=townToAttack.getOwner(); int minKnightsToLeaveAtThisTown = calculateDesiredKnightsAtTown(thisTown); int minKnightsToLeftAtAttackedTownAfterBattle = calculateDesiredKnightsAtTown(townToAttack); double defenceBonus = townToAttack.hasDefenceBonus()?1.2:1; double defenderAttackStrength = townToAttack.getKnightCount() * defenceBonus; int knightsNeededToWinAndEnsureNotAttackedNextRound = minKnightsToLeftAtAttackedTownAfterBattle + (int) (defenderAttackStrength); knightsNeededToWinAndEnsureNotAttackedNextRound = knightsNeededToWinAndEnsureNotAttackedNextRound + ((knightsNeededToWinAndEnsureNotAttackedNextRound-defenderAttackStrength - townToAttack.getMinimumKnights() < 0) ?townToAttack.getMinimumKnights():0); int knightsLeftAtSortieingTownAfterAttacking = thisTown.getKnightCount()-knightsNeededToWinAndEnsureNotAttackedNextRound; // if the sortieing town is sufficiently safe from another attack after it attempts to attack the other town will it try to attack if (knightsLeftAtSortieingTownAfterAttacking > thisTown.getMinimumKnights()*2 && knightsLeftAtSortieingTownAfterAttacking>minKnightsToLeaveAtThisTown && thisTown.getFreeKnights()>knightsNeededToWinAndEnsureNotAttackedNextRound) { response = "A " + townToAttack.getId() + " " + knightsNeededToWinAndEnsureNotAttackedNextRound; } // not safe... so lets support our other towns else { int surplusKnights = thisTown.getKnightCount()-minKnightsToLeaveAtThisTown; // this town has surplusKnights if (surplusKnights>0) { int knightsAvailable = Math.min(surplusKnights, thisTown.getFreeKnights()); // find our weakest and strongest towns Town myWeakestTown=null; Town myStrongestTown=null; for (Town town : myTowns) { if (!(town.getKnightCount()==0 && round<50) && (myWeakestTown == null || town.getKnightCount()<myWeakestTown.getKnightCount())) { myWeakestTown=town; } if (!(town.getKnightCount()==0 && round<50) && ( myStrongestTown == null || town.getKnightCount()>myStrongestTown.getKnightCount())) { myStrongestTown=town; } } // see if my Weakest Town needs support Town townToSupport = null; int knightsToSend=0; if (thisTown!=myWeakestTown) { int desiredKnightsAtTown = calculateDesiredKnightsAtTown(myWeakestTown); if (myWeakestTown.getKnightCount()<desiredKnightsAtTown) { int deltaDesiredKnights = desiredKnightsAtTown-myWeakestTown.getKnightCount(); knightsToSend = Math.min(knightsAvailable, deltaDesiredKnights); townToSupport=myWeakestTown; } } // no towns needed support so we will attempt to support the strongest town if (townToSupport == null) { if (thisTown!=myStrongestTown) { int desiredKnightsAtTown = calculateDesiredKnightsAtTown(myStrongestTown); if (myStrongestTown.getKnightCount()<desiredKnightsAtTown) { int deltaDesiredKnights = desiredKnightsAtTown-myStrongestTown.getKnightCount(); knightsToSend = Math.min(knightsAvailable, deltaDesiredKnights); knightsToSend = knightsAvailable; townToSupport=myStrongestTown; } } } // support the chosen town if possible if (townToSupport != null) { response = "S " + townToSupport.getId() + " " + knightsToSend; } } } } } } } // save state information try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file)); oos.writeObject(townOwnerShipMap); oos.writeInt(targetOpponent); oos.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println(response); } // returns a town of the opponent that is deemed to be the most worthy private final Town chooseNewOpponentToAttack() { Town townToAttack=null; // calculate opponent sizes HashMap<Integer,Opponent> opponentMap = new HashMap<Integer, Opponent>(); for (Town town : otherTowns) { Opponent opponent = opponentMap.get(town.getOwner()); if (opponent == null) { opponent = new Opponent(town.getOwner()); opponentMap.put(town.getOwner(), opponent); } opponent.addTown(town); } // create sorted list of opponents based on strength. List<Integer> opponentsByStrength = new ArrayList<Integer>(opponentMap.keySet()); opponentsByStrength.sort(new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { Opponent left = opponentMap.get(o1); Opponent right = opponentMap.get(o2); return left.getTotalKnights()-right.getTotalKnights(); } }); // attempt to choose the weakest opponent's weakest town that has some ability to generate knights... out: for (Integer opponent : opponentsByStrength) { for (Town town : opponentMap.get(opponent).getTowns()) { if (town.getOwner() !=-1 && town.getLowbornCount() > 0 && (townToAttack == null || town.getKnightCount()<townToAttack.getKnightCount())) { townToAttack=town; break out; } } } // no opponents left with knights producing towns... just go for the weakest town. if (townToAttack == null) { for (Town town : otherTowns) { if (townToAttack == null || town.getKnightCount()<townToAttack.getKnightCount()) { townToAttack=town; } } } return townToAttack; } // returns the number of knights that should make this town safe from attack final private int calculateDesiredKnightsAtTown(Town town) { int minimumKnightsWeWantInATown = avgOpponentTownSize; return minimumKnightsWeWantInATown + town.getLowbornCount()==0?0:(minimumKnightsWeWantInATown +(int) (((double) town.getLowbornCount() / MAX_POSSIBLE_LOWBORNS_IN_TOWN) * (midAvgMaxOpponentTownSize-minimumKnightsWeWantInATown))); } /** represents a conquest of a Town by a player */ class Conquest implements Serializable { private static final long serialVersionUID = -1120109012356785962L; private int owner; private int conquestRound; public int getOwner() { return owner; } public void setOwner(int owner) { this.owner = owner; } public int getConquestRound() { return conquestRound; } public void setConquestRound(int conquestRound) { this.conquestRound = conquestRound; } public Conquest(int owner, int conquestRound) { super(); this.owner = owner; this.conquestRound = conquestRound; } } /** represents an opponent in the simulation */ private class Opponent implements Serializable { private int ownerId; private int totalKnights; private List<Town> towns = new ArrayList<SuperProducer.Town>(); public void addTown(Town town) { totalKnights+=town.getKnightCount(); towns.add(town); } public int getOwnerId() { return ownerId; } public int getTotalKnights() { return totalKnights; } public List<Town> getTowns() { return towns; } public Opponent(int ownerId) { super(); this.ownerId = ownerId; } } /** represents a Town in the simulation */ private class Town implements Serializable { private static final long serialVersionUID = 5011668142883502165L; private final int ownerId; private final int id; private final int knights; private final int lowborns; private boolean defenceFlag =true; public Town(String string){ String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); id = Integer.parseInt(args[1]); knights = Integer.parseInt(args[2]); lowborns = Integer.parseInt(args[3]); } public boolean hasDefenceBonus() { return defenceFlag; } public void setDefenceBonus(boolean defenceFlag) { this.defenceFlag = defenceFlag; } public int getId() { return id; } public int getOwner() { return ownerId; } public int getKnightCount() { return knights; } public int getLowbornCount() { return lowborns; } public boolean isMine(){ return ownerId == playerID; } public boolean isThisTown(){ return id == thisTownID; } private int getFreeKnights() { return knights - lowborns / 2 - 1; } private int getMinimumKnights() { return lowborns / 2 + 1; } } } ``` Compile: javac SuperProducer.java Run: java moogiesoft.SuperProducer [Answer] # C++11, attackOn3 code itself didn't get much prettier, but now i use another way to target, will possibly add comments to the code later. seems to do okay with the bots i am running, although it still is hard vs frankenstein and liberator and can't win consistently. ``` #include <iostream> #include <string> #include <vector> #include <sstream> #include <cmath> #include <ratio> #include <fstream> #include <algorithm> using namespace std; class Town { public: Town(int owner, int townId, int knights, int population, int roundToDefBonus); int getOwner(); int getId(); int getKnights(); int getPopulation(); int getFreeKnights(); int neededConquer(); int needRevolt(); int getRoundToDef(); bool operator<(const Town &other) const { return townId < other.townId; } private: int owner; int townId; int knights; int population; int roundToDefBonus; double defBonus; }; Town::Town(int inOwner, int inTownId, int inKnights, int inPopulation, int inRoundToDefBonus) { owner = inOwner; townId = inTownId; knights = inKnights; population = inPopulation; roundToDefBonus = inRoundToDefBonus; if (roundToDefBonus > 0) { defBonus = 1; } else { defBonus = 1.2; } } int Town::getOwner() { return owner; } int Town::getId() { return townId; } int Town::getKnights() { return knights; } int Town::getPopulation() { return population; } int Town::getFreeKnights() { return knights - population / 2; } int Town::neededConquer() { return max(static_cast<int>(ceil(knights * defBonus + population / 2)), 1); } int Town::needRevolt() { return knights * defBonus - population / 2; } int Town::getRoundToDef() { return roundToDefBonus; } #define maxRounds 100 #define newKnights 3 const int attackround = newKnights - 1; const int getEmptyTowns = maxRounds - 5; int gameRound; int myId; int thisTownId; Town *thisTown; vector<Town> myTowns; vector<Town> enemyTowns; vector<Town> lastTime; string turn(); Town *bestGainTarget(int knights); Town *bestSafe(int knights); Town *biggestTarget(int knights); Town *biggestSafe(int knights); Town *weakTarget(int knights); string out(string, int, int); string attack(Town *); string safe(Town *); bool sortTowns(const Town &t1, const Town &t2); vector<string> stringSplit(string input, string delimeter); int getBiggestEnemyId(); int main(int argc, char *argv[]) { if (argc < 2) { cout << "100 100 100"; ofstream myFile; myFile.open("attackOn3.txt"); myFile << "0\n"; myFile.close(); } else { if (argc == 2) { string input = argv[1]; vector<string> params = stringSplit(input, ";"); gameRound = atoi(params.at(0).c_str()); myId = atoi((params.at(1)).c_str()); thisTownId = atoi(params.at(2).c_str()); ifstream myfile("attackOn3.txt"); if (myfile.is_open()) { string line; getline(myfile, line); bool newRound = false; if (atoi(line.c_str()) > gameRound) { newRound = true; } vector<string> oldVals; if (!newRound) { while (getline(myfile, line)) { oldVals = stringSplit(line, "_"); int playerId = atoi(oldVals.at(0).c_str()); int townId = atoi(oldVals.at(1).c_str()); int knights = atoi(oldVals.at(2).c_str()); int population = atoi(oldVals.at(3).c_str()); int roundToDefBonus = atoi(oldVals.at(4).c_str()); lastTime.push_back(Town(playerId, townId, knights, population, roundToDefBonus)); oldVals.clear(); } } else { while (getline(myfile, line)) { oldVals = stringSplit(line, "_"); int playerId = atoi(oldVals.at(0).c_str()); int townId = atoi(oldVals.at(1).c_str()); int knights = atoi(oldVals.at(2).c_str()); int population = atoi(oldVals.at(3).c_str()); int roundToDefBonus = atoi(oldVals.at(4).c_str()); if (roundToDefBonus) { //if round def bonus > 0, decrement because new round roundToDefBonus--; } lastTime.push_back(Town(playerId, townId, knights, population, roundToDefBonus)); oldVals.clear(); } } std::sort(lastTime.begin(), lastTime.end()); } if (lastTime.size() > 0) { vector<string> values; for (int i = 3; i < params.size(); i++) { values = stringSplit(params.at(i), "_"); int playerId = atoi(values.at(0).c_str()); int townId = atoi(values.at(1).c_str()); int knights = atoi(values.at(2).c_str()); int population = atoi(values.at(3).c_str()); int roundsToDef = lastTime.at(townId).getRoundToDef(); if (playerId != lastTime.at(townId).getOwner()) { roundsToDef = 2; } if (playerId == myId) { if (thisTownId != townId) myTowns.push_back(Town(playerId, townId, knights, population, roundsToDef)); else { thisTown = new Town(playerId, townId, knights, population, roundsToDef); } } else { enemyTowns.push_back(Town(playerId, townId, knights, population, roundsToDef)); } values.clear(); } } else { vector<string> values; for (int i = 3; i < params.size(); i++) { values = stringSplit(params.at(i), "_"); int playerId = atoi(values.at(0).c_str()); int townId = atoi(values.at(1).c_str()); int knights = atoi(values.at(2).c_str()); int population = atoi(values.at(3).c_str()); if (playerId == myId) { if (thisTownId != townId) myTowns.push_back(Town(playerId, townId, knights, population, 0)); else { thisTown = new Town(playerId, townId, knights, population, 0); } } else { enemyTowns.push_back(Town(playerId, townId, knights, population, 0)); } values.clear(); } } string tmp = turn(); cout << tmp; ofstream writeFile("attackOn3.txt"); if (writeFile.is_open()) { writeFile << gameRound << "\n"; writeFile << thisTown->getOwner() << "_" << thisTown->getId() << "_" << thisTown->getKnights() << "_" << thisTown->getPopulation() << "_" << thisTown->getRoundToDef() << "\n"; for (vector<Town>::size_type i = 0; i != myTowns.size(); i++) { writeFile << myTowns[i].getOwner() << "_" << myTowns[i].getId() << "_" << myTowns[i].getKnights() << "_" << myTowns[i].getPopulation() << "_" << myTowns[i].getRoundToDef() << "\n"; } for (vector<Town>::size_type i = 0; i != enemyTowns.size(); i++) { writeFile << enemyTowns[i].getOwner() << "_" << enemyTowns[i].getId() << "_" << enemyTowns[i].getKnights() << "_" << enemyTowns[i].getPopulation() << "_" << enemyTowns[i].getRoundToDef() << "\n"; } } } else { cout << "error, wrong parameter"; } } delete thisTown; return 0; } string turn() { Town *safeTarget; Town *attackTarget; if (thisTown->getFreeKnights() < 0) { //evacuate safeTarget = biggestSafe(thisTown->getKnights()); attackTarget = biggestTarget(thisTown->getKnights()); if (safeTarget != nullptr && attackTarget != nullptr) { if (safeTarget->getPopulation() > attackTarget->getPopulation()) { return out("S", safeTarget->getId(), thisTown->getKnights()); } else { return out("A", attackTarget->getId(), thisTown->getKnights()); } } if (safeTarget) { return out("S", safeTarget->getId(), thisTown->getKnights()); } if (attackTarget) { return out("A", attackTarget->getId(), thisTown->getKnights()); } Town *target = &myTowns.at(0); for (vector<Town>::size_type i = 1; i != myTowns.size(); i++) { if (target->getPopulation() < myTowns[i].getPopulation()) target = &myTowns[i]; } return out("S", target->getId(), thisTown->getKnights()); } safeTarget = biggestSafe(thisTown->getFreeKnights()); if (gameRound % newKnights == attackround) { //knights only get produced every 3 town, i want to conquer the best towns just before that so i get more reinforments and dont need to fight quite that much attackTarget = bestGainTarget(thisTown->getFreeKnights()); } else { //but if a town is easy to aquiere i still want it, e. g. because of revolution or someone weakened it so that it will revolte attackTarget = weakTarget(thisTown->getFreeKnights()); } if (safeTarget != nullptr && attackTarget != nullptr) { if (safeTarget->getPopulation() > attackTarget->getPopulation()) { return safe(safeTarget); } else { return attack(attackTarget); } } if (safeTarget) { return safe(safeTarget); } if (attackTarget) { return attack(attackTarget); } if (gameRound > getEmptyTowns) { //empty towns dont matter early on but still count to win score for (vector<Town>::size_type i = 0; i != enemyTowns.size(); i++) { if (enemyTowns[i].getPopulation() < 2) { if (enemyTowns[i].neededConquer() < thisTown->getFreeKnights()) { return attack(&enemyTowns[i]); } } } } int biggestEnemy = getBiggestEnemyId(); //if last round attack possible biggest other guy if (gameRound == maxRounds) { int targetKnights = -1; Town *target; for (vector<Town>::size_type i = 0; i != enemyTowns.size(); i++) { if (enemyTowns[i].getOwner() == biggestEnemy) { if (enemyTowns[i].neededConquer() < thisTown->getFreeKnights()) { if (enemyTowns[i].getFreeKnights() > targetKnights) { target = &enemyTowns[i]; targetKnights = target->getFreeKnights(); } } } } if (targetKnights > -1) { attack(target); } } //revolt from biggest other guy if (gameRound > 10) { //most bots need a bit of time int targetPop = 0; Town *target; for (vector<Town>::size_type i = 0; i != enemyTowns.size(); i++) { if (enemyTowns[i].getOwner() == biggestEnemy) { if (enemyTowns[i].needRevolt() < thisTown->getFreeKnights()) { if (enemyTowns[i].getPopulation() > targetPop) { target = &enemyTowns[i]; targetPop = target->getPopulation(); } } } } if (targetPop != 0) { return attack(target); } } return "W"; } Town *bestGainTarget(int knights) { Town *target = nullptr; int gain = -thisTown->getFreeKnights(); int now = -thisTown->getFreeKnights(); //int loses = thisTown->getFreeKnights(); for (vector<Town>::size_type i = 0; i != enemyTowns.size(); i++) { int conquer = enemyTowns[i].neededConquer(); if (conquer < knights && enemyTowns[i].getPopulation() > 0) { if (enemyTowns[i].getPopulation() * 2 *1.2 - conquer > gain) { if(enemyTowns[i].getPopulation() - conquer > now){ target = &enemyTowns[i]; now = target->getPopulation() - conquer; gain = target->getPopulation() * 2 - conquer; } } } } return target; } Town *weakTarget(int knights) { //maybe change it that it prefers targets with 0/40 over 24/50 Town *target = nullptr; double population = 1; for (vector<Town>::size_type i = 0; i != enemyTowns.size(); i++) { if (enemyTowns[i].neededConquer() < knights) { if (enemyTowns[i].getKnights() < enemyTowns[i].getPopulation() / 2) { if (enemyTowns[i].getPopulation() > population) { target = &enemyTowns[i]; population = target->getPopulation(); } } } } return target; } Town *biggestTarget(int knights) { Town *target = nullptr; int population = -1; for (vector<Town>::size_type i = 0; i != enemyTowns.size(); i++) { if (enemyTowns[i].neededConquer() < knights) { if (enemyTowns[i].getPopulation() > population) { target = &enemyTowns[i]; population = target->getPopulation(); } } } return target; } Town *biggestSafe(int knights) { Town *target = nullptr; int population = -1; for (vector<Town>::size_type i = 0; i != myTowns.size(); i++) { if (myTowns[i].getFreeKnights() < 0 && myTowns[i].getFreeKnights() + knights >= 0) { if (myTowns[i].getPopulation() > population) { target = &myTowns[i]; population = target->getPopulation(); } } } return target; } int getBiggestEnemyId() { int players[enemyTowns.size() / 3 + 1]; for (vector<Town>::size_type i = 0; i != enemyTowns.size(); i++) { if (enemyTowns[i].getOwner() != -1) { players[enemyTowns[i].getOwner()] = enemyTowns[i].getPopulation(); } } int max = 0; for (int i = 1; i < enemyTowns.size() / 3 + 1; i++) { if (players[i] > players[max]) { max = i; } } } string attack(Town *target) { int knights; if (thisTown->getPopulation() > target->getPopulation()) { knights = target->neededConquer(); } else { knights = thisTown->getFreeKnights(); } return out("A", target->getId(), knights); } string safe(Town *target) { int knights; if (thisTown->getPopulation() > target->getPopulation()) { knights = target->getFreeKnights() * -1; } else { knights = thisTown->getFreeKnights(); } return out("S", target->getId(), knights); } string out(string order, int targedId, int knights) { stringstream tmp; tmp << order << " " << targedId << " " << knights; return tmp.str(); } vector<string> stringSplit(string input, string delimeter) { stringstream tmp(input); vector<string> splitted; string pushThis; while (getline(tmp, pushThis, delimeter.at(0))) { splitted.push_back(pushThis); } return splitted; } ``` compile with: `g++ -std=c++11 attackOn3.cpp -o attackOn3.exe` and run `attackOn3.exe` ]
[Question] [ Given any string, print it in the form of a triangle where the text runs up and down along each diagonal. For example, an input of `"Hello World"` should output: ``` d l r d o l W r d o l o W r d l o l l o W r d e l o l H l o W r d e l o l l o W r d l o l o W r d o l W r d o l r d l d ``` The space between each character in a row must be at least 1, in order to maintain the proper format. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~10~~ 7 bytes ``` ↗ELθ✂θι~~UE¹~~ ``` ~~[Try it online!](https://tio.run/##BcGxCoAgEADQ3a9wvAMbWmsOGgqiiGYxyYNDzST6@@s9F2xxybLIUihW6Pa80hWq0bPNMPl41QA3Gr0xOQ@30YSIvRq@6uMJLfYio2dO@kiFTyXNK83DPw "Charcoal – Try It Online")~~ [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMqtCAoMz2jREfBN7FAwyc1L70kQ6NQU0chOCczOVWjUEchU1NT0/r/f4/UnJx8hfD8opwUrv@6Zf91i3MA "Charcoal – Try It Online") Links are to verbose version of code. Explanation: ``` ↗ Print up and to the right ELθ✂θι All suffixes of the input, as a list down and to the right ~~UE¹~~ ~~Insert blank columns~~ ``` ~~First time I got to use the `UE` command.~~ [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ ~~8~~ 7 bytes Thanks to *Emigna* for saving 2 bytes! ``` ðâƶ.cðζ ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f//8IbDi45t00s@vOHctv//PVJzcvIVwvOLclIA "05AB1E – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 75 bytes ``` s=input() k=l=len(s) while k>1-l:k-=1;m=abs(k);print' '*m+' '.join(s[m::2]) ``` [Try it online!](https://tio.run/##Dcu7CoAgFADQva@wSe0FNRq3uX@IhiIh8/pAjejrreVsx7/pdHbIOYKy/k6MFxoQUFoWefGcCiXRU9@i0C30o4Ftj0zz0QdlEyW0MvVvdzn1h8UIMaw8ZzpLRNeQxwU8SvoB "Python 2 – Try It Online") Ruud saved 3 bytes. [Answer] # C, ~~86~~ ~~78~~ ~~73~~ 70 chars ``` for(int i=1,j=1-n;i=putchar(j*j<i*i&i-j?s[i-1]?:13:32)^13?i+1:++j<n;); ``` [Try it online!](https://tio.run/##PczLDoIwEIXhPU8xiYkBsYaCKy6y9Q1cEExIuU1Tp4ZCXBBeXWw37ibfnPyCCdXQsB@QhFraDiA3c4v6Mt68v1makAZnSDO8GiQ/WD0AMTYTmIpH8bWGAtZoy6wO3Wx8E7jTzcl@bEB15HDv9eQ7xoKfZcEZZVi8l9mlfHmSOZ7wiEyWpkLG6zLlSZrEwZMnJYY8DUOZU2Yz237vlNLw0JNqv6JXzWB29vkB "C (clang) – Try It Online") ### Explanation Naive implementation: two cycles, fill from top to bottom, left to right (99 bytes): ``` for(int j=1;j<n*2;j++){for(int i=0;i<n;i++)printf("%c ",(i+j)%2&&i+1>=abs(j-n)?s[i]:' ');puts("");} ``` Here, puts() just prints \n to the output. Let’s combine variable declarations and combine j++ with something (94 bytes): ``` for(int i,j=0;++j<n*2;){for(i=0;i<n;i++)printf("%c ",(i+j)%2&&i>=abs(j-n)?s[i]:' ');puts("");} ``` Good. Variable j has a range 0...2n; let it be within -n...n, this makes the math simpler. Notice that boolean expression at the right of && always has the value 0 or 1. This means we can replace && with &. 91 byte: ``` for(int i,j=-n;++j<n;){for(i=0;i<n;i++)printf("%c ",~(i+j)%2&i>=abs(j)?s[i]:' ');puts("");} ``` And now we realized we printing an extra space. And yeah, we don’t need printf() to print just a single symbol. 86 bytes: ``` for(int i,j=-n;++j<n;){for(i=0;i<n;i++)putchar(~(i+j)%2&i>=abs(j)?s[i]:' ');puts("");} ``` Even better. Notice that condition i \* i>=j \* j is same as i>=abs(j), but shorter. Let’s move puts() into for loop increment expression. And guess what? Actually, we don’t need the braces around i+j. 78 bytes: ``` for(int i,j=-n;++j<n;puts(""))for(i=0;i<n;i++)putchar(i*i>=j*j&~i+j?s[i]:' '); ``` Did you know that putchar() returns the character it has printed? Let’s use XOR to test numbers for equivalence. Let’s replace space with its ASCII code, 32. Remember that end-of-line character code is 13. And finally: did you know that GCC/Clang do support <https://en.wikipedia.org/wiki/Elvis_operator> ? 73 bytes: ``` for(int i,j=-n;++j<n;)for(i=0;putchar(i*i>=j*j&~i+j?s[i]?:13:32)^13;i++); ``` Finally, guess what? We don’t need two for loops. We can replace ugly ~i+j with just i-j. 70 bytes: ``` for(int i=1,j=1-n;i=putchar(j*j<i*i&i-j?s[i-1]?:13:32)^13?i+1:++j<n;); ``` Future work: change loop direction? This might save some bytes, if done properly. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~13~~ ~~10~~ 9 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ēI*@∑}¹╚H ``` This uses a feature that I [just added](https://github.com/dzaima/SOGLOnline/commit/73fcff638b63b47cb3c7d727daa710a0e7c5abef), but was [documented](https://github.com/dzaima/SOGL/blob/ad1a893f24b6198074b4767e11ddc2a99ee3b807/P5ParserV0_12/data/charDefs.txt#L424) a while ago. [Try it here!](https://dzaima.github.io/SOGLOnline/?code=JTJDJTdCJXUwMTEzSSpAJXUyMjExJTdEJUI5JXUyNTVBSA__,inputs=SGVsbG8lMjBXb3JsZA__) In that link `,` is added because this expects the input on the stack and `{` added because otherwise `,` would get executed every time in the loop ``` implicitly start loop over POP ē increase the variable E, on first push which will be 0 I increase by 1 * multiply the current character that many times @∑ join with spaces } end loop ¹ wrap everything on stack in an array ╚ center vertically H rotate counter-clockwise ``` [Answer] # [Haskell](https://www.haskell.org/), 73 bytes ``` f s|l<-length s-1=[zipWith min s$(' '<$[1..abs x])++cycle"~ "|x<-[-l..l]] ``` [Try it online!](https://tio.run/##Dc2xCoMwGEXhvU9xCQFbJAH3uHfv4BAypBpr6G8iJoIt0ldPHQ98cCab3o6olBHpICXIhVeekETT6q9fOn/G7AMSv1aoFNeNlPaZsJtbXfefnhz7gR27ElqQlGRMme3pWwzxAixbfuQVElsgH1wCxwh2P48RXVxpYOUP "Haskell – Try It Online") [Answer] # [Gaia](https://github.com/splcurran/Gaia), 16 bytes ``` $:ċ⟪×$§×⟫†€|$¦tụ ``` [Try it online!](https://tio.run/##ATIAzf9nYWlh//8kOsSL4p@qw5ckwqfDl@Kfq@KAoOKCrHwkwqZ04bul//9IZWxsbyBXb3JsZA "Gaia – Try It Online") ### Explanation ``` $ Split into list of chars :ċ Push [1 .. len(input)] ⟪×$§×⟫† Apply this block to corresponding elements of the two lists: × Repetition $ Split into chars §× Join with spaces €| Centre align the rows $¦ Split each line into chars t Transpose ụ Join each row with spaces, then join the rows together with newlines ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~86~~ 83 bytes -3 thanks to officialaimm ``` lambda s,j=' '.join:map(j,zip(*(j(c*-~i).center(len(s)*2)for i,c in enumerate(s)))) ``` [Try it online!](https://tio.run/##JYwxDgIhEAC/sh0LwSuuNLneH9hcg9wSl8BCOCy08OtI4rQzmfruzyLrCNs@ksuPw8Fp46ZALbGwXLOrGO2HKxqM6M3ly3rxJJ0aJhI8tVl1KA3YemABklem5jpNMxm1sXRQu/x/GFDdKKUC99LSoWbxAw "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` ;€⁶ṁ"JUz⁶ZUŒBZG ``` [Try it online!](https://tio.run/##y0rNyan8/9/6UdOaR43bHu5sVPIKrQKyokKPTnKKcv///78HUEW@Qnh@UU4KAA "Jelly – Try It Online") [Answer] # Octave, ~~59~~ ~~63~~ ~~58~~ 57 bytes ``` @(s,a=@strjust)a([kron(+a(hankel(s)),[1 0;0 0]) '']',99)' ``` [Try it online!](https://tio.run/##BcGxCoAgEADQXxEX78jBRomgsT9oEIejhEhR8Kzfv95r56AviWzAltaNR39eHkgQcm8VJoKbak4FGNGGWbnFKRdRGRON9R6NUGXQeyqlqaP1cmmUHw "Octave – Try It Online") [Answer] ## Java, 292 bytes (sorry) ``` public class D{ public static void main(String[]r){ String s=r[0];int L=s.length(),n=L*2-1,x=L-1,d=-1,i,j;boolean a=false,o=L%2==1; for(i=0;i<n;i++){ for(j=0;j<L;j++)System.out.print(j<x||a&&j%2==(o?0:1)||!a&&j%2==(o?1:0)?' ':s.charAt(j)); System.out.println(); x+=d;if(x<0){x=0;d=1;}a=!a;}}} ``` [Answer] # [Haskell](https://www.haskell.org/), 81 bytes ``` f s|l<-length s=[[last$' ':[s!!i|i>=n,mod(n+i)2<1]|i<-[0..l-1]]|n<-abs<$>[-l..l]] ``` [Try it online!](https://tio.run/##Dc2xDsIgEADQX7k2JNUoxDoa6Ozu4EAYMKWW9HqYHt34d@z6ljd7XgJirRNwQS0x0DfPwMZa9JxFB93DctPEEgdD1zWNJ7rE8133rkQt7U0plL1zhbT0H9ZisBIPc66uPhIY@O35lTdQsBNGCgwCJmifR5rgnTYc2/oH "Haskell – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 116 bytes ``` s->{for(int l=s.length(),i=-l;++i<l;)System.out.printf("%"+l+"s%n",s.substring(i<0?-i:i).replaceAll("(.).","$1 "));} ``` [Try it online!](https://tio.run/##dY69asMwFIX3PMVFNCBhW7RrbaeULl06ZehQOii27Fz3WjLSVaAEP7trnNKt04Hz83EGczGFn6wb2q9lSifCBhoyMcKbQQfXHcCvG9nwKhePLYxrJo8c0PUfn2BCH9VWBRhWnk6MpLvkGkbv9It3MY02VLfBAVrL3hn2AeolFodr54NEx0B11GRdz2epcqwLKrMMKyrV8TuyHbVPrKcVwZ0Ue5FRJuLeiTzqmE5xY0us7p8KfESlg53INPaZSAqplRa5uHsAoVQ5L@V29e@GNk1jJ5biFc8o1L@pJfLw7gO1t9K8m5cf "Java (OpenJDK 8) – Try It Online") ## Explanation ``` s->{ // Consumer<String> lambda for(int l=s.length(),i=-l;++i<l;) // For each length between l and 1 and back to l, System.out.printf("%"+l+"s%n", // Print with align to right s.substring(i<0?-i:i) // skip the first |i| characters .replaceAll("(.).","$1 ") // replace every even-positioned character with a space. ); } ``` [Answer] # C++, 135 bytes Okay, here's my shot with C++: ``` auto f=[&](auto f,int y)->void{ for(int i{};i<n;i++) putchar(y<0?f(f,y+1?i+1:n-1-i),'\n':i<y||i+y&1?' ':s[i]); }; f(f,-1); f(f,-2); ``` [Try It Online (ideone)!](https://ideone.com/VhsZpN) [Answer] # [Haskell](https://www.haskell.org/), ~~140~~ 137 bytes ``` (m#n)s=(\(i,x)->' ':(last$" ":[x:" "|rem i 2==m&&i>n]))=<<zip[0..]s g s=((++)=<<reverse.tail)$id=<<[[(0#n)s,(1#n)s]|n<-[-1,1..length s]] ``` [Try it online!](https://tio.run/##FY6xDoIwFEVn@YqXSqQN0IgjocwOOjk41A5NaKCxLaSthhj@HWE6yRnOvYMMb2XMumJ7dCQw/MK6mEnZZpDV2MgQUwSAaj7XCNDilQUNF8bs6aRbJwhhTfPTEz9TKkLSw1bAeb5br77KB0Wj1IakutsU5/i8rxS42iEW15S8rIqKUqNcHwcIQqxWagcMuhGSg5XTHaZPfER/c5BCD@i63R3hOXrTofUP "Haskell – Try It Online") *Saved 3 bytes thanls to Challenger5* I don't think that's optimal... `f` produces one of the lines (`m` = 0 or 1 is the modulo of the line number, `n` is the number of the line) `g` intercalates "odd" and "even" lines, and add to the result a mirror of itself. [Answer] # [Pyth](https://pyth.readthedocs.io), 25 bytes ``` j+_Km++*d;@Qdtj;%2>QdUQtK ``` [Try it here.](https://pyth.herokuapp.com/?code=j%2B_Km%2B%2B%2ad%3B%40Qdtj%3B%252%3EQdUQtK&input=%22Hello+World%22&debug=0) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` JrLm€2Ṭ;€0a⁸o⁶ṚŒḄG ``` [Try it online!](https://tio.run/##y0rNyan8/9@ryCf3UdMao4c711gDaYPER4078h81bnu4c9bRSQ93tLj///9fyQOoNl8hPL8oJ0UJAA "Jelly – Try It Online") [Answer] ## Mathematica 105 Bytes ``` (c=Characters@#;l=Length@c;StringRiffle@Table[If[Abs[j-l]<i&&EvenQ[j+i],c[[i]]," "],{j,1,2l+1},{i,1,l}])& ``` Maybe I could shave off another byte or two, but the character count overhead of dealing with strings in Mathematica makes simple challenges like this uncompetitive. [Answer] # J, 54 bytes ``` [:|:|.@i.@#(>@],~' '#~[)"_1[:(,' '&,)/&.>>:@i.@#<@#"0] ``` [Try it online!](https://tio.run/##y/r/P03BVk8h2qrGqkbPIVPPQVnDziFWp05dQV25LlpTKd4w2kpDB8hT09HUV9Ozs7MCK7JxUFYyiOXiSk3OyFdIU1D3SM3JyVcIzy/KSVH//x8A) (note that the output on TIO has a newline and three spaces, but that isn't from the function call -- it's probably just what the J interpreter does automatically). I think the general idea for solving this is right, but there are small things that I'm probably doing sub-optimally that are adding to the bytecount. ### Previous variants 55 bytes ``` <:@+:@#{.[:|:|.@i.@#(],~' '#~[)"_1>:@i.@#(,' '&,)/@#"0] ``` 56 bytes ``` <:@+:@#{.[:|:|.@i.@#(],~' '#~[)"_1#{.[:(,' '&,)//.[:]\.] ``` # Explanation This will be split into a few functions. Also, I wasn't as thorough with latter parts of the explanation, so let me know if you want a better explanation for a certain part and I can edit that in. ``` dup =. >:@i.@# <@#"0 ] space =. (,' '&,)/&.> pad =. |.@i.@# (>@],~' '#~[)"_1 ] trans =. |: ``` * `dup` duplicates each character as many times as its index (plus one) in the string * `space` inserts spaces between each character * `pad` pads the characters with the right amount of spaces * `trans` transposes the resulting matrix Sample call: ``` trans pad space dup 'abc' c b a c b c ``` ### Dup ``` >:@i.@# <@#"0 ] >:@i.@# Indices of each character plus one # Length of the string i. Range [0,length) >: Add one <@#"0 ] Duplicate each character as many times as it index (plus one) "0 For each # ] Copy the character >:@i.@# as many times as it index < Box the result ``` The results are boxed to prevent J from padding the ends with spaces (since they're of uneven length). Sample call: ``` dup 'abc' ┌─┬──┬───┐ │a│bb│ccc│ └─┴──┴───┘ ``` ### Space ``` (,' '&,)/&.> &.> For each boxed element (,' '&,)/ Insert spaces between each ``` Sample call: ``` space dup 'abc' ┌─┬───┬─────┐ │a│b b│c c c│ └─┴───┴─────┘ ``` ### Pad ``` |.@i.@# (>@],~' '#~[)"_1 ] (>@],~' '#~[) Pad the right arg with spaces given by the left arg |.@i.@# Indices in reverse order i. # Range [0,length) |. Reverse ``` Basically, pad the first element with length - 1 spaces, the second with length - 2, etc. It also removes the boxing. Sample call: ``` pad space dup 'abc' a b b c c c ``` ### Transpose This is just the built-in function `|:` which takes the transpose of a matrix. [Answer] # JavaScript (ECMAScript 6), 161 bytes ``` (s,n=console.log)=>s.split("").map((q,i,a,p)=>n(p=" ".repeat(q=a.length-++i)+a.map((v,j)=>j>=q&&j%2==q%2?a[j]+' ':'').join(''))||p).reverse().map((v,i)=>i&&n(v)) ``` [Try it online!](https://tio.run/##NYy9CoMwFEZfJQSq92LM4FiIXfsGHUqHoBebkObHBHHw3W2gdPvgnPNZvek8rSaW3oeZTkeF7UydkIVXU/A5OJIuLKjGLHN0pgDnKD86AiRhhBaxIg9RccblSpF0gaS0dOSX8u67zmCnf/4mbHXtqFLT2MugVLoMN/20r65l7bVtUdpgPNSBxxGxvm20ZgL856bmpmk8bIjnDvxOzgX2CKubOZ5f "JavaScript (Node.js) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 86 + 2 (-F) = 88 bytes Used @Dom's suggestions and a few of my own tweaks to lower the byte count. ``` for$k(0..$#F){$i=1;$a[$#F+$k]=$a[$#F-$k]=[map$i++<$k|($i+$k)%2?$":$_,@F]}say"@$_"for@a ``` [Try it online!](https://tio.run/##K0gtyjH9X1qcqmCqZ2BoYP0/Lb9IJVvDQE9PRdlNs1ol09bQWiUxGsjRVsmOtYUwdUHM6NzEApVMbW0blewaDSBDJVtT1cheRclKJV7HwS22tjixUslBJV4JaKBD4v//Hqk5OfkK4flFOSn/8gtKMvPziv/rugEA "Perl 5 – Try It Online") [Answer] # q/kdb+, 55 bytes **Solution:** ``` -1(+){{1_a,((2*y)#" ",z),a:x#" "}'[(|)c;1+c:(!)(#)x]x}; ``` **Example:** ``` q)-1(+){{1_a,((2*y)#" ",z),a:x#" "}'[(|)c;1+c:(!)(#)x]x}"Hello World"; d l r d o l W r d o l o W r d l o l l o W r d e l o l H l o W r d e l o l l o W r d l o l o W r d o l W r d o l r d l d ``` **Explanation:** TODO. ungolfed version is 66 bytes: ``` -1 flip{{1_a,((2*y)#" ",z),a:x#" "}'[reverse c;1+c:til count x]x}; ``` **Bonus:** To get the same output as the example (74 bytes): ``` q)-1(+){1_'raze{(a,((2*y)#" ",z),a:x#" ";(2*y+x)#" ")}'[(|)c;1+c:(!)(#)x]x}"Hello World"; d l r d o l W r d o l o W r d l o l l o W r d e l o l H l o W r d e l o l l o W r d l o l o W r d o l W r d o l r d l d ``` ]
[Question] [ My first code golf post, apologies for any mistakes... # Context In rock climbing ([bouldering specifically](https://en.wikipedia.org/wiki/Grade_(bouldering))), the V/Vermin (USA) climbing grades start at 'VB' (the easiest grade), and then go 'V0', 'V0+', 'V1', 'V2', 'V3', 'V4', 'V5' etc. up to 'V17' (the hardest grade). # Task You will take as input a list/array of climbing grades and you have to to return or print a list/array of the grades sorted from easiest to hardest. If the input is empty, return an empty data structure; otherwise the input will always be a valid. # Test cases ``` Input | Output [] | [] ['V1'] | ['V1'] ['V7', 'V12', 'V1'] | ['V1', 'V7', 'V12'] ['V13', 'V14', 'VB', 'V0'] | ['VB', 'V0', 'V13', 'V14'] ['V0+', 'V0', 'V16', 'V2', 'VB', 'V6'] | ['VB', 'V0', 'V0+', 'V2', 'V6', 'V16'] ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge. [Answer] # [Python 2](https://docs.python.org/2/), ~~58~~ 54 bytes ``` lambda x:sorted(x,key=lambda y,B10=0:eval(y[1:]+'10')) ``` [Try it online!](https://tio.run/##LYrLCoMwEEX3fsXskqCUjH0HsvEjZtN2kaJSaapiQjFfn47QxTD3nnvmFF/TWOfe3rN3n2frYDVhWmLXyrV6d8n@aaoa1Fab7uu8TDc0j1KgFkrlYAUhAuEB6AhUA52ANHdODb89H5MrEAvIxpnnkuPmAG0zk4vYhdkPUaqimJdhjNDLoPIP "Python 2 – Try It Online") ## How it works ``` y y[1:]+'10' eval(y[1:]+'10') ======================================= VB B10 0 (a variable we defined) V0 010 8 (an octal literal) V0+ 0+10 10 V1 110 110 V2 210 210 ... ... ... V17 1710 1710 ``` [Answer] ## JavaScript (ES6) / Firefox, 53 bytes ``` a=>a.sort((a,b)=>(g=s=>parseInt(s,32)%334+s)(a)>g(b)) ``` ### Test cases For Firefox: ``` let f = a=>a.sort((a,b)=>(g=s=>parseInt(s,32)%334+s)(a)>g(b)) console.log(JSON.stringify(f([]))) console.log(JSON.stringify(f(['V1']))) console.log(JSON.stringify(f(['V7', 'V12', 'V1']))) console.log(JSON.stringify(f(['V13', 'V14', 'VB', 'V0']))) console.log(JSON.stringify(f(['V0+', 'V0', 'V16', 'V2', 'VB', 'V6']))) ``` For Chrome or Edge (+4 bytes): ``` let f = a=>a.sort((a,b)=>(g=s=>parseInt(s,32)%334+s)(a)>g(b)||-1) console.log(JSON.stringify(f([]))) console.log(JSON.stringify(f(['V1']))) console.log(JSON.stringify(f(['V7', 'V12', 'V1']))) console.log(JSON.stringify(f(['V13', 'V14', 'VB', 'V0']))) console.log(JSON.stringify(f(['V0+', 'V0', 'V16', 'V2', 'VB', 'V6']))) ``` ### How? We apply 3 successive transformations that lead to lexicographically comparable strings. ``` s | Base32 -> dec. | MOD 334 | +s ------+----------------+---------+--------- "VB" | 1003 | 1 | "1VB" "V0" | 992 | 324 | "324V0" "V0+" | 992 | 324 | "324V0+" "V1" | 993 | 325 | "325V1" "V2" | 994 | 326 | "326V2" "V3" | 995 | 327 | "327V3" "V4" | 996 | 328 | "328V4" "V5" | 997 | 329 | "329V5" "V6" | 998 | 330 | "330V6" "V7" | 999 | 331 | "331V7" "V8" | 1000 | 332 | "332V8" "V9" | 1001 | 333 | "333V9" "V10" | 31776 | 46 | "46V10" "V11" | 31777 | 47 | "47V11" "V12" | 31778 | 48 | "48V12" "V13" | 31779 | 49 | "49V13" "V14" | 31780 | 50 | "50V14" "V15" | 31781 | 51 | "51V15" "V16" | 31782 | 52 | "52V16" "V17" | 31783 | 53 | "53V17" ``` [Answer] ## [Husk](https://github.com/barbuz/Husk), 5 bytes ``` ÖiÖm± ``` [Try it online!](https://tio.run/##yygtzv7///C0zMPTcg9t/P//f7RSmIG2kg6QBBGGZiDSCEQ4gQgzpVgA "Husk – Try It Online") The results are printed one per line, but internally this is a function that takes and returns a list of strings. ## Explanation This is surprisingly similar to [Martin's Retina answer](https://codegolf.stackexchange.com/a/137157/32014). First we do `Öm±`, meaning "order by mapping is-digit". This puts `VB`, `V0` and `V0+` in the correct order, since they are compared as `[0,0]`, `[0,1]` and `[0,1,0]`. Next we do `Öi`, meaning "order by integer value". Given a string, `i` returns the first sequence of digits occurring in it as an integer, or 0 if one is not found. The three strings above are all mapped to 0 and the sort is stable, so they will be in the correct order in the output. [Answer] ## [Retina](https://github.com/m-ender/retina), 14 bytes ``` B ! O` ! B O#` ``` [Try it online!](https://tio.run/##FYotFoAwDIN9bsFDYigbf7YXmIveBAKD4HH/kok0afK913c/LcIxoFQdRxlrBM1Ay@AKLuAGzvqVXJYkNScowETsmifFzoB9VnP8 "Retina – Try It Online") ### Explanation ``` B ! ``` Replace `B` with `!` so that the lexicographic order of grades puts `VB` (or then `V!`) in front of all the numeric grades. ``` O` ``` Sort all input lines lexicographically. This doesn't give the right result but it does order `V! < V0 < V0+` correctly. ``` ! B ``` Turn `V!` back into `VB`. ``` O#` ``` Sort the lines numerically. Retina simply looks for the first decimal number in a string to determines its sort key. If there is no number (such as for `VB`), it sets the value to `0`. That means all of `VB`, `V0` and `V0+` have the same sort key. But Retina's sort is stable and we've already put them in the correct relative order. [Answer] # [V](https://github.com/DJMcMayhem/V), 3 bytes ``` Úún ``` [Try it online!](https://tio.run/##K/v///Csw7vy/v8PM9DmCjPmCjPhCjPgCjPkCnPiCjPiCjPlCjMDcs0B "V – Try It Online") ## How does it work? ``` ú # Sort on... n # the first decimal number on the line ``` This command is *almost* a valid solution, since every line that *can't* be sorted by numbers (AKA, `VB`) will be placed at the beginning, without the order changed. However, since it's only looking at numbers, it can't distinguish between `V0` and `V0+`. Since Vim uses a stable sort, whichever of these came first will remain first after sorting it. So... ``` Ú # Sort lexicographically (will place 'V0' before 'V0+') ú # Sort by... n # The first number on the line ``` [Answer] # C#, ~~121~~ ~~83~~ ~~82~~ 83 bytes *Saved **39** bytes thanks to TheLethalCoder and LiefdeWen* ``` a=>a.OrderBy(x=>x[1]>65?-1:x=="V0+"?0.5:int.Parse(x.Remove(0,1))) ``` [Try it online!](https://tio.run/##TU@xasMwFNz1FQ9NMnWEPaRDXCmQ0kJLS0ML6RAyqPZLENgSleTUIfjbXcU4pbc97u7dXelnjTV2aL02B/g4@YBNQf5f/EWb74KQslbewxrOBCJ8UEGXcLS6glelDfPBRc92B8odfDKpLnhsTXl3ZVN4enMVOqweTNugU181TqSUsI9SEECu3kEJqfhoWJ1YJ2S3zXfydr6c5YtOCLrJbugy4/OFNoGvlfPIOv6OjT0iy9I8SZIhFod7a7ytkX86HTCuwaksf7axOE1peglmBn/gb8UZ6CanKYwZ0MdXxdiqJ/3wCw "C# (Mono) – Try It Online") Bytecount includes `using System.Linq`. --- **How?** * Gets an array of strings as input. * If the input is equal to `VB`, set the value to -1, if it's equal to `VB0+`, set the value to 0. * Order the input based on the number value that comes after the `V`. Might be a bit of a hack, but it works! :) [Answer] # [Ruby](https://www.ruby-lang.org/), ~~52 42~~ 41 bytes ``` ->x{[?B,0,"0+",*1..17].map{|a|"V#{a}"}&x} ``` [Try it online!](https://tio.run/##FYrLCsIwFER/5RJR1MaQ66u6UKEfMZvSRVx0VyhqsZLm2@N0MczrvIbnL7e3vLuPsX5U1lvjC2O36pyWjetCH6cwGSxiSCatxpT74fOWtl5@11AV6FFwEuwFZ4FnZ6poB4rLVUBASZS8C8aZEcw3l8umyX8 "Ruby – Try It Online") ### How it works: Turn the problem around, produce the full sorted list, then get the intersection with our input. Thanks Lynn for saving 1 byte. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 16 bytes Port of [Python answer](https://codegolf.stackexchange.com/a/137152/48934) by OP. ``` o|hx"B00+"tN+3st ``` [Test suite](http://pyth.herokuapp.com/?code=o%7Chx%22B00%2B%22tN%2B3st&test_suite=1&test_suite_input=%5B%5D%0A%5B%27V1%27%5D%0A%5B%27V7%27%2C+%27V12%27%2C+%27V1%27%5D%0A%5B%27V13%27%2C+%27V14%27%2C+%27VB%27%2C+%27V0%27%5D%0A%5B%27V0%2B%27%2C+%27V0%27%2C+%27V16%27%2C+%27V2%27%2C+%27VB%27%2C+%27V6%27%5D&debug=0). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ ~~13~~ 8 bytes ``` Σþï}„VB† ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3OLD@w6vr33UMC/M6VHDgv//o9XDDLTVdRSAFJg0NANTRmDSCUyaqccCAA "05AB1E – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḋv-.F+LµÞ ``` A monadic link taking a list of lists of characters and returning the sorted list. **[Try it online!](https://tio.run/##y0rNyan8///hjq4yXT03bZ9DWw/P@3@4PcvhUdOaR4371NWzgKSOwv//6mEG2uo6CkAKTBqagSkjMOkEJs3UAQ "Jelly – Try It Online")** (the footer formats the result nicely) ### How? ``` Ḋv-.F+LµÞ - Link: list of lists of characters µÞ - sort by key: Ḋ - dequeue (remove the 'V' from the item) -. - literal -0.5 v - evaluate as Jelly code with argument -0.5 - ...this means `VB` and `V0+` become -0.5 - (to binary and addition respectively) - while others become their literal numbers F - flatten +L - add the length of the item - ...'VB', 'V0', 'V0+', 'V1', 'V2'... -> 1.5, 2, 2.5, 3, 4, ... ``` [Answer] # [Haskell](https://www.haskell.org/), 55 bytes ``` f l=['V':x|x<-"B":"0":"0+":map show[1..17],_:y<-l,x==y] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hxzZaPUzdqqKmwkZXyUnJSskAhLWVrHITCxSKM/LLow319AzNY3XirSptdHN0KmxtK2P/5yZm5tkWFGXmlaikRSuFAdXrKAApMGloBqaMwKQTmDRTiv0PAA "Haskell – Try It Online") [Answer] ~~To kick things off here is my Python 3 solution...~~ Apologies, posted this too soon against convention, now re-posting... # [Python 3](https://docs.python.org/3/), ~~69~~ 67 bytes ``` lambda l:sorted(l,key=lambda x:'B00+'.find(x[1:])+1or int(x[1:])+3) ``` [Try it online!](https://tio.run/##TY5NDoMgEEb3nIIdEEkD2tiEhI2H6MaysFFSU/wJsNDTU4Q2lQWPeTNkvnX3r2WugpaPYLrp2XfQCLdYP/TY0Pewy6/dBGoYK9BFj3OPt5YLRQq@WDjO/ldWJPjBeQclbAGMp1U0E905@r9viMJoyoxTg1dZXROadLNTP@7PKk3VCeVptkZKAaBjqiNHjJboRPq/2iOqxociBIQP "Python 3 – Try It Online") [Answer] # [Swift 3](https://swift.org/blog/swift-3-0-released/), 102 bytes ``` var r={String((Int($0,radix:32) ?? 992)%334)+$0};func f(l:[String]){print(l.sorted(by:{r($0)<r($1)}))} ``` This is a function. You can call it as such: ``` f(l:["V0","VB","V13","V0+"]) ``` **[Try it online!](http://swift.sandbox.bluemix.net/#/repl/5981c1ec94c9c15dc3f62e5e)** --- # How does this work? This is basically a port of the [amazing Javascript answer by @Arnauld](https://codegolf.stackexchange.com/questions/137151/sort-the-climbing-grades/137159#137159), but optimized for Swift. It maps each of the values to lexicographically orderable Strings as shown in the table below: ``` Initial String -> Result V1 -> 325V1 V10 -> 46V10 V11 -> 47V11 V12 -> 48V12 V13 -> 49V13 V14 -> 50V14 V15 -> 51V15 V16 -> 52V16 V17 -> 53V17 V2 -> 326V2 V3 -> 327V3 V4 -> 328V4 V5 -> 329V5 V6 -> 330V6 V7 -> 331V7 V8 -> 332V8 V9 -> 333V9 V0+ -> 324V0+ V0 -> 324V0 VB -> 1VB ``` --- # Code Explanation * `String((Int($0,radix:32) ?? 992)%334)` - Converts each String from a base-32 Number to Decimal. In case the value is "V0+", the call to `Int(_:radix:)` will return nil, and we take the value of "V0", 992. We additionally take the result of `mod 334`, and finally convert it to String. * `+$0` - Adds the current value to the String created above. For instance, if the String is `V9`, the function above returns `333` and we add `V9`, resulting in `333V9`. * `var r={...}` - Declares a variable `r` to an anonymous closure, because it saves lots of bytes since it's used twice. * `func f(l:[String])` - Defines a function `f` with a parameter `l`, a list of Strings. * `print(l.sorted(by:{r($0)<r($1)}))` - Prints the result of sorting the given list, with the key being the variable `r` defined above. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 45 bytes ``` param($a)'B',0,'0+'+1..17|%{"V$_"}|?{$_-in$a} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVRU91JXcdAR91AW13bUE/P0LxGtVopTCVeqbbGvlolXjczTyWx9v///w4a6mFANToKQApMGpqBKSMw6QQmzdQ1AQ "PowerShell – Try It Online") Uses the same process as [G B's Ruby answer](https://codegolf.stackexchange.com/a/137173/42963) to construct the full argument list in sorted order, then select out those that are `-in` the input list. [Answer] # Google Sheets, 142 bytes ``` =ArrayFormula(If(A1="","",Sort(Transpose(Split(A1,",")),Transpose(IfError(Find(Split(A1,","),"VBV0V0+"),Value(Mid(Split(A1,","),2,3))+9)),1))) ``` Input is a string in `A1` with each entry separated by a comma. Output is the formula's cell plus the `n-1` cells below it where `n` is the number of entries in `A1`. [![Result](https://i.stack.imgur.com/J37Hh.png)](https://i.stack.imgur.com/J37Hh.png) It's a long, messy formula so let's unpack it. * `If(A1="","",~)` fixes the null input. Without this, an empty input returns a `#VALUE!` error because the `Split` function doesn't work on empty inputs. * `Transpose(Split(A1,","))` splits `A1` at the commas and transposes it into a column because the `Sort` function only works on columns. * `Transpose(IfError(Find(),Value()+9))` is breaks into these pieces: + `Find(Split(A1,","),"VBV0V0+")` tries to find each parameter in that string. These first three are the only ones that must be sorted as strings so we use `Find` to get their sort order. + `Value(Mid(Split(A1,","),2,3))+9` gets the numerical value of the grade. This only matters for V1 and higher so they sort numerically just fine. The `+9` at the end is to ensure V1 comes after V0+ since its `Find` value would be `5`. Technically, then, only `+5` is required but it costs me no more bytes to make extra double sure it sorts correctly. + `IfError(Find(~),Value(~))` returns the `Find` value if the string was found (i.e., the grade is VB, V0, or V0+). If it can't be found, it returns the numerical value of the grade plus nine. + `Transpose(IfError(~))` again turns it into a column so `Sort` can use it. * `Sort(Transpose(Split(~)),Transpose(IfError(Find(~),Value(~)+9)),1)` wraps it all up by sorting the split input using the custom sort order ascending. * `ArrayFormula(~)` wraps the entire thing so it returns the results as an array instead of just returning the first value in that array. This is what causes the formula in one cell to fill the cells below it, too. [Answer] # Bash + coreutils, 21 ``` tr B .|sort -V|tr . B ``` [GNU `sort`'s `-V`ersion sorting mode](https://www.gnu.org/software/coreutils/manual/html_node/Details-about-version-sort.html#Details-about-version-sort) almost does what we want. Switch the `B` for a `.` and we're done. [Try it online](https://tio.run/##FUs7DoAgFNt7ircbifhDVw7RXSc3E2Dk7s@atGn6u6/6uLdi2UKvb2k2sssGy@6MG3iCcQGzZBJ38JAIP1dQUK7FDKpMoE7ToFJBTB8). [Answer] # [Haskell](https://www.haskell.org/), ~~90~~ ~~84~~ ~~83~~ 61 bytes ``` import Data.List f"VB"=[] f(_:'1':[a])='X':[a] f x=x sortOn f ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuIQrTSnMSck2OpYrTSPeSt1Q3So6MVbTVj0CzOBKU6iwreBKty0GavLPU0j7n5uYmWdbUJSZV6KSHq0UZqCtpKMApMCkoRmYMgKTTmDSTCn2PwA "Haskell – Try It Online") `f` is a function that converts climbing grades to strings that can be compared. If converts `VB` to be the empty string so it gets the highest priority, it then replaces `V1` with `X` in strings that are three long to lower the priority of `V10`-`V17`. For the remainder we do nothing. To sort the list we use `Data.Lists`'s `sortOn` function (as suggested by Lynn) to create a point-free function. [Answer] # [R](https://cran.r-project.org/), 45 bytes ``` l=paste0('V',c('B','0','0+',1:17));l[l%in%x] ``` ### How does this work? * Assign the correctly ordered vector of grades to 'l'; + Use 'paste0' instead of 'paste' to avoiding making a 'sep=""' argument; * Index 'l' based on matches of 'l' in your input vector of mixed, unsorted grades. [Answer] **Python2, 77 bytes** ``` sorted(input(),key=lambda s:float(s[1:].replace("B","-1").replace("+",".5"))) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 11 bytes ``` fØD ṢÇÞÇV$Þ ``` [Try it online!](https://tio.run/##y0rNyan8/z/t8AwXroc7Fx1uPzzvcHuYyuF5/w@3H530cOeM//@j1cMMtNV1FIAUmDQ0A1NGYNIJTJqpxwIA "Jelly – Try It Online") [Answer] # [TXR Lisp](http://nongnu.org/txr): 45 bytes ``` (op sort @1 :(ret`@(mod(toint @1 32)334)@1`)) ``` Run: ``` 1> (op sort @1 :(ret`@(mod(toint @1 32)334)@1`)) #<interpreted fun: lambda (#:arg-01-0168 . #:rest-0167)> 2> [*1 ()] nil 3> [*1 (list "V0+" "V0" "V16" "V2" "VB" "V6")] ("VB" "V0" "V0+" "V2" "V6" "V16") ``` [Answer] # [Perl 5](https://www.perl.org/), 56 + 1 (-a) = 57 bytes ``` map{$i=$_;s/V//;$a[/B/?0:/^0/?length:$_+2]=$i}@F;say"@a" ``` [Try it online!](https://tio.run/##LYxPC4IwHEC/yrAJhdhvE/SgLMVDt66/S39kkJXMnGxeROqjtxZ0ezx4b2xNn7pVqMRTjouFGsCItwXk69N1A4iUe7GjzavaF1bOVC2eb9oQq81EVDvbULlfSztBm8KXAAWVR38qWQ4XBmXfDvfpkdMmSs6Cdv9TUMnAOWQRQUaQZwQTgjXB7KPHqdODdfEh3TLOXCy/ "Perl 5 – Try It Online") ]
[Question] [ What is the shortest way of generating a random string with a given length and with only alphanumeric characters allowed? * example of a random string: with N = 9 output would be `aZua7I0Lk` * the given length N can be assumed to be always greater than 0 * if necessary you can assume 256 as a maximum value for N, but solutions with higher limits for N and still having a fast computation time are preferred * allowed characters: 0-9, a-z and A-Z * a character can occur more than once in the output string * each possible string should be equally likely (to the accuracy of your language's random number generator) [Answer] # [Taxi](https://bigzaphod.github.io/Taxi/), 2577 bytes ``` Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:n 1 l 1 l 1 r.[a]Go to Heisenberg's:n 1 r 1 r 3 r.Pickup a passenger going to Cyclone.Go to Go More:n 1 l 3 l 3 l.Go to Starchild Numerology:e 2 r.62 is waiting at Starchild Numerology.Pickup a passenger going to Cyclone.Go to Cyclone:e 1 l 2 r.Pickup a passenger going to What's The Difference.Pickup a passenger going to Divide and Conquer.Pickup a passenger going to Divide and Conquer.Go to Divide and Conquer:n 2 r 2 r 1 r.Pickup a passenger going to Trunkers.Go to Trunkers:e 1 r 3 r 1 l.Pickup a passenger going to Multiplication Station.Go to Cyclone:w 2 r.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:s 1 l 2 r 4 l.Pickup a passenger going to What's The Difference.Go to What's The Difference:n 2 l 1 r 3 l.Pickup a passenger going to Addition Alley.Go to Starchild Numerology:e 1 r 3 l 2 r.1 is waiting at Starchild Numerology.63 is waiting at Starchild Numerology.Pickup a passenger going to Addition Alley.Pickup a passenger going to The Underground.Go to Addition Alley:e 1 l 2 r 3 r 1 r.Pickup a passenger going to Joyless Park.Go to Writer's Depot:n 1 l 1 l.ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789- is waiting at Writer's Depot.Pickup a passenger going to Chop Suey.Go to Joyless Park:n 3 r 2 r 2 l.Go to Chop Suey:w 1 r 1 r 1 l.[b]Pickup a passenger going to Narrow Path Park.Go to Narrow Path Park:n 1 l 1 r 1 l.Go to The Underground:e 1 r.Switch to plan "c" if no one is waiting.Pickup a passenger going to The Underground.Go to Fueler Up:s.Go to Chop Suey:n 3 r 1 l.Switch to plan "b".[c]Go to Joyless Park:n 1 r.Pickup a passenger going to The Underground.Go to Narrow Path Park:w 1 r 3 l.[d]Pickup a passenger going to KonKat's.Go to KonKat's:e 1 r.Pickup a passenger going to KonKat's.Go to The Underground:s.Switch to plan "e" if no one is waiting.Pickup a passenger going to The Underground.Go to Fueler Up:s.Go to Narrow Path Park:n 4 l.Switch to plan "d".[e]Go to KonKat's:n.Pickup a passenger going to Riverview Bridge.Go to Riverview Bridge:n 1 l.Go to Narrow Path Park:e 1 l 1 r.Pickup a passenger going to Post Office.Go to Post Office:e 1 r 4 r 1 l.Go to Sunny Skies Park:s 1 r 1 l 1 r.Pickup a passenger going to The Underground.Go to The Underground:n 1 r 1 r 2 r.Switch to plan "f" if no one is waiting.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:n 3 l 2 l 1 l.Switch to plan "a".[f] ``` [Try it online!](https://tio.run/nexus/taxi#tVbLctowFP0VTTZZhSmGpC07Ak3SpCE0JKUtw0LY17aKIjmSjOv@d9dUtoUB49pApwvh0evcc899oOU1R4qjIZcKPbgusaEToSaieojk2xgSex4GCKMASwnMA4E8TpiX3HryAV3iGVCXSB9E3MjAissduUKsRBuFjMVoNCcg0RCLuUErLneYQcsQJ3ianbsBohFnILxTmZ4R6WjVWO3FNuUMjDH9e88FGButbKyIKCxsn1AHDcIXEJxyL@4AsrSBCwsRiSJMVIKKVenZA2iYmUZPaFg1Lox9rE5lKnufuC4IYDZU3uiTBXEAYeagHmevIYhDj2c8dze0cppuOuri/SRCNgchV1ljpqnTadxq8@8@pIoElNhYEc4S0ZNvQcOoVr9KmPJNk9KJm@0akuXRycBL91IJqRGhGrvrOCSl1aUU4uo8NXipGs190vWi9a9JXaBX10qemaOrV/CQOcaVbYB1OZjsqA7rLY8pyK1eMhZEgdCK9yHgat1JGt3LXv/D1fXNx9u7T/eDh@Hnx9HT85fx12/f8cx2wPV88mNOXxgPXoVU4SL6Gf9607Ra7fOLt@/enxWE2jZTXfc@D3SLy4O3SVrza5lasvIulF9I@7TI@/RkNq2yM8BC8EjDKn9TkOJyLkkGuu7nG7HJcqkxioiy/WQ/oJihE/sEERcxjnTRbehxRNSvQqD61HPQkTtOs7wxFO3PThoTe1qqYm0nKqWxo02U1@TEqRT7jrO7pLAN0GpqhDvgZlF5ueM1/EfVS5KjXSK8o4WHacFVVsngkSxALAhE6FIQx1u1w@Jylo1/YwN7vSo2XjaN3bdO1hbbW@m@8@CQq3o4MpGKUVw/TqySOnKPiOj@T6fsH4CWVhDWgXSny6V1fv6b8TMb2z78AQ) Taxi is *super* not made for this but you can do it! I'll try to explain what's happening below the un-golfed version. ``` Go to Post Office: west 1st left 1st right 1st left. Pickup a passenger going to The Babelfishery. Go to The Babelfishery: south 1st left 1st right. Pickup a passenger going to Sunny Skies Park. Go to Sunny Skies Park: north 1st left 1st left 1st right. [a] Go to Heisenberg's: north 1st right 1st right 3rd right. Pickup a passenger going to Cyclone. Go to Go More: north 1st left 3rd left 3rd left. Go to Starchild Numerology: east 2nd right. 62 is waiting at Starchild Numerology. Pickup a passenger going to Cyclone. Go to Cyclone: east 1st left 2nd right. Pickup a passenger going to What's The Difference. Pickup a passenger going to Divide and Conquer. Pickup a passenger going to Divide and Conquer. Go to Divide and Conquer: north 2nd right 2nd right 1st right. Pickup a passenger going to Trunkers. Go to Trunkers: east 1st right 3rd right 1st left. Pickup a passenger going to Multiplication Station. Go to Cyclone: west 2nd right. Pickup a passenger going to Multiplication Station. Go to Multiplication Station: south 1st left 2nd right 4th left. Pickup a passenger going to What's The Difference. Go to What's The Difference: north 2nd left 1st right 3rd left. Pickup a passenger going to Addition Alley. Go to Starchild Numerology: east 1st right 3rd left 2nd right. 1 is waiting at Starchild Numerology. 63 is waiting at Starchild Numerology. Pickup a passenger going to Addition Alley. Pickup a passenger going to The Underground. Go to Addition Alley: east 1st left 2nd right 3rd right 1st right. Pickup a passenger going to Joyless Park. Go to Writer's Depot: north 1st left 1st left. ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789- is waiting at Writer's Depot. Pickup a passenger going to Chop Suey. Go to Joyless Park: north 3rd right 2nd right 2nd left. Go to Chop Suey: west 1st right 1st right 1st left. [b] Pickup a passenger going to Narrow Path Park. Go to Narrow Path Park: north 1st left 1st right 1st left. Go to The Underground: east 1st right. Switch to plan "c" if no one is waiting. Pickup a passenger going to The Underground. Go to Fueler Up: south. Go to Chop Suey: north 3rd right 1st left. Switch to plan "b". [c] Go to Joyless Park: north 1st right. Pickup a passenger going to The Underground. Go to Narrow Path Park: west 1st right 3rd left. [d] Pickup a passenger going to KonKat's. Go to KonKat's: east 1st right. Pickup a passenger going to KonKat's. Go to The Underground: south. Switch to plan "e" if no one is waiting. Pickup a passenger going to The Underground. Go to Fueler Up: south. Go to Narrow Path Park: north 4th left. Switch to plan "d". [e] Go to KonKat's: north. Pickup a passenger going to Riverview Bridge. Go to Riverview Bridge: north 1st left. Go to Narrow Path Park: east 1st left 1st right. Pickup a passenger going to Post Office. Go to Post Office: east 1st right 4th right 1st left. Go to Sunny Skies Park: south 1st right 1st left 1st right. Pickup a passenger going to The Underground. Go to The Underground: north 1st right 1st right 2nd right. Switch to plan "f" if no one is waiting. Pickup a passenger going to Sunny Skies Park. Go to Sunny Skies Park: north 3rd left 2nd left 1st left. Switch to plan "a". [f] ``` **Start: Get stdin** Pick up the stdin value as text, convert it to a number, and go stick it somewhere to wait. **Plan A Part 1: Get a random integer 1-62** Get a random integer and then get `62` as a number. Duplicate both the random integer and the `62` because we'll need them later. You can only carry 3 passengers at once so we end up with `rand`, `rand`, and `62`. (The other `62` will wait around until we get back.) Go divide `rand` by `62` and truncate the result to get an integer. Go back to get the other copy of `62` and multiply it by the truncated integer from the division. Finally, subtract the product from the first copy of `rand`. This gives us a number 0-61. Now we have to go back to pickup a `1` and add it to the result to get a number 1-62. Yes, all those many lines of text are just `mod(rand(),62)+1`. **Plan A Part 2: Create an array of characters from which to choose** Pickup a string with all the valid characters and also one at the end we don't want (more on that later). The `63` we picked up earlier matches this string length. Take it over to Chop Suey to have it broken into individual passengers. **Plan B: Move the array so we can select a character** One by one, move every character over to Narrow Path Park. It's the only stack available and the only way to not have leftover passengers getting in the way. Everything else in Townsburg is FIFO so I would have to go back and clear out all the passengers every iteration of the overall loop. This way, I can just leave them at the park and they'll get pushed out of the way by the 63 new characters every time. The very first `A` is likely to [never escape](https://i.stack.imgur.com/qKkjr.jpg). **Plan C: Prepare to select a character** This is really just a few stops that didn't need to be in Plan D. Re-position the taxi in preparation. **Plan D: Get all the characters we *dont* want** Starting with the first character in the reversed "array" (this is the 63rd character we don't want), keep picking up and concatenating characters as we count down from the result of the `mod` function in Plan A. Once you hit zero, the next character is the one you want. **Plan E: Drown the ones you don't want and return the chosen one.** "[P]assengers dropped off at Riverview Bridge seem to always fall over the side and into the river..." Well, that gets rid of that concatenated string of losers. Go pick up the next character and send it to stdout. Finally, let's check how many characters we've printed thus far. Back to Sunny Skies to pick up the stdin value we left so long ago. Subtract one and, if the result is more than zero, send it back to wait and start over again at Plan A. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~57~~ ~~55~~ 52 bytes Thanks to 2501 for the pointers... ``` i;f(n){for(;n-=isalnum(i=rand()%150)&&putchar(i););} ``` [Try it online!](https://tio.run/nexus/c-gcc#bcvBCoMwEIThu09RhMrOQYgtPS0@TIgGF5q1JHoSH7vnVAOFHjrHj/mzsCfF5udIrG0vyT51DSR9tDoQrt3DoGle6@ImG0nA4D0HK0qotupyLJXnImEkA/BJxT11N/BRJqpr8Nfuf8z8WOn3/Na5ddZN4wc "C (gcc) – TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) *Missed a trick - see [ais523's 4 byter](https://codegolf.stackexchange.com/a/119196/53748)* ``` ØBX$€ ``` **[Try it online!](https://tio.run/nexus/jelly#@394hlOEyqOmNf///zf@mpevm5yYnJEKAA "Jelly – TIO Nexus")** ### How? ``` ØBX$€ - Main link: n € - for each in range(n): $ - last two links as a monad: ØB - "base digits" - yields list of chars "01..9AB...Zab...z" X - random choice ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ØBṗX ``` [Try it online!](https://tio.run/nexus/jelly#@394htPDndMj/v//b/w1L183OTE5IxUA "Jelly – TIO Nexus") ## Explanation ``` ØBṗX ØB All letters (uppercase and lowercase) and digits ṗ Cartesian power with {the input} X Select a random possibility ``` Cartesian power basically generates all list of a given length that can be formed out of a given set of elements; that's exactly what we need here. [Answer] # Shell + [pwgen](https://linux.die.net/man/1/pwgen), 13 bytes ``` pwgen -s $1 1 ``` > > -s, --secure > > > Generate completely random, hard-to-memorize passwords. > > > ### Sample output ``` %pwgen -s 10 1 2cyhLovbfT ``` [Answer] # Java 8, ~~183~~ ~~149~~ ~~97~~ 88 bytes ``` n->{for(int t;n-->0;t*=Math.random(),System.out.printf("%c",t+=t>9?t>35?61:55:48))t=62;} ``` [Try it online.](https://tio.run/##jZDRasIwFIbvfYqDMEg2W9SushlSn0BvvJRdHNN2i2tPpT0KIn32mka3i8GguQjk/B/5v@SAZwwO6XdnCmwaWKOl6wjAEmd1jiaDTX8EOFc2BSPcHEgqN2pHbmsY2RrYAIGGjoLkmle1h1hRECRTxc96jfwV1khpVQo52V4azsqwOnF4rB2Zi/GTGU/4RXPyvuIkileL2TKOl69vUrJezFXbqb7reNoXrutR6X1KZyu27K753H0Ayrvqj4LVkQLrLeARAVBoROwf0K@/MgWJ36wnZ9PB6Hw4GkWD0P@z1v9/290A) -9 bytes by porting [*@2501*'s C answer](https://codegolf.stackexchange.com/a/119142/52210), so make sure to upvote him as well! **Old answer, 97 bytes** ``` n->{for(int t;n-->0;t*=Math.random(),System.out.printf("%c",t>9?(t<36?65:97)+t%26:48+t%10))t=62;} ``` [Try it online.](https://tio.run/##jZHBbsIwDIbvPIWFhJQwWrF2dIPQ8gRw4Yh2yNJ2C2td1BqkCfXZOzeDHSZNag6JYn/y/0U56ov2julnZwrdNLDVFq8jAIuU1bk2Gez6K8ClsikYwXVAqbjUjnhrSJM1sAOEGDr0kmte1Q4ihZ6XzBVN462mD7/WmFalkLP9V0NZ6Vdn8k81k7kYT8x4RslyI2gdRptosVo@yweaBNHq6YXPx7mUFEeBajvVh57ObwWH3rKdWMnaYk887/3wClr@ON9dbBwqsE4Hbi0A9I1YuJf0669VgeK315PsMBQNhqNhOAj9v9e6j2i7bw) **Explanation:** ``` n->{ // Method with integer parameter and String return-type for(int t; // Temp integer n-->0 // Loop the input amount of times: ; // After every iteration: t*=Math.random(), // Set `t` to a random integer in the range [0,62) System.out.printf("%c", // Print as character: t+= // The random integer, after we've added: t>9? // If the random integer is larger than 9: t>35? // If the random integer is larger than 35: 61 // Add 61 : // Else: 55 // Add 55 : // Else: 48)) // Add 48 t=62;} // (Re)set `t` to 62 for the random n->{for(int t;n-->0;t*=Math.random(),System.out.printf("%c",...))t=62;} // Similar as above t>9? // If the random integer is larger than 9: (t<36? // If the random integer is smaller than 36: 65 // Start with 65 ('A') : // Else: 97) // Start with 97 ('a') +t%26 // And add the random integer modulo-26 : // Else: 48 // Start with 48 ('0') +t%10) // And add the random integer modulo-10 ``` [Answer] ## C, 60 bytes ``` r;f(n){for(;n--;)r=rand()%62,putchar(r+=r>9?r>35?61:55:48);} ``` See it [work here](https://ideone.com/Uvh4PA). See the [distribution here](https://ideone.com/lvgSHj). It is uniformly distributed, assuming `rand() % 62` produces a uniform distribution. Since 62 usually doesn't evenly divide RAND\_MAX, there is a very small bias. [Answer] # [Snowman](http://github.com/KeyboardFire/snowman-lang), 58 bytes ``` ((}#`""*:48vn58nR|65vn91nR,aC|97vn123nR,aCAsH1AaL#aC*;bR)) ``` [Try it online!](https://tio.run/nexus/snowman#qzM00PqvoVGrnKCkpGVlYlGWZ2qRF1RjZlqWZ2mYF6ST6FxjaV6WZ2hkDOY4FnsYOib6KCc6a1knBWlq/lcuDvj/NS9fNzkxOSMVAA "Snowman – TIO Nexus") This is a subroutine that takes an integer as input and returns the random string. ``` (( subroutine } make b, e, g active #` e = input (from +) ""* store an empty string in + : what follows is the block to prepend a random char to + 48vn58nR| generate range(48..58) and place in g (need b and e for next step) 65vn91nR generate range(65..91) in b ,aC| move g to e, concatenate b and e, and move the result to g 97vn123nR generate range(97..123) in b ,aC move g to e, concatenate b and e, keeping the result in b AsH shuffle the array of candidate ASCII codes stored in b 1AaL equivalent to 0aAwR - get the first element wrapped in an array #aC retrieve + and prepend the randomly generated character * store back into + ;bR repeat this block e times, where e has been set to the input )) output is given via + ``` [Answer] # PowerShell, ~~58~~ 54 Bytes -4 thanks to Andrei Odegov - casting to a char array instead of looping to create a char array. ``` -join[char[]](65..90+97..122+48..57|random -C "$args") ``` generates a range `1..2+4..5 = 1,2,4,5` of all the acceptable charachter codes, then selects `$args` number of elements randomly using `random -Count` - the resulting elements ~~are looped through `|%{}` and turned into `[char]`s,~~ are cast to an array of chars using `[char[]]` - then the whole thing is encapsulated in brackets and `-join`ed together. ``` PS C:\users\sweeneyc\Desktop> .\grstr.ps1 5 oaCE5 PS C:\users\sweeneyc\Desktop> .\grstr.ps1 10 UReh6McG7D PS C:\users\sweeneyc\Desktop> .\grstr.ps1 30 t1YrhZf5egyzqnPlWUKV3cEoIudMTs ``` Does not work for an input of 0 as `Get-Random` only accepts numbers above 1 for the `-Count` parameter. [Answer] # PHP, 56 Bytes ``` for(;$argn;)ctype_alnum($l=chr(rand()))&&$argn-=print$l; ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/b2f96e9a51a5923ad559d4225a516138bea6ba9c) [ctype\_alnum](http://php.net/manual/en/function.ctype-alnum.php) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` FžK.RJ ``` [Try it online!](https://tio.run/nexus/05ab1e#@@92dJ@3XpDX//@GRl/z8nWTE5MzUgE "05AB1E – TIO Nexus") **Explanation** ``` F # input number of times do žK # push [a-zA-Z0-9] .R # pick one at random J # join to string ``` [Answer] # [Perl 5](https://www.perl.org/), 41 bytes 40 bytes of code + `-p` flag. ``` $\.=(a..z,A..Z,0..9)[rand 62]for 1..$_}{ ``` [Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAt@K8So2erkainV6XjqKcXpWOgp2epGV2UmJeiYGYUm5ZfpGCop6cSX1v9/7@Zyde8fN3kxOSMVAA "Perl 5 – TIO Nexus") `(a..z,A..Z,0..9)` creates an array containing all letters and numbers, `[rand 62]` returns an random element of this array, which is append (`.=`) to `$\`, which is implicitly printed at the end thanks to `-p` flag with `}{`. --- Or, for the same bytecount, but using the parameters rather than the standart input: ``` print+(a..z,A..Z,0..9)[rand 62]for 1..pop ``` [Try it online!](https://tio.run/nexus/perl5#U1YsSC3K@V9QlJlXoq2RqKdXpeOopxelY6CnZ6kZXZSYl6JgZhSbll@kYKinV5Bf8P//fzOTr3n5usmJyRmpAA "Perl 5 – TIO Nexus") [Answer] # R, 51 bytes Same length as the other R answer, but a different approach. ``` cat(sample(c(letters,LETTERS,0:9),scan(),T),sep="") ``` `letters` and `LETTERS` both are built-in variables containing all lower and uppercase letters respectively. Adding `0:9` to that and we have the entire set of alphanumeric characters. [Answer] ## R, 54 52 51 49 bytes ``` intToUtf8(sample(c(65:90,97:122,48:57),scan(),T)) ``` Explanation: 1. Read input integer *n*: `scan()` 2. Vector with ASCII values: `c(65:90,97:122,48:57)` 3. Sample *n* ASCII values with replacement: `sample(c(65:90,97:122,48:57),scan(),T)` 4. Transform ASCII values to a character string with `intToUtf8` [Answer] # JavaScript (ES6), ~~61~~ ~~54~~ ~~39~~ ~~52~~ 64 bytes This is almost like reverse-golf! Took a big hit on the byte count ensuring that the full range of characters from all three groups would be used. ``` f=n=>n--?btoa(String.fromCharCode(Math.random()*248))[0]+f(n):"" ``` * 15 bytes saved (at one stage) thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s suggestion of using a recursive function. --- ## Try it ``` f=n=>n--?btoa(String.fromCharCode(Math.random()*248))[0]+f(n):"" i.addEventListener("input",_=>o.innerText=f(+i.value)) ``` ``` <input id=i type=number><pre id=o> ``` [Answer] ## [Alice](https://github.com/m-ender/alice), 24 bytes ``` /w9u"Uz;r \0.rdao"ki@/t& ``` [Try it online!](https://tio.run/nexus/alice#@69fblmqFFplXcQVY6BXlJKYr5Sd6aBfovb/v6GBwde8fN3kxOSMVAA "Alice – TIO Nexus") This layout is already a lot better than what I originally had (32 bytes), but I'm sure it's not optimal yet... ### Explanation ``` / Reflect to SE. Switch to Ordinal. The IP now bounces diagonally up and down through the code. 09 Append 0 and 9 to an (implicit) empty string to create "09". r Range expansion, turns the string into "0123456789". "az" Push this string. r Range expansion, turns it into the lower-case alphabet. i Read all input as a string. / Reflect to E. Switch to Cardinal. t Implicitly convert the input string to the integer value N it contains and decrement it. & Run the next command N-1 times. The IP wraps around to the first column. \ Reflect to NE. Switch to Ordinal. (This is not a command.) w Push the current IP address to the return address stack N-1 times. This starts a loop whose body will run N times. . Duplicate the lower-case alphabet. u Convert it to upper case. d Push the concatenation of all values on the stack. This pushes a single string with digits, lower-case and upper-case alphabet. U Random choice. Pick a character from this string uniformly at random. o Print it. ; Discard the upper-case alphabet, because it will be regenerated in the next loop iteration (and if we leave it, then upper-case letters will become more and more likely as the output grows). k As long as there is still an address on the return address stack, jump back to that address (i.e. to the w). Once the return address stack has been depleted, this does nothing and the loop is exited. @ Terminate the program. ``` [Answer] # Python + [exrex](https://github.com/asciimoo/exrex), 81 bytes ``` import exrex,random lambda n:random.choice(list(exrex.generate("[A-Za-z0-9]"*n))) ``` [Answer] # [Bash](https://www.gnu.org/software/bash/), 43 bytes ``` shuf -ern$1 {a..z} {A..Z} {0..9}|tr -d "\n" ``` [Try it online!](https://tio.run/nexus/bash#@1@cUZqmoJtalKdiqFCdqKdXVatQ7ainFwWkDPT0LGtrSooUdFMUlGLylP7//29o8DUvXzc5MTkjFQA "Bash – TIO Nexus") [Answer] # Python 2, 79 83 79 bytes ``` import random as r,string as s;lambda x:''.join(r.sample(s.printable[:62]*x,x)) ``` +4 bytes (didn't account for repetition) -4 bytes (Thanks to @Rod for the suggestion for using `printable[:62]`) [Answer] # [Pip](https://github.com/dloscutoff/pip), 13 bytes ``` LaORCz.AZ.J,t ``` [Try it online!](https://tio.run/##K8gs@P/fJ9E/yLlKzzFKz0un5P///5YA "Pip – Try It Online") ### Explanation ``` a is cmdline arg; t is 10; z is lcase alphabet; AZ is ucase (implicit) La Do the following, a times: O Output (without newline) RC random choice from: z Lowercase letters .AZ concatenated with uppercase letters .J,t concatenated with range(10) joined into a string ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 17 bytes Full program. Prompts for length. ``` (?⎕⍴62)⊇⎕A,⎕D,⌊⎕A ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKO94L@G/aO@qY96t5gZaT7qageyHXWAhIvOo54uEAek6L8CGBRwGZmaAwA "APL (Dyalog Extended) – Try It Online") `⎕A` uppercase **A**lphabet `⌊` **L**owercased `⎕D,` prepended by the **D**igits `⎕A,` prepended by the uppercase **A**lphabet `(`…`)⊇` select the following indices from that:  `⍴62` reshape 62 to the following shape:  `⎕` prompt for a number  `?` random indices in in those ranges [Answer] # Swift, ~~138~~ ~~127~~ ~~124~~ 115 bytes ``` var s={String((1...$0).map{_ in"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".randomElement()!})} ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 14 bytes ``` ~l{Ạụ:Ạ:Ịcṛ}ᵐc ``` [Try it online!](https://tio.run/nexus/brachylog2#@1@XU/1w14KHu5daASmrh7u7kh/unF37cOuE5P//Lf9Hfc3L101OTM5IBQA "Brachylog – TIO Nexus") ### Explanation ``` ~l Create a list of length Input { }ᵐ Map on each element of that list: Ạụ:Ạ:Ịc The string "A…Za…z0…9" ṛ Pick a character at random c Concatenate into a single string ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` 8Y2iT&Zr ``` [Try it online!](https://tio.run/nexus/matl#@28RaZQZohZV9P@/JQA "MATL – TIO Nexus") ``` 8Y2 % Push string '012...89ABC...YZabc...yz' i % Input N T&Zr % Sample with replacement. Implicitly display ``` [Answer] ## Batch, 175 bytes ``` @set s=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz @for /l %%i in (1,1,%1)do @call :c @echo %s:~62% :c @set/an=%random%%%62 @call set s=%s%%%s:~%n%,1%% ``` `s` performs double duty here as it contains both the alphanumeric list and the randomly selected characters. After printing the result the code falls through to the subroutine whose result is ignored. [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 4 bytes ``` ~JfH ``` [Try it online!](https://tio.run/nexus/pyke#@1/nlebx/7/x17x83eTE5IxUAA "Pyke – TIO Nexus") ``` ~J - "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" f - cominbations(^, length=input) H - random.choice(^) ``` [Answer] # Pyth, ~~7~~ 11 bytes ``` O^s++rG1GUT ``` [Try it online](https://pyth.herokuapp.com/?code=O%5Es%2B%2BrG1GUT&input=3&debug=0) Explanation ``` O^s++rG1GUT +rG1G Take the uppercase and lowercase alphabets. + UT Add it to the list [0, ..., 9]. s Concatenate to get a string. ^ Q Get all strings of length N. O Choose one at random. ``` [Answer] # C# - 121 bytes ``` void g(int n){Console.Write(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(new Random().Next().ToString())).Substring(0,n));} ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 47 bytes ``` ->n{([*?a..?z,*?A..?Z,*?0..?9]*n).sample(n)*''} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWiNayz5RT8@@SkfL3hFIRwFpAyBtGauVp6lXnJhbkJOqkaeppa5e@7@gtKRYIS3aIJYLyjJEsAxi/wMA "Ruby – Try It Online") [Answer] # Sinclair ZX81/Timex TS1000/1500 BASIC, ~63 tokenized BASIC bytes ``` 1 INPUT N 2 IF NOT N THEN STOP 3 FOR N=SGN PI TO N 4 PRINT CHR$ (CODE "A"+RND*26); 5 NEXT N ``` There are no lower-case characters in ZX81 without using assembly or having some sort of UDG ROM or something, and for the time being, it only outputs `A-Z`. If zero is entered then the program halts and returns to direct mode. ]
[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/36515/edit). Closed 8 years ago. [Improve this question](/posts/36515/edit) # Background You are all traders for a slightly less than reputable stock firm. You all are part of a group of traders who focus only on one specific stock. Each hour each trader has a chance to Buy X stocks or Sell X stocks. There are 50 hours per round and 3 rounds per competition. At the end of all of the rounds the trader with the highest average value wins a trip to Jamaica! # Gameplay There are 3 rounds of 50 turns each. Each trader begins the round with $5000 and **A random number of shares between 20 and 30** shares. The price of the shares starts at a random number between 10 and 150. Each turn each trader can Buy any number of shares they can afford or Sell any number of shares they currently hold, each for the current price per share. The price per share increases by a random number between 1 and 5 for each share bought and decreases by a random value between 2 and 6 for each share sold. The minimum price is $1. It is important to note that all traders process their transactions at the same time, meaning that any trader buying/selling shares will not affect the price until the next turn. The player with the highest average value at the end of the 3 rounds wins. Value is determined by taking the amount of money left over at the end of the round and adding the number of shares owned by the trader \* closing market price. # Arguments Your program will be rerun at the start of each turn receiving the current market price, the trader's current amount of money and the number of shares owned by that trader. Ex: ``` 120 5000 0 ``` # Output Your trader program must output a letter corresponding to the action it would like to take followed by the quantity. Ex: ``` B10 //Buy 10 shares ``` or ``` S3 //Sell 3 shares ``` The trader also has the option to not do anything that turn. That can be accomplished by outputting a W or any other command that is not 'B>amnt<' or 'S>amnt<' # Submissions Your program will be inside a 'players/>your program name<' directory: ``` +-- players | +-- BotNameFolder | +-- BotProgram ``` Please provide your code along with a command line argument to run it from inside the 'players' directory. For example the Test1 trader could be run with `java -cp "Test1" Test1` # Additional Rules Go ahead, shoot yourself EmoWolf, Idc. No messing with anything outside of your BotNameFolder directory, feel free to create files in there though for persistent info throughout rounds / turns. Do not intentionally create programs to crash the simulation. I will accept multiple entries per user, as long as the entries act as seperate entities (No insider trading). # Leaderboard ``` [java&-cp&"TestPlayer"&Test1]:$10027395221 [python&daydreamer/daydreamer.py]:$5000 [java&-cp&"DayTrader"&DayTrader]:$4713199930331196453 ``` **I will try to update the leaderboard at least once a day** # Controller ``` import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Random; public class Controller { public static BigInteger marketValue = BigInteger.valueOf(100); public static BigInteger newValue = BigInteger.valueOf(100); public static final char BUY = 'B'; public static final char SELL = 'S'; public static final int MARKET_INDEX = 1; public static final int MONEY_INDEX = 2; public static final int SHARE_INDEX = 3; public static int numRunning = 0; public static final int MAX_RUNNING = 10; public static void main(String[] args){ try { BufferedReader br1 = new BufferedReader(new InputStreamReader(new FileInputStream("resources/config"))); int numRounds = Integer.parseInt(br1.readLine()); int turnsPerRound = Integer.parseInt(br1.readLine()); //Create the array of players List<String> players = new LinkedList<String>(); String line1 = null; while((line1 = br1.readLine()) != null){ players.add(line1); } BigInteger[] totalVals = new BigInteger[players.size()]; for(int i = 0; i < totalVals.length; i++){ totalVals[i] = BigInteger.valueOf(0); } br1.close(); //Begin processing for(int round = 0; round < numRounds; round++){ //Create players' shares and currency array Map<String,BigInteger[]> vals = new HashMap<String, BigInteger[]>(); for(int i = 0; i < players.size(); i++){ vals.put(players.get(i), new BigInteger[]{BigInteger.valueOf(5000), BigInteger.valueOf(getRandInt(20,30))}); } marketValue = BigInteger.valueOf(getRandInt(10,150)); newValue = marketValue; for(int turn = 0; turn < turnsPerRound; turn++){ marketValue = newValue; Queue<Object[]> processQueue = new LinkedList<Object[]>(); for(String playerKey : vals.keySet()){ BigInteger[] valSet = vals.get(playerKey); String[] pkParts = playerKey.split("&"); String[] parts = new String[pkParts.length + 3]; for(int i = 0; i < pkParts.length; i++){ parts[i] = pkParts[i]; } parts[pkParts.length] = marketValue + ""; parts[pkParts.length + 1] = valSet[0] + ""; parts[pkParts.length + 2] = valSet[1] + ""; processQueue.add(new Object[]{playerKey, parts}); } while(!processQueue.isEmpty() || numRunning > 0){ if(numRunning < MAX_RUNNING && !processQueue.isEmpty()){ numRunning++; Object[] o = processQueue.poll(); String pKey = (String)(o[0]); String[] p = (String[])(o[1]); try { Process proc = new ProcessBuilder(p).directory(new File("resources/players").getAbsoluteFile()).start(); BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line = br.readLine(); br.close(); switch(line.charAt(0)){ case BUY : BigInteger numShares = new BigInteger(line.substring(1).trim()); if(numShares.multiply(marketValue).compareTo(vals.get(pKey)[0]) <= 0){ BigInteger[] tempVals = vals.get(pKey); tempVals[0] = tempVals[0].subtract(numShares.multiply(marketValue)); tempVals[1] = tempVals[1].add(numShares); vals.put(pKey, tempVals); newValue = newValue.add(numShares.multiply(BigInteger.valueOf(getRandInt(0,2)))); if(newValue.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) >= 1){ newValue = BigInteger.valueOf(Integer.MAX_VALUE - 1); } } break; case SELL: BigInteger shares = new BigInteger(line.substring(1).trim()); if(shares.compareTo(vals.get(pKey)[1]) <= 0){ BigInteger[] tempVals = vals.get(pKey); tempVals[0] = tempVals[0].add(shares.multiply(marketValue)); tempVals[1] = tempVals[1].subtract(shares); vals.put(pKey, tempVals); newValue = newValue.subtract(shares.multiply(BigInteger.valueOf(getRandInt(5,10)))); if(newValue.compareTo(BigInteger.valueOf(1)) <= -1){ newValue = BigInteger.valueOf(1); } } break; } } catch (Exception e) { System.err.println("[" + pKey + "] threw error:"); e.printStackTrace(); } finally{ numRunning--; } }else{ try{ Thread.sleep(50); continue; }catch(InterruptedException e){ continue; } } } System.out.println("Turn " + turn + " over: " + marketValue); } System.out.println("End of round market value is: " + marketValue); int count = 0; for(String player : vals.keySet()){ totalVals[count] = totalVals[count].add(vals.get(player)[0].add(vals.get(player)[1].multiply(marketValue))); count++; } newValue = BigInteger.valueOf(100); } for(int i = 0; i < players.size(); i++){ System.out.println("[" + players.get(i) + "]:$" + (totalVals[i].divide(BigInteger.valueOf(numRounds)))); } } catch (Exception e) { System.err.println("An exception occured while running the controller."); e.printStackTrace(); } } public static Random r = new Random(new Date().getTime()); public static int getRandInt(int min, int max){ return r.nextInt(max - min) + min; } } ``` ***Compile this with `java Controller.java` and run from a directory containing a directory like below:*** ``` +-- resources | +-- config | +-- players | +-- Player1Folder | +-- Player1Program | +-- Player2Folder | +-- Player2Program ``` The file `config` should look something like this: ``` 3 50 java&-cp&"TestPlayer"&Test1 python&daydreamer/daydreamer.py java&-cp&"DayTrader"&DayTrader ``` ***First number is number of rounds, second number is turns per round, followed by the commands to run each player.*** # Replace spaces with ampersands! ('&') ~Let me know if I can improve the wording of this post at all, and happy trading! [Answer] I present 'daydreamer', who is always asleep and forgets to buy or sell anything. He hopes that other players will have a net loss. Python code: ``` if __name__ == "__main__": print "W" ``` run with `python daydreamer\daydreamer.py 120 5000 0` or whatever values you want. I will post a more serious answer later, this is just to get the ball rolling :) [Answer] # DayTrader Updated for rule change made on 8/21/2014, where players now start with 20-30 shares. Buys as much as possible, then sells as much as possible. **Philosophy** We hope that the below pattern will repeat itself over and over. Note that by adhering to this pattern, we also contribute to it. * Everyone can only buy or hold on round one. The value can only increase, so we buy. * Everyone can buy more, hold, or sell on round two. We don't expect many players to buy on round two, so we sell. The pattern is crystal clear at the beginning. Value *will* increase after round one. It should decrease after round two. Beyond that, projections get fuzzy. I expect to do well in the early rounds, before the market stabilizes. ``` import java.math.BigInteger; /** * Submission for http://codegolf.stackexchange.com/q/36515/18487 * @author Rainbolt */ public class DayTrader { /** * @param args the command line arguments containing the current * market value, our current money, and our current shares */ public static void main(String[] args) { BigInteger marketValue = new BigInteger(args[0]); BigInteger myMoney = new BigInteger(args[1]); BigInteger myShares = new BigInteger(args[2]); // If we have less than or equal to 30 shares, buy as much as possible if (myShares.compareTo(new BigInteger("30")) <= 0) { System.out.println("B" + myMoney.divide(marketValue).toString()); // Otherwise, sell as much as possible } else { System.out.println("S" + myShares.toString()); } } } ``` Compile with `javac DayTrader.java`. Run with `java -cp "DayTrader" DayTrader`. [Answer] # Walt Disney - Python 3 Walt waits until the shares hit rock bottom and then buys as much as his money allows. Then, when the price soars, he sells them all. Based upon Disney's strategy when he 'survived' through the Wall Street Crash. Unfortunately, my program cannot build theme parks... If only... Run: ``` python3 waltdisney.py ``` Code: ``` from sys import argv import os price=int(argv[1]) money=int(argv[2]) share=int(argv[3]) if os.path.exists('./buyingprice.txt'): f = open('buyingprice.txt', 'r') buyingprice=int(f.read()) f.close() else: buyingprice=0 if share > 0: if price > buyingprice*10: print('S'+str(share)) else: print('W') elif money > 0: if buyingprice==0: print('B10') m=open('buyingprice.txt', 'w') m.write(str(price)) m.close() elif price <= buyingprice: print('B'+str(int(money/price))) g=open('buyingprice.txt', 'w') g.write(str(price)) g.close() else: print('W') ``` [Answer] ## Tommy only knows what he has but is determined to risk everything on the market. If he can buy, he will. If he can't, he sells everything he has so he can next turn. (This will work well with extreme ones like DayTrader but will autocorrect if the value drops when he thinks it will grow.) ``` import java.math.BigInteger; public class Tommy { public static void main(String[] args) { BigInteger Value = new BigInteger(args[0]); BigInteger Money = new BigInteger(args[1]); BigInteger Shares = new BigInteger(args[2]); if (Money.compareTo(Value)<1) { System.out.print("S" + Shares.toString()); } else { System.out.print("B" + Money.divide(Value).toString()); } } } ``` ## Golfscript This is the same code but if prefered this. I wrote the java after in case the BigInteger thing was needed. Use whatever is easier. ``` 2$2$>{@@;;"S"\}{;\/"B"\} if ``` [Answer] ## BuyAndHold - C ``` #include <stdio.h> #include <stdlib.h> /* BuyAndHold * Code revised from OptoKopper's WaitForCrash.c */ int main(int argc, char *argv[]) { long long int share_price = strtoll(argv[1], NULL, 0); long long int money = strtoll(argv[2], NULL, 0); if (money >= share_price) { printf("B%lld\n", money / share_price); } else { printf("W\n"); } return 0; } ``` Compile with: gcc buyandhold.c -o buyandhold Run it with ./buyandhold PRICE MONEY SHARES [Answer] **Alfred Pennyworth** - Python 2 While I was out on patrol one night, Alfred tried to create a stock trading program without my knowing. He thought he could hide it from me, but I found it and figured out what it did. Because I'm Batman. Now I've decided to enter it into a competition to teach him a lesson. Money is no object to Alfred because I'm REALLY rich, but he's still smart about his trading. When he's out of shares, he buys as many as he can afford, regardless of market price. Then he sells 10 (or all remaining) shares every time the market price is higher than the price it was purchased at. ``` import argparse parser = argparse.ArgumentParser(description="This is a private matter, Master Bruce. Learn how to make your own bed and I will tell you.") parser.add_argument("Stuff", type=int, nargs='+', help="You don't need to know, Master Bruce.") args=parser.parse_args() vals=[] for x in args: vals.append(x) a=vals[0] b=vals[1] c=vals[2] if c==0: x=1 while x*a<b: x+=1 print "B"+str(x) with open("lastval.txt", w) as f: f.write(a) else: lastval=next(open("lastval.txt")) if a>lastval:print "S10" if c>10 else "S"+str(c) else:print 'W' ``` Run with: `python GoAwayMasterBruce.py <args>` [Answer] ## NaiveBot NaiveBot is new to all this "stock market" hooplah. He just assumes that when the price is going up he should buy, and when the price goes down he should sell. But he's no sap, he's got a trick up his sleeve! He only ever buys half of what he can afford, and only ever sells half of what he has. No more living in a box under the freeway for NaiveBot! ``` <?php $cur = array('price' => $argv[1], 'funds' => $argv[2], 'shares' => $argv[3]); $cachefile = 'cache.json'; if( ! file_exists($cachefile) ) { $cache = array(); } else { $cache = json_decode(file_get_contents($cachefile), true); } // determine action if( empty($cache) ) { $action = 'buy'; // always buy on first turn } else if( $cur['price'] > $cache[count($cache)-1]['price'] ) { $action = 'buy'; } else if( $cur['price'] < $cache[count($cache)-1]['price'] ) { $action = 'sell'; } else { $action = 'hold'; } // determine volume if( $action == 'hold' ) { $volume = 0; } else if( $action == 'buy' ) { // spend half my money on shares! $volume = floor(($cur['funds']/2)/$cur['price']); } else if( $action == 'sell' ) { // sell half my shares! $volume = floor($cur['shares']/2); } // do a thing! if( $action == 'hold' ) { echo 'W'; } else if( $action == 'buy' ) { echo "B $volume"; } else { echo "S $volume"; } echo "\n"; $cache[] = $cur; if( count($cache) == 50 ) { unlink($cachefile); } // wipe cache on last turn else { file_put_contents($cachefile,json_encode($cache)); } // write cache ``` Run with `php Naivebot.php $1 $2 $3`, makes a `cache.json` in its current folder. [Answer] # Profit - Haskell 1. Wait until the price is 1/maxValue 2. Buy/Sell everything 3. ???? 4. PROFIT!!! --- ``` import System.Environment (getArgs) main = putStrLn . trade . map read =<< getArgs trade :: [Integer] -> String trade [p,m,s] -- not intended | p == 1 = "B" ++ (show m) | p == (fromIntegral $ (maxBound::Int) - 1) = "S" ++ (show s) | otherwise = "W" ``` Compile with `ghc profit.hs` and run with `./profit price money stock`. If it is not efficient enough, add `-O3` flag, although it probably is overkill :D --- ## Edit: "optimised", now sells everything when the price is equal to `Integer.MAX_VALUE`. [Answer] ## WaitForCrash EDIT: fixed flaw in concept EDIT: now using long long int This is my first try. It behaves really simple and keeps one share to distinguish if it is the first round or a later one. In the first round nothing can be lost, so it buys shares. If it has shares it sells them. If eventually share prices drop to 10, it will buy again. ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { long long int share_price = strtoll(argv[1], NULL, 0); long long int money = strtoll(argv[2], NULL, 0); long long int shares_owned = strtoll(argv[3], NULL, 0); if(shares_owned > 1) { printf("S%lld\n", shares_owned - 1); } else if (shares_owned == 0 || share_price == 10) { printf("B%lld\n", money / share_price); } else { printf("W\n"); } return 0; } ``` compile with: `gcc waitforcrash.c -o waitforcrash` run it as `./waitforcrash PRICE MONEY SHARES` [Answer] ## Earthquaker Alternates between buying everything and selling everything (but one). It doesn't really aim to win as much as it does disrupt everyone else. ``` using System; using System.IO; namespace Earthquaker { class Program { static void Main(string[] args) { if (args.Length < 3) return; int stockPrice = int.Parse(args[0]); int money = int.Parse(args[1]); int stocks = int.Parse(args[2]); bool shouldBuy = true; if (stocks != 0) { StreamReader sr = new StreamReader("brain.txt"); if (sr.ReadLine() == "B") shouldBuy = false; else shouldBuy = true; sr.Close(); } if (shouldBuy) Console.Write("B" + (money / stockPrice)); else Console.Write("S" + (stocks - 1)); StreamWriter sw = new StreamWriter("brain.txt", false); sw.Write(shouldBuy ? 'B' : 'S'); sw.Close(); } } } ``` Compile with `csc Earthquaker.cs`. Run with `Earthquaker`. [Answer] # MonkeyTrader (in JAVA) There's a saying that monkeys are good traders. I make the proof. Decisions between "buy" and "sell" are totally random. ``` import java.math.BigInteger; import java.util.Random; public class MonkeyTrader { /** * @param args the command line arguments containing the current * market value, our current money, and our current shares */ public static void main(String[] args) { BigInteger marketValue = new BigInteger(args[0]); BigInteger myMoney = new BigInteger(args[1]); BigInteger myShares = new BigInteger(args[2]); Random random=new Random(); switch (random.nextInt(2)) { case 0: System.out.println("B" + myMoney.divide(marketValue)); break; case 1: System.out.println("S" + myShares); break; } } } ``` [Answer] # IntelliTrader 1st round he will sell his shares if they're a good price: $80 or more. Then he will sell off if the price is the same or better than the last price he sold at, buy if the price is the same or lower than the last price he bought at. IntelliTrader.java ``` import java.io.*; import java.math.BigInteger; import java.util.Properties; public class IntelliTrader { private static final String ROUND_NUM = "roundNum"; private static final String LAST_BUY = "lastBuy"; private static final String LAST_SELL = "lastSell"; private static final String FILE = "IntelliTrader/memory.txt"; private Properties memory; private int roundNum; private IntelliTrader(Properties memory) { this.memory = memory; roundNum = new Integer(memory.getProperty(ROUND_NUM, "0")); } public String evaluate(BigInteger market, BigInteger money, BigInteger shares) { String command = "W"; if (roundNum == 0) { if (market.intValue() > 80) { command = sell(market, shares); } else { command = buy(market, money); } } else { if (market.compareTo(new BigInteger(memory.getProperty(LAST_SELL, "0"))) >= 0) { command = sell(market, shares); } else if (market.compareTo(new BigInteger(memory.getProperty(LAST_BUY, "999999999"))) <= 0) { command = buy(market, money); } } return command; } private String buy(BigInteger cost, BigInteger money) { memory.setProperty(LAST_BUY, cost.toString()); return "B" + money.divide(cost).toString(); } private String sell(BigInteger cost, BigInteger shares) { memory.setProperty(LAST_SELL, cost.toString()); return "S"+shares.toString(); } public static void main(String[] args) { BigInteger marketValue = new BigInteger(args[0]); BigInteger myMoney = new BigInteger(args[1]); BigInteger myShares = new BigInteger(args[2]); Properties memory = new Properties(); try { memory.load(new FileReader(FILE)); } catch (IOException e) { //ignore, file probably doesn't exist yet } int roundNum = new Integer(memory.getProperty(ROUND_NUM, "0")); if (roundNum > 49) { roundNum = 0; memory.setProperty(ROUND_NUM, "0"); memory.setProperty(LAST_BUY, "0"); memory.setProperty(LAST_SELL, "0"); } IntelliTrader it = new IntelliTrader(memory); String command = it.evaluate(marketValue, myMoney, myShares); System.out.println(command); roundNum++; memory.setProperty(ROUND_NUM, ""+roundNum); try { memory.store(new FileWriter(FILE), "IntelliTrader memory properties"); } catch (IOException e) { e.printStackTrace(); } } } ``` Compile with **javac IntelliTrader**. Run with **java -cp "IntelliTrader" IntelliTrader** [Answer] # theAnswerOfLifeIs42.py My program loves the number 42 The rule is simple: I can either buy 42 stock or sell 42 stock. ``` import sys price, money, shares = [int(arg) for arg in sys.argv[1:]] if money>42*price: print "B 42" else: print "S 42" ``` [Answer] ## LeesonLearnt v1.1 (Java, conservative) Since the rule change means that we now start with some shares, there's no longer a guaranteed best first move, so I've simplified this by removing the special case for the first turn. ``` import java.math.BigInteger; public class LeesonLearnt { private static final BigInteger THRESHOLD = new BigInteger("100"); public static void main(String[] args){ BigInteger price = new BigInteger(args[0]); BigInteger capital = new BigInteger(args[1]); BigInteger shareholding = new BigInteger(args[2]); BigInteger affordable = capital.divide(price); // In the long run, the shares will probably lose all their value. // But if they're cheap, buying them will pump them and they can be sold at a profit. // The target amount of our value held in shares varies exponentially with their price. BigInteger targetShareholding = price.compareTo(THRESHOLD) > 0 ? BigInteger.ZERO : affordable.add(shareholding).shiftRight(price.intValue() - 1); if (targetShareholding.compareTo(shareholding) <= 0) { System.out.println("S" + shareholding.subtract(targetShareholding)); } else { BigInteger diff = targetShareholding.subtract(shareholding); System.out.println("B" + diff.min(affordable)); } } } ``` Invoke as ``` java -cp LeesonLearnt LeesonLearnt <price> <capital> <shareholding> ``` [Answer] ## Dollar Cost Averager - Python 3 This strategy attempts to use dollar cost averaging by buying (as close as it can to) a fixed amount of money (arbitrarily set at 150 so that it'll probably use up most of its money by the end) each turn. ``` import sys price, money, shares = [int(arg) for arg in sys.argv[1:]] target_per_day = 150 buy = round(min(target_per_day, money) / price) if buy * price > money: buy -= 1 if buy > 0: print("B" + str(buy)) else: print("W") ``` [Answer] ## Cash Is King - Python 2 or 3 This guy is very pessimistic about the stock market. He'd rather keep his money in cash where he can keep it safe under his mattress. ``` import sys shares = int(sys.argv[3]) if shares > 0: print("S" + str(shares)) else: print("W") ``` [Answer] **Slow and Steady** As long as it has money, it buys $165 worth of shares. Otherwise it sells all of its shares to get more money, to buy more shares. On the 50th round it makes sure to sell all shares, because in the end we want cash. ``` import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.math.BigInteger; import java.nio.file.Files; import java.nio.file.Paths; public class SlowAndSteady{ public static void main(String[] args) { BigInteger price = new BigInteger(args[0]); BigInteger cash= new BigInteger(args[1]); long shares= Long.parseLong(args[2]); BigInteger number = new BigInteger("165"); String count = "0"; try { count = new String(Files.readAllBytes(Paths.get("counter.txt"))); } catch (IOException e) { } int c = Integer.parseInt(count)+1; if (c >= 50) { System.out.println("S" + shares); c=0; } else if(cash.compareTo(number) > 0) System.out.println("B" + (number.divide(price))); else System.out.println("S" + shares); try { Writer wr = new FileWriter("counter.txt"); wr.write(Integer.toString(c)); wr.close(); } catch (IOException e) { } } } ``` Compile with javac SlowAndSteady.java. Run with java -cp "SlowAndSteady" SlowAndSteady. Counter should reset between rounds, but if the file is deleted, it will also work. [Answer] # BuyHighSellLow Tracks the market history and buys when the price low and sells when it's high. ``` import sys storage = 'BuyHighSellLow' turn = 0 turns = 50 max_start_price = 150 limit = 0.25 price = int(sys.argv[1]) money = int(sys.argv[2]) shares = int(sys.argv[3]) # Calculate average price with open(storage+'/history', mode='a') as f: pass # Create file if it doesn't exist with open(storage+'/history', mode='r') as f: values = list((int(line) for line in f)) turn = len(values) + 1 if turn > turns: turn = 1 if turn == 1: average = max_start_price + 1 turn = 1 else: average = sum((value / turn for value in values)) # Buy low and sell high if price < average: print('B' + str(int(limit * money / price))) elif price > average: print('S' + str(int(limit * shares))) else: print('W') # Save history if turn == 1: mode='w' else: mode = 'a' with open(storage+'/history', mode=mode) as f: print(price, file=f) ``` Run with: ``` python3 BuyHighSellLow/buyhighselllow.py ``` [Answer] # Time is Right - Python 3 I got bored so I wrote another entrant... This young entrepeneur lives his life by the clock. When the time is right, he makes a decision. He also annoyingly uses French out of context... ;) ## Run: ``` python3 timeisright.py [arg1] [arg2] [arg3] ``` ## Code: ``` import sys, time price = int(sys.argv[1]) money = int(sys.argv[2]) shares = int(sys.argv[3]) lheure = int(time.time()) if lheure % 3 == 0: print('S'+str(int(shares/4))) elif lheure % 3 == 1: print('B'+str(int(money/4*price))) else: print('W') ``` [Answer] # Ol' Timer - Fortran 77 This old man is going to waste away his pension after sixty years of working as an office clerk. During his old age, however, he became quite blind, so he can only see he first number of each argument, so he estimates the price. His method is similar to that of Walt's, except Ol' Timer is a little more careless. Because of the problems with the Fortran printing, I've written a Python program which will help. The program takes the arguments supplied and pipes them through to the Fortran program. Then, the Python program reformats the output to the expected format. ### Compile: ``` gfortran oltimer.for -o oltimer.exe ``` ### Run: ``` python3 assistant.py [arg1] [arg2] [arg3] ``` ### Python Assistant Code: ``` from subprocess import Popen, PIPE import sys, re ret = Popen('./oltimer.exe '+sys.argv[1]+' '+sys.argv[2]+' '+sys.argv[3], stdout=PIPE, shell=True).communicate()[0].decode('utf-8') value=re.findall(r'\d+',ret) if 'W' in ret:      print('W') elif 'B' in ret:      print('B'+str(value[0])) elif 'S' in ret:      print('S'+str(value[0])) ``` ### FORTRAN Main Code: ``` PROGRAM OLTIMER C DEFINE VARIABLES INTEGER :: PRICE INTEGER :: STOCK INTEGER :: MONEY INTEGER :: INTBUFFER CHARACTER :: BUFFER C GET CMD ARGUMENTS & CONVERT TO INT CALL getarg(1, BUFFER) READ (BUFFER, '(i10)') PRICE CALL getarg(2, BUFFER) READ (BUFFER, '(i10)') MONEY CALL getarg(3, BUFFER) READ (BUFFER, '(i10)') STOCK C EVALUATE SITUTATION AND MAKE DECISION IF (PRICE.LT.5) THEN IF (MONEY.GT.0) THEN INTBUFFER=(MONEY*50)/(5-PRICE) PRINT*,'B',INTBUFFER ELSE PRINT*,'W' END IF ELSE IF (PRICE.GT.9) THEN IF (STOCK.GT.0) THEN INTBUFFER=STOCK/(PRICE-9) PRINT*,'S',INTBUFFER ELSE PRINT*,'W' END IF ELSE PRINT*,'W' END IF END IF END PROGRAM ``` [Answer] # Test1 Trader ``` public class Test1 { public static void main(String[] args){ int marketValue = Integer.parseInt(args[0]); int myMoney = Integer.parseInt(args[1]); int myShares = Integer.parseInt(args[2]); //Buy 10 if we don't have any. if(myShares <= 0){ System.out.println("B10"); }else{ System.out.println("S1"); } } } ``` Compile with `javac Test1.java` run with `java -cp "Test1" Test1` [Answer] # Hedgehog - python2.7 *This is mostly to reserve the name* ``` from __future__ import print_function from sys import argv storage = 'prices.txt' price,cash,shares = map(long, argv[1:]) turn = 1 buy = lambda x: print('B%d' % long(x)) sell = lambda x: print('S%d' % long(x)) cashtoshares = lambda c: long(c/price) TURN,PRICE,CASH,SHARES=range(4) try: data = [map(long, line.split()) for line in open(storage)] if data: turn = data[-1][TURN] + 1 except IOError: pass with open(storage, 'a') as pricelist: pricelist.write('%d %d %d %d\n' % (turn, price, cash, shares)) if turn == 1: buy(cashtoshares(cash)) # convert all cash into shares elif price == 1: buy(cashtoshares(cash)) # cannot buy at a better deal elif price < 10: buy(cashtoshares(cash/2)) elif shares < 10: buy(cashtoshares(cash/2)) else: sell(shares/2) ``` Run as ``` python hedgehog.py PRICE CASH SHARES ``` [Answer] ## BuyAndSell - C Similar but not a duplicate of Tommy. Alternates between panic buying as much as possible and selling everything. Almost a duplicate of Earthquaker which retains one share while BuyAndSell sells all shares. BuyAndSell takes no action when it has no shares to sell but hasn't got enough money to buy one share. ``` /* BuyAndSell * Code revised from OptoKopper's WaitForCrash.c and my BuyAndHold.c * Alternates between buying as many shares as possible and selling everything * Run it as ./buyandsell PRICE MONEY SHARES */ int main(int argc, char *argv[]) { long long int share_price = strtoll(argv[1], NULL, 0); long long int money = strtoll(argv[2], NULL, 0); long long int shares = strtoll(argv[3], NULL, 0); if (money >= share_price) { printf("B%lld\n", money / share_price); } else { if (money == 0) { printf("S%lld\n", shares); } else { printf("W\n"); } } return 0; } ``` Compile with "gcc buyandsell.c -o buyandsell" Run as "./buyandsell PRICE MONEY SHARES [Answer] # Gorge Soros ``` price = ARGV.shift money = ARGV.shift stock = ARGV.shift if price*10<money puts "B10" else puts "S#{stock}" end ``` Buys slowly, than sells everything in an attempt to crash the market. Run with:`Soros.rb price money stock` ]
[Question] [ A [narcissistic number](https://en.wikipedia.org/wiki/Narcissistic_number) is a natural number which is equal to the sum of its digits when each digit is taken to the power of the number digits. For example \$8208 = 8^4 + 2^4 + 0^4 + 8^4\$, so is narcissistic. We'll define a function \$f(x)\$ as the following, for a natural number \$x = d\_1d\_2\dots d\_n\$, where \$d\_i\$ is a single digit \$0\$ to \$9\$ (therefore \$x\$ has \$n\$ digits): $$f(x) = \sum\_{i=1}^nd\_i^n$$ In this case, a number is narcissistic if \$f(x) = x\$. However, when we apply \$f(x)\$ to a number repeatedly, we find an interesting pattern emerges. For any given \$x\$, the sequence either reaches a fixed point (i.e. a narcissistic number), or enters a fixed loop which repeats infinitely. For examples, take the three integers \$x = 104, 127, 370\$: * \$x = 104\$: Repeated application of \$f(x)\$ leads to the following chain $$104, 65, 61, 37, 58, 89, 145, 190, 730, 370, 370, ...$$ Here, the loop eventually reaches a fixed point, \$370\$. * \$x = 127\$: Repeated application of \$f(x)\$ leads to $$127, 352, 160, 217, 352, 160, 217, ...$$ Here, the triple \$352, 160, 217\$ repeats ad infinitum * \$x = 370\$: \$x\$ here is already narcissistic, so the chain will just be an endless stream of \$370\$s. These examples document the two possible outcomes for a given \$x\$. By treating a fixed point as a loop of length \$1\$, we now arrive at the task at hand: Given a natural number \$n > 0\$, output the length of the loop that arises through repeated application of \$f(n)\$. The above three examples return \$1\$, \$3\$ and \$1\$ respectively. You can assume that all \$n\$ eventually enter a loop, which appears to be the case for at least all \$n < 10^4\$. If there exists an \$n\$ for which this is false, your program may do anything short of [summoning Cthulhu](https://codegolf.stackexchange.com/questions/128784/find-the-highest-unique-digit/214724#comment317467_128784). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins. The vast majority of numbers return \$1\$. However, these two arrays contain all \$n < 1000\$ which don't, along with what their outputs should be: ``` [ 59, 95, 106, 115, 127, 136, 138, 147, 149, 151, 157, 159, 160, 163, 168, 169, 172, 174, 175, 177, 178, 179, 183, 186, 187, 189, 194, 195, 196, 197, 198, 199, 217, 228, 229, 235, 238, 244, 245, 253, 254, 255, 258, 259, 267, 268, 271, 276, 277, 279, 282, 283, 285, 286, 289, 292, 295, 297, 298, 299, 309, 316, 318, 325, 328, 335, 352, 353, 355, 357, 358, 361, 366, 367, 369, 375, 376, 381, 382, 385, 388, 389, 390, 396, 398, 405, 408, 417, 419, 424, 425, 442, 445, 447, 450, 452, 454, 456, 457, 459, 465, 466, 468, 469, 471, 474, 475, 477, 478, 479, 480, 486, 487, 488, 491, 495, 496, 497, 499, 504, 507, 508, 511, 517, 519, 523, 524, 525, 528, 529, 532, 533, 535, 537, 538, 540, 542, 544, 546, 547, 549, 552, 553, 555, 556, 558, 559, 564, 565, 567, 568, 570, 571, 573, 574, 576, 580, 582, 583, 585, 586, 589, 591, 592, 594, 595, 598, 601, 607, 609, 610, 613, 618, 619, 627, 628, 631, 636, 637, 639, 645, 646, 648, 649, 654, 655, 657, 658, 663, 664, 666, 669, 670, 672, 673, 675, 678, 679, 681, 682, 684, 685, 687, 689, 690, 691, 693, 694, 696, 697, 698, 699, 705, 706, 708, 712, 714, 715, 717, 718, 719, 721, 726, 727, 729, 735, 736, 741, 744, 745, 747, 748, 749, 750, 751, 753, 754, 756, 760, 762, 763, 765, 768, 769, 771, 772, 774, 777, 778, 779, 780, 781, 784, 786, 787, 788, 791, 792, 794, 796, 797, 799, 804, 805, 807, 813, 816, 817, 819, 822, 823, 825, 826, 829, 831, 832, 835, 838, 839, 840, 846, 847, 848, 850, 852, 853, 855, 856, 859, 861, 862, 864, 865, 867, 869, 870, 871, 874, 876, 877, 878, 883, 884, 887, 891, 892, 893, 895, 896, 900, 903, 906, 914, 915, 916, 917, 918, 919, 922, 925, 927, 928, 929, 930, 936, 938, 941, 945, 946, 947, 949, 951, 952, 954, 955, 958, 960, 961, 963, 964, 966, 967, 968, 969, 971, 972, 974, 976, 977, 979, 981, 982, 983, 985, 986, 991, 992, 994, 996, 997, 999] [ 3, 3, 3, 3, 3, 2, 10, 14, 10, 3, 10, 14, 3, 2, 14, 10, 3, 14, 10, 2, 10, 2, 10, 14, 10, 10, 10, 14, 10, 2, 10, 10, 3, 10, 3, 3, 3, 2, 2, 3, 2, 10, 10, 10, 14, 10, 3, 14, 10, 14, 10, 3, 10, 10, 10, 3, 10, 14, 10, 10, 14, 2, 10, 3, 3, 2, 3, 2, 10, 10, 10, 2, 10, 10, 14, 10, 10, 10, 3, 10, 14, 6, 14, 14, 6, 10, 14, 14, 10, 2, 2, 2, 3, 14, 10, 2, 3, 10, 3, 10, 10, 10, 14, 10, 14, 14, 3, 14, 10, 10, 14, 14, 10, 10, 10, 10, 10, 10, 10, 10, 14, 10, 3, 10, 14, 3, 2, 10, 10, 10, 3, 2, 10, 10, 10, 10, 2, 3, 10, 3, 10, 10, 10, 10, 10, 14, 3, 10, 10, 14, 10, 14, 10, 10, 3, 14, 10, 10, 10, 14, 10, 10, 14, 10, 10, 3, 10, 3, 3, 10, 3, 2, 14, 10, 14, 10, 2, 10, 10, 14, 10, 10, 14, 10, 10, 10, 14, 10, 10, 10, 14, 10, 3, 14, 10, 14, 2, 10, 14, 10, 14, 10, 2, 6, 10, 10, 14, 10, 10, 10, 6, 2, 14, 3, 14, 3, 14, 10, 2, 10, 2, 3, 14, 10, 14, 10, 10, 14, 14, 3, 14, 10, 10, 14, 10, 10, 3, 14, 3, 14, 10, 14, 2, 10, 2, 10, 14, 6, 14, 14, 14, 10, 10, 2, 14, 14, 2, 14, 10, 10, 14, 3, 14, 10, 14, 10, 14, 10, 10, 10, 3, 10, 10, 10, 10, 3, 10, 14, 6, 14, 14, 10, 10, 10, 10, 10, 14, 10, 10, 14, 10, 14, 10, 2, 6, 14, 10, 10, 2, 14, 14, 14, 10, 14, 10, 10, 6, 10, 6, 14, 14, 10, 10, 14, 10, 2, 10, 10, 3, 10, 14, 10, 10, 14, 14, 6, 10, 10, 10, 10, 10, 14, 10, 10, 3, 10, 10, 10, 14, 10, 10, 10, 6, 2, 2, 14, 10, 10, 14, 3, 10, 10, 6, 10, 6, 10, 10, 10, 2, 3, 2] ``` Furthermore, [this](https://tio.run/##y0rNyan8/99Fy0cl@FjXsTVc1ofbH@5cdbjd59gm60cNc2tg/GNdmu7///83NDAAAA) is a program which takes an integer \$n\$ and, for each integer \$1 \le i \le n\$, generates it's output and the loop that arises. [This](https://math.stackexchange.com/q/3896749/427632) is a question over on Math.SE about whether the output ever exceeds \$14\$, and if each natural number will eventually go into a loop or not. [Answer] # [Haskell](https://www.haskell.org/), 85 bytes ``` l=length k?x|elem x k=l$x:takeWhile(/=x)k|q<-show x=(x:k)?sum[read[k]^l q|k<-q] ([]?) ``` [Try it online!](https://tio.run/##BcGxDsIgEADQvV/B0AGGRuum6YXPcCCYkHgVcgdKwcjAv@N73hVC5jEYGNOr@ol068gYRRMEPFdHePeBUZ6gKep5W4p//0QD2W6kdPlGc6B7GrIPFrnTtmQ77SCN1WpEFxJ8jpDqvIt1vZ4v4w8 "Haskell – Try It Online") This is frustratingly long for Haskell. We have one main function here. It keeps track of a list `k` of numbers we already visited, appending new numbers to the front. Once we reach a number `x` which is on our list we return one more than the largest prefix not containing `x`. ``` k ? x | elem x k = length (x : takeWhile (/=x) k) | otherwise = (x : k) ? sum [ read [x] ^ length (show x) | k <- show x ] ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~107~~ \$\cdots\$ ~~90~~ 84 bytes Saved a byte thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! ``` f=lambda n,l=[]:n in l and-~l.index(n)or f(str(sum(int(d)**len(n)for d in n)),[n]+l) ``` [Try it online!](https://tio.run/##dZbdbttGEIXv9RRsbiymjMH9nRkDKtAn6E3vXCNwLToRQlOGKKNJDffV3Y/6s0QriY@0HM7unHNmRPDxx/rrsguvr/ez9vbh7/lt0VXt7PrmqisWXdEWt93803/t5aKbN9@nXblcFffTfr2a9k8P00W3ns7Ljx/bpuPWPffmw6auLKvr7ubXtnxdN/36cze7TlZZqlydK@f49lK5wDpo5SLraJVLDrAm1eUaBMD9zLV4EAF7hRwhLsSVHOUcJaZcGzlDHSNmxIw8s8o7qbxXwDokwDpGwDoFwDoNa@LU95l8antxIAOuqefVA/KVXOp6anojRk1PPU89T71QA5eBVsEnwDd1Q/IggGEtgHh2gFxqBrQGNAZqBiVOvUCtoORRK1gNuEedWCfAN9qisyr6CIhFD4Zv4qkGXKMvpgyGGLmZ@9SMaIzUjOiM@BupHdEa8TeiNyr70RnxN8IhGnlojXCI6I1oTXUEArRKzgHW8Ek@AO7BKaE/4X0KHhDHixTIow8p1oA4/UgxA@LMQ4J3wquEVwnuCa8S3FMmD/4JvxL8k7Af/knIRUPCuwTvhHeJXiX8SzrE2Av/RL8Sc5LQkfAx1w4IsCq7GgRAHA2ZOc1wz4Ec5jXDOQfi@JvhmiP34JrxN8Mz42@GZ2Z2MzwzHmf8zXDMzHCGY8bjjL8ZfzM9zvDMSi48Mz5neGb6nOGajXy4ZvzO@J0Hvngu9F74LQmei/MgAmJ4L26IkeMdIAcNgveC54IGicTxWtAgeC1oEDQIsyL8BgXPBT2C58LvUDLno0fwXPBb0CP4LegR/BbmRdAj6BF8FzQJegTPBT3C3AhaBN8FLYIWQYugQ5kdRYviv@K78ptRN6y55z0gxvwoOhQNSh@UGVK0KLOj9EKZH6UXihZFi6JDmR1Fh9ITRYcyN8rvTNGi9EXRosyPokXpjaJH0aLMjqJH0aPMjqJD0aDwV/gr/VDmRtFgdQ0CYI3/hv/mhrUABTzy0GDwN3pgzJGhwQL76IPB3@iF0QeDv8Hf4vCYJAZ/owcGf2OejD4Y/I0@GPyNuTL4Wx7usQf@Rj8MDYYGQ4PRD6MXxnwZWoz5MnpiaDG0GL2wQQe9MLObSfP9sblbN/PZNQ@o3X8euzyJ4/AZdstNcB/ZfPvDx/Z69/d2b797f6Y/nFyfnB/H1erjwodkvz9rdI4/Oe90c95EN9/1brnZsSWzvwqj0m@M4hu/o/3n/97b9cbGn6SeqVgf9o0p1Ccu1WNXRj7vq8X3vXi/6@z6qCF@zMTvjDzdl7cFw7Fd/qAzvqv9ztQ3iePiftTHQ7bfXfmTk0bl3g3Ez8bjbCvPaR@XHxXKu484PsL/bKgPs3mufDjfp7wZ35Huk/rHg@ZvJsPbWD977q6aYnhZ66pmeF37d/E43b6nVftnQPkyufva3H1rVrPpxV9PXuLdRbVZuHBRTm7b9vOX5XI@@3P11Ew2Rw0HrW67L83UVYWra1deTQr@9bPt6yLvhJvrZrYhwethsbjfbtvWLpq2bwq3SXpcDW@W9xfP3Uvx6bfiuX8pnnd8rvvZrLl5udiediCyXwyvq8WQMuH0ffDq6NAPv7dtseiLf5q2/aW4KsvyQzkZSp8k/bF87Kuif1o17Y@iXz40xcOiX99@ay4vL4ur6Yfy9X8 "Python 3 – Try It Online") Expects input as a string. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes I wonder if this is the same as caird's answer (it probably isn't, because the control flow here almost certainly can be simplified by anyone who actually *knows* Jelly, or perhaps even by a good lossless compression utility). This may also be wrong. ``` D*L$S ÇÐLÇƬL ``` [Try it online!](https://tio.run/##y0rNyan8/99Fy0clmOtw@@EJPofbj63x@f//v6GpJQA "Jelly – Try It Online") [Answer] # [Raku](http://raku.org/), ~~67~~ ~~65~~ 64 bytes ``` {{$_-1-.first(:k,.tail)}($_,{sum .comb X**.chars}...{%\{$_}++})} ``` [Try it online!](https://tio.run/##DYvLCoMwFER/ZRBbfAZvfVRL9Tu6KIgVQ6WKJbELCfn29C4OcxhmvpNaKrceOEu0zhi/TykVclZ6D26fROzDvIQ28PvE6N8KMW7rC48oEuN7UNoKIczpyS8bxza0Tg8HPL9H28FIcO1Bbgr3skFTgrIKRJyXKyhnz2tQwV40oJIYdp5SlTE5U3fuDw "Perl 6 – Try It Online") * `$_, { ... } ... { ... }` generates the sequence of numbers, starting with `$_`, the argument to the outer function. The first braces enclose the function that generates successive elements, and the second braces enclose the function that indicates when to stop. * `sum .comb X** .chars` produces the next number from the preceding one. The `comb` method with no arguments splits strings/numbers into their characters/digits. The `chars` method returns the number of characters/digits in a string/number. The list of digits is cross-exponentiated with the number of digits by the `X**` operator, then summed. * The ending condition uses an anonymous state hash variable `%`, which stores the number of times each element has been seen so far. The iteration stops when the current number has been seen for a second time. * That sequence is fed into an inner anonymous function, which is called immediately. (This is a bit shorter than storing the sequence into a variable.) Just like the outer function, this inner function accepts its argument in the `$_` variable. * `.first(:k, .tail)` finds the index (thanks to the `:k` adverb) of the first element of the sequence which is equal to the final element, returned by `.tail`. * `$_ - 1 - .first(...)` is the length of the sequence, minus one, minus the first index of the single repeated element, giving the length of the final cycle. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~78~~ 73 bytes -5 thanks to J42161217. His answer is better, so check that out too. ``` #[]//.a_@e___/;a!=e:>a~Tr[#^#2&@@RealDigits@a]~e/.a_@e__:>{e}~Position~a& ``` [Try it online!](https://tio.run/##Ncq9CsMgEADgPW9RAplsjR0TFIcs3ULpdlzlKGoP8gOJW4ivbqd@8zdT@vqZEn@oBF1qQClv5Kx3zsmeLtp3hvJrg/pd3xtrn56mgSOn3RJm/7@dOfyZx3XnxOuSqSnDClXUwXJfPQJEACUUolFi3HhJwFcTEStxsFBt255Yfg "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 12 bytes ``` LUṠ-U¡λṁ^L¹d ``` [Try it online!](https://tio.run/##AR8A4P9odXNr//9MVeG5oC1VwqHOu@G5gV5Mwrlk////MTM4 "Husk – Try It Online") Found a better way to do it by removing the longest unique prefix from the infinite list, and taking the longest unique prefix of that. # [Husk](https://github.com/barbuz/Husk), 14 bytes ``` ▼mLUmUṫ¡λṁ^L¹d ``` [Try it online!](https://tio.run/##ASMA3P9odXNr///ilrxtTFVtVeG5q8KhzrvhuYFeTMK5ZP///zEzOA "Husk – Try It Online") Basically, we make an infinite list of infinite lists in order to find which one contains the required cycle. Then we take the length of the cycle. ## Explanation ``` ▼mLUmUṫ¡λṁ^L¹d ¡λ apply the following to get an infinite list d take the digits ^L¹ the the power of their length ṁ sum them ṫ get the postfixes of the list mU get the logest unique prefix of each postfix U get the longest unique prefix of that mL Map each cycle to it's lenght ▼ take the minimum ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~202~~ ... 149 bytes ``` f(l){long a[16]={},i,k=l,n;for(;i=k;a[n++&15]=k){for(l=0;k;k/=10)l++;for(;i;i/=10)k+=__builtin_powi(i%10,l);for(l=16;l--;)if(a[l]==k)return n-l&15;}} ``` [Try it online!](https://tio.run/##LY3BbsIwEETP4Su2SKls2RH2oRy6@EtCFIVQo5W3DoqCOET@9mDTnmZ35s3u2NzGcdu8YLnyFG8wtPbYuTVp0sGxjuinWSC5gEMblfq0X50Lci0uO4MBw8FZI1mpfxLpbQTl@v7yIF4o9vfpSYJqazRL/KvaI3LToCQvhpY7l4/OP8tjjhAbzl8wpY3iAr8DRSFh3VWlVxwCBxaznLIaY/Ko1JuoSsw59oIklt2DYPjInMxbdZ8z4MW@vn5DfT3HvQbSwAVNu7S9AA "C (gcc) – Try It Online") ## Explained ``` f(l) { long a[16] = {}, // Circular buffer of recently seen values i, // Current value, will be initialized to l, // l will become number of digits in i, // and will later be used as a loop counter k = l, // Will become f(i) n; // Current index into the circular buffer for (; i = k; // Loop forever, let i = f(i) a[n++ & 15] = k) { // Store f(i) in the buffer for (l = 0; k; k /= 10) // Set length to zero, loop over all digits in k (which is equal to i) l++; // Increment l for each digit // k is zero after this loop for (; i; i /= 10) // Loop over all digits again k += __builtin_powi(i % 10, l); // Add pow(digit, length) to k for (l = 16; l--;) // Check all the values in the buffer if (a[l] == k) // If k matches a value in the buffer return n - l & 15; // Return the distance between k and the match in the buffer } } ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~70~~ 59 bytes ``` Gather@NestList[Tr[#^#2&@@RealDigits@#]&,#,#]~Count~{_,__}& ``` [Try it online!](https://tio.run/##FcfBCsIwDADQjwn0VLHz7ggoeBGR6a3UEkaoha1Cm52G@/WI7/ZmkjfPJHkkTUe9/Fvxxk2uuYl/Vg8vOBjEgWk655SlIQRjwULYTp@lyLZGG@PX6L3mIh52ffIQgtnjgycexQ9UEmPnnLMJoe9MUP0B "Wolfram Language (Mathematica) – Try It Online") -11 bytes from @att [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes ``` NθW¬№υθ«⊞υθ≔ΣX↨θχLθθ»I⊕⌕⮌υθ ``` [Try it online!](https://tio.run/##Jc3NCoMwEATgs3mKHHfBQoVCD55aoSAUkfYJUl1MQDc1P3ooffbU4nFgvplOK9dZNaZU8zuGJk4vcjBjKVZtRpLQ2ACVjRwg5nJGRPkRWRu93nMpsov3ZmB4xglau276qjzBnMviiLm8Ew9Bw1/u/a9ondnmKuUD1Nw5mogD9XAz3MODFnIbj7i/YZlScTqnwzL@AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` W¬№υθ« ``` Repeat until a loop is detected. ``` ⊞υθ ``` Save the previous value. ``` ≔ΣX↨θχLθθ ``` Compute the next value. ``` »I⊕⌕⮌υθ ``` Output the number of terms in the loop. [Answer] # JavaScript (ES7), 72 bytes Expects the input number as a string. ``` n=>(g=i=>i-g[[...n].map(d=>t+=d**n.length,t=0)|t]||g(-~i,g[n=t+'']=i))`` ``` [Try it online!](https://tio.run/##FcxNDoIwEAXgvafowsRWoaEiKDHDzhO4JCQ0/NQanBJo3IheHZnNl3nJe/PUbz3Vox18iK5plw4WhJwbsJDb0BSFlBJL@dIDbyD3B2j2e5R9i8Y/Ag@RmH05z4aHPxuYAsEfdrsSrBBVtVwLlmQBy5KAqShdUXQdzysxxfiycqJ4WmsqUQRFWqk0ImKCeil9yrJyIzs33nT94MggZ7XDyfWt7J3hlebbD34FA7b9dByld3c/WjRciG8lxPIH "JavaScript (Node.js) – Try It Online") ### Commented ``` n => ( // n = input number as a string g = i => // g is a recursive function taking a counter i i - // subtract from i g[ // lookup in g: [...n].map(d => // for each digit d in n: t += // add to t: d ** n.length, // d raised to the power of the length of n t = 0 // starting with t = 0 ) | t // end of map(); yield t ] // end of lookup in g || // if the above result is NaN, g( // do a recursive call: -~i, // pass i + 1 g[n = t + ''] = i // copy t to n, coerced back to a string // and set this entry to i in g ) // end of recursive call )`` // initial call to g with i zero'ish ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 27 bytes ``` {tgjlᵗgᵗz^ᵐ+}ᵃ↖N{¬≠&}↔a↰₄bl ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSu9qhtw6Ompoe7Omsfbp3wv7okPSvn4dbp6UBcFQcU0QYKNz9qm@ZXfWjNo84FarWP2qYkgvW0JOX8/x@tYGigo2BqqaOgYGmqA@SYAQlDEMvIHEgYg7jGFkDCBMQ1AaozNDUEESCuqWUsAA "Brachylog – Try It Online") ``` {tgjlᵗgᵗz^ᵐ+}ᵃ↖N{¬≠&}↔a↰₄bl { }ᵃ↖N repeat the predicate N times and accumulate results tg last result as list [x] jlᵗgᵗ [x, [len(x)]] z^ᵐ each digit ^ length + sum {¬≠&} must have duplicates (not all are different) ↔a reverse and take prefixes (shortest first) ↰₄ that must have duplicates bl length - 1 ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 19 bytes ``` `XIvIFYAtn^syy-]=Pf ``` [Try it online!](https://tio.run/##y00syfn/PyHCs8zTLdKxJC@uuLJSN9Y2IO3/f0MTcwA "MATL – Try It Online") Or [plot the sequence](https://matl.suever.net/?code=vXJx%22%40%0A%60XIvIFYAtn%5Esyy-%5D%3DPf%0AJwhXJx%5D%0AGJ3%243YH&inputs=50%3A170&version=22.3.0) from `50` to `170` (it takes about 30 seconds). ### Explanation ``` ` % Do...while XI % Copy into clipboard I. This implicitly takes input the first time v % Concatenate stack contents vertically. This attaches the newly computed % term onto the sequence. The first time it does nothing I % Paste from clipboard I. This pushes the last computed term FYA % Convert number to vector of decimal digits tn^s % Duplicate, number of elements, element-wise power, sum. This computes a % new term to extend the sequence yy % Duplicate top two elements in the stack: sequence so far and new term - % Element-wise difference. This is truthy if all values are nonzero ] % End. A new iteration is run if top of the stack is truthy = % (The stack contains the computed sequence and a new term that has been % found to appears in that sequence) Element-wise equality comparison P % Reverse f % index of true value. Implicitly display ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` D*L$SƊƬ⁺€ṪL ``` [Try it online!](https://tio.run/##y0rNyan8/99Fy0cl@FjXsTWPGnc9alrzcOcqn/@H24GsyP//FUwtdRQULE11FAwNzICEIYhlZA4kjEFcYwsgYQLimgDVGZoagggQF6TN0MwARBiDCJA6M5CYuRGIMAERIKPMQYrNQbLmQFkjoAYjoBlGRgA "Jelly – Try It Online") ``` D Take the decimal digits * to the power of L the length of $ the list of decimal digits S and sum them. Ɗ For all that, Ƭ iterate until a loop is reached collecting all intermediate results, € then for each of the collected results ⁺ iterate again starting from there, Ṫ take the results from the last result, L and get the length of that. ``` Can be even shorter if we take input as a digit list: # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` *LSDƲƬ⁺€ṪL ``` [Try it online!](https://tio.run/##y0rNyan8/1/LJ9jl2KZjax417nrUtObhzlU@/10Ot6sA2ZH//yuYWuooKFia6igYGpgBCUMQy8gcSBiDuMYWQMIExDUBqjM0NQQRIC5Im6GZAYgwBhEgdWYgMXMjEGECIkBGmYMUm4NkzYGyRkANRkAzjIwA "Jelly – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Turns out I got the same as [Unrelated String](https://codegolf.stackexchange.com/a/214872/53748). ``` D*L$SƊƬ⁺€ṪL ``` A monadic Link accepting a positive integer which yields a positive integer. **[Try it online!](https://tio.run/##ASAA3/9qZWxsef//RCpMJFPGisas4oG64oKs4bmqTP///zE1OQ "Jelly – Try It Online")** ### How? ``` D*L$SƊƬ⁺€ṪL - Link: n Ƭ - collect while distinct: Ɗ - last three links as a monad: D - digits $ - last two links as a monad: L - length * - exponentiate S - sum € - for each: ⁺ - repeat the last link (the collect-while-distinct, above) Ṫ - tail (this will be a single loop) L - length ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes ``` Δ¤SDgmO©ªÙ}R®k> ``` [Try it online!](https://tio.run/##ASQA2/9vc2FiaWX//86UwqRTRGdtT8KpwqrDmX1Swq5rPv//WzE2OF0 "05AB1E – Try It Online") Takes input as a singleton list containing the integer. A different approach that comes in at 16 bytes: ``` λSDgmO}ηíεćk}Ù¥н ``` [Try it online!](https://tio.run/##ASQA2/9vc2FiaWX//867U0RnbU99zrfDrc61xIdrfcOZwqXQvf//NTk "05AB1E – Try It Online") **Commented**: ``` Δ¤SDgmO©ªÙ}R®k> # implicit input: [x] Δ } # run until the output does not change: ¤ # take the last integer from the list S # split into digits D # duplicate g # take the length of the copy m # take each digit to the power of the length O # sum all powers © # store this value in the register ª # and append it to the list Ù # uniquify the list # the loop only stops if Ù removed the new element, # which only happens if it was in the list already R # reverse the (unique) list ® # take the last computed value k # find the 0-based index in the list > # and increment it λSDgmO}ηíεćk}Ù¥н # implicit input: x λ } # recursively apply the code to the input # to generate an infinite list SDgmO # same as above η # take the prefixes í # reverse each prefix ε } # map over the reversed prefixed ć # extract the first element k # find its index in the remaining prefix # this returns -1 if the prefix was unique # this results in [-1, ..., -1, res-1, res-1, ...] Ù # uniquify => [-1, res-1] # while this list is finite, 05ab1e does not know this ¥ # take the differences => [(res-1) - (-1)] = [res] н # take the first element => res ``` [Answer] # [APL (dzaima/APL)](https://github.com/dzaima/APL), ~~30~~ 29 bytes ``` {1⊃⍸⌽(⊢/=⊢){+/(⊢*≢)10⊤⍵}⍡⍵⊢⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pSszMTfz/qG@qp/@jtgkG/9OAZLXho67mR707HvXs1XjUtUjfFkhoVmvrgzhajzoXaRoaPOpa8qh3a@2j3oVACigM4oBMAepOUzC1/A8A "APL (dzaima/APL) – Try It Online") -1 byte using `⎕IO←0`. Since the length of the cycle never exceeds \$n\$, we can loop n times instead of finding a fixed point, then calculate the length of the cycle. ## Explanation ``` {⊃⍸1↓⌽(⊢/=⊢){+/(⊢*≢)10⊤⍵}⍡⍵⊢⍵} ⊢⍵ input integer n { }⍡⍵ apply the following n times, collecting intermediate results: 10⊤⍵ get base 10 digits (⊢*≢) raise to the power of length +/ and sum (⊢/=⊢) bit mask of the locations of the last element 1↓⌽ reverse and remove first 1 ⊃⍸ first index of the last element ``` [Answer] # [Icon](https://github.com/gtownsend/icon), 99 bytes ``` procedure f(n) t:=table() i:=1 until\t[n]do{t[n]:=i (s:=0)+:=!n^*n&\z n:=s i+:=1} return i-t[n] end ``` [Try it online!](https://tio.run/##VY/fqsIwDMbv8xSxF9J6NmhVGBTqi/gH1HUQmKnU7hyO4rNrpwPddxPy/ZIvhI6BH49zDEdfd9FjI1lBsi7tD62XCsg6Ax0najdpzds63PpiHYG8WKfVj3UT3s14urkCW3cByo65Q/Spi4xU9uPguf66cdoT52jM@ouUvDR6WQgsVyiKpm/UCM6rLzivRnBR6Q/MzQiKcpB4u/7Xx3/sP8IU0GitsQ54e7GsRpJaGZwO21SIIZeG1Du8HnkC "Icon – Try It Online") [Answer] # [Red](http://www.red-lang.org), 125 bytes ``` func[n][m: copy #()i: 1 while[not m/:n][put m n i i: i + 1 s: 0 foreach d k: to""n[s:(-48 + d)**(length? k)+ s]n: s]i - m/:n] ``` [Try it online!](https://tio.run/##PYzLCoMwFAXX9SsOduMDqbaC5W76D90GF8UkNag3EiOlX58GCm4OAzMcp2R4Kin6RFPQOw@Ce7EQBrt@cc5yQ2hOn9HMSrD1WC4U/bpHAsMgaoMSDTZCnWjr1GsYITERvE1TFhtlVXuPicyLIpsVv/34wJSX2HqmOAbV/zWszrCHRlO3ycHX7uBbV4cf "Red – Try It Online") [Answer] # Scala, 117 bytes Port of Wheat Wizard's [Haskell answer](https://codegolf.stackexchange.com/a/214864/95792). ``` def>(n:Any,k:Seq[_]=Nil):Any=if(k toSet n)1+k.indexOf(n)else>(s"$n".map(d=>math.pow(d-48,s"$n".size).toInt).sum,n+:k) ``` [Try it online!](https://scastie.scala-lang.org/rGFG3DIiRHKsmkj23VvCdw) # Scala, 160 bytes ``` Stream.iterate(_){n=>s"$n".map(d=>math.pow(d-48,s"$n".size).toInt).sum}.scanLeft(Seq[Int]())(_:+_).flatMap(_.tails).find(l=>l.size>1&&l.head==l.last).get.size-1 ``` [Try it online!](https://scastie.scala-lang.org/ysthakur/yMNczRpGSYunrPUN9CFq4A/64) A ridiculously long solution, made worse by the fact that Scala doesn't have `**` like Python and other languages do, and `inits` returns the biggest inits first, so we have to use `scanLeft(Seq[Int]())(_:+_)`. [Answer] # [R](https://www.r-project.org/), 84 bytes ``` x=scan();while(!(y=match(x,F,0))){F=c(x,F);x=sum((x%/%10^((z=nchar(x)):0)%%10)^z)};y ``` [Try it online!](https://tio.run/##rY5BasMwEEX3OsWUYJgBk0p0U2yUZU7QXUlATGUsKktGkqmdkLM79iI36PJ//ue9tK6zzmwCUvvXO2/xDRc9mMI9zvW5lkR0P2veA7XbdBoQ5@q9UvKKeNOBe5NwJmokVVtJ1xs92mVVH59CHODHdi5YMBm6KXBxMUCJwL3lXxgmX9zoLRSbC7DJNjciDfi1kUQwiX2Mo379NsZd/KOheOx@xnvYUS5nl4tj2JkZTgq6mCCAC6CORyVlI9DobMbRL6iarZD1S5Ho25zUZX0C "R – Try It Online") **Commented:** ``` x=scan(); # get input as x # F is vector that holds values of f(x) so far # (initialized by default as zero) while(!(y=match(x,F,0))){ # if x is present in F, get its matching index as y, # otherwise set y to zero. # While !y (x not present in F yet): F=c(x,F); # prepend F with x x=sum((x%/%10^((z=nchar(x)):0)%%10)^z) # update x as f(x): # sum of decimal digits to the power of # digits }; y # We exit the while loop when F contains x; # at this point, y gives the index, which is the # loop length ``` [Answer] # [J](http://jsoftware.com/), 40 bytes *-5 by FrownyFrog!* ``` 0(i.~~:@|.)(,*/@~:$1#.&(^#)10#.inv{:)^:_ ``` [Try it online!](https://tio.run/##lZRNj9xEEIbv@ytaWZTMoInpr/oyQopA4hRx4BopHFBWCQe4cSHav774cRCz67U9k8O8mnZVt@upt9p/PLwYXt2lH8b0Kp1STuP0ez2kn359@/NDPnwa7u/HN5@H4@H07Xdv7sdvyu3w8vD@9ljy7fDpz7//GY/vx98ejje//Dikd@PtcP9uvB9fDp@Hw2kt9TCfwp6bmw@/f/wrHb6/O6bS7b/V4e5FPiaJU0ohp1SyTlL4V22SxrL5iR3IlFekICzZVjQjDSFPeWYV6QhHGclG1Ig6yc7JTsB5FiTPFQSBIBDsiClay7Ss1RGWTRCWvSMspSEsZV4Spb6q7KW0agVRhGfUUr0i7HW2UVWloBoEKKhSS6WWSi0tI0WR6VmrgvCPqppUpCHz0hCiWhC2UVCjTY3mNApqTpRaGmU0ZwdltMgIKVTQsyD8oyW9TCm9doRAr8j8j6hkhGf0pYsic4BtSh4FdZrTKajToY5vndI6ber41ulVd86jQx3fOkX2YAdt6hTZ6VWnTZI7YsiUJ6UgLKlZakNIoXChf4K10ipClHZKYwdOS88IUTyXrghRZlKgFNoutF1AFdouoIqyA16h9wKvGOfBK8Y2oAUrBErBCmEsBD/E5wBHwSvMhjCxArngjOaCGDLlaclIQ4gCrdwoBVUbydwtBVAbUXxTsLSTApbim0Kk@KYQKVdNIVLMU3xTYJRLp8Ao5im@Kb4pw6UQqbMNIsVBhUiZMAVLg71gKV4qXurMhqHG6BmfB8NQKxXpCAGstTIHSK4FIRlow1rDUAPaOlFsNKANGw1oA9oYW@MjYxhq9MAw1PjSmPJeemAYanhp9MDw0uiB4aUxu0YPjB4YrhqNMHpgGGr0wJhiA99w1cA38A18g9wZZQff8ddx1fkAeJmXpNSKEGCeHXIH2nHaGWoH3xllx25nnh27HXwH3yF3Rtkhd4x3yJ0pdr4gDr7jvoPvzLOD74yA0wMH3xllpwdOD5xRdsgdaIfX4XU8d6bYgY6ckYawxN/A3yjz0hBHplcG0AFvYHIw2QF0NE7B6YA3sDtwOuANeAOnA5MD3sDkgDeY8cDpgDdwOuANpj3gDZ1TOADewPMAOoAOoAPPA7uDuQ/wg7kPjA/wA/zA7pjJsTsijun1mKbstCrTlsTNTjTmy785cH72KG@Rcl7W5//O0UeysmPxyrX6vkh7vm218L5LlDcoF@c9IlrUslXG8lm/@Mqk/@edl/nJs/PJi0Yso20PddmSvtKrlfdeI1cMzUoPVm28FiY/f9E2at6ajbzn/v5gLjn6xfHef8c112Vlslev2mIs9PJM6hOO84v2r/jmVbt6zFac2adc8C5uz/LQ@rSMunXPNzn27@/XXOwrbs81Nu4Cbs@9Pv3X9967@VXe9le/AvDCt2llJi/4tkm59VWpD/8C "J – Try It Online") ### [J](http://jsoftware.com/), 45 bytes ``` [:#.~[:~:&.|.(,1#.&(^#)10#.inv{:)^:(*/@~:)^:_ ``` [Try it online!](https://tio.run/##lZRNj9RGEIbv/AqLlWAGDZP@qM9BkSJFyokTVyQ4RFkBB7jlkmj/@saPQZldr@0ZDvNq2lXdrqfean@5f358eTv8ehpeDoehDKfx9/o4/P7u7R/37083x7v3p7vTi@O/x92h3hxf7D7c7Gu5OX7@@vc/p/2H0@7VL7/d8efj/f7Zs7/@/PRt2L253Q9V/Mdqd/u87AfNwzCkHoZabJTKv@ajdJY9DuxAxryqFWHJtmoF6Qh5xjNviCAc5SQ7UScaJAcnB4HgWZI8VZAEkkCyI8doq@OytUBYdkVYiiAstSMsdVoSpb5m7KW05hUxhGfU0qIh7A22UVWjoJYEKKhRS6OWRi29INWQ8VlvivCPqro2pCPT0hGiVhG2UVCnTZ3mdArqQZRaOmX0YAdl9CwIKVQgRRH@0RKpY4o0QQhIQ6Z/RLUgPKMvooZMAbYZeRQkNEcoSOiQ4JtQmtAmwTehVxKcR4cE34QiJdlBm4QihV4JbdIiiCNjntaKsKRmbR0hhcKV/inWam8IUdqpnR04rVIQoniuYghRZlKhVNqutF1BVdquoKqxA16l9wqvOufBq842oBUrFErFCmUsFD80pgBHwavMhjKxCrnijJWKODLmWS1IR4gCbdwoA9U6ydwtA9A6UXwzsExIAcvwzSAyfDOIjKtmEBnmGb4ZMMalM2AM8wzfDN@M4TKILNgGkeGgQWRMmIFlyV6wDC8NL21iw1Bn9JzPg2Oo14YIQgBrvU4BkltFSAbasdYx1IF2IYqNDrRjowPtQDtj63xkHEOdHjiGOl8aN95LDxxDHS@dHjheOj1wvHRm1@mB0wPHVacRTg8cQ50eOFPs4DuuOvgOvoPvkAejHOAH/gauBh@AqNOSlNYQAsxzQB5AB04HQx3gB6Mc2B3Mc2B3gB/gB@TBKAfkgfEBeTDFwRckwA/cD/CDeQ7wgxEIehDgB6Mc9CDoQTDKAXkAHfAGvIHnwRQH0FkK0hGW@Jv4m3VaOhLI@MoEOuFNTE4mO4HOzik4nfAmdidOJ7wJb@J0YnLCm5ic8CYznjid8CZOJ7zJtCe8aVMKB8CbeJ5AJ9AJdOJ5Yncy9wl@MveJ8Ql@gp/YnRM5dmfmfnh9GsbsYVHGLQM3e6Ax3/9NgfOzB3mzlPOyPf13jj6QhR2zVy7V9136022LhcsmUVmhnJ33gGhWy1oZ82dy8ZWD/Z93XpZHz84nzxoxj/Yt1HlLZKFXC@@9Rq4YmoUeLNp4LUx5@qJ11LI2G2XL/e3BnHPIxfHefsc112Vhshev2mws7PJM2iOO84u2r/jqVbt6zBac2aac8c5uz/zQ9riMtnbPVzm27@/PXOwrbs81Nm4Crs@9Pf4nW@9d/Sqv@2s/AXjh27Qwkxd8W6Vc@6q0@/8A "J – Try It Online") * `…^:_` until result does not change: * `…^:(*/@~:)` if there is no duplicate in the list: * `10#.inv{:` digits of the last number … * `1#.&(^#)` powered by their length, summed * `,` appended to the list. * `[:~:&.|.` reverse list, get a bitmask of first occurrences in it, reverse back. So `1 2 3 2 3 -> 3 2 3 2 1 -> 1 1 0 0 1 -> 1 0 0 1 1`. * `[:#.~` count the trailing 1s with mixed base conversion. [Answer] # [K (Kona)](https://github.com/kevinlawler/kona), 42 bytes ``` --/&{x=*|x}{x~?x}{x,_+/{x^'#x}10_vs*|x}/,: ``` [Try it online!](https://tio.run/##y9bNzs9L/P8/zUpXV1@tusJWq6aitrqizh5E6sRr61dXxKkrV9QaGsSXFYPk9HWs/qcpGBqYcAFJI3MgaWxuAGIbW/wHAA "K (Kona) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` D*L$SƊÐḶL ``` [Try it online!](https://tio.run/##lZW9bhxVFMdf5RZUyMXcj/NVIBrKVKFEKSwz0pqsbBN2A@kiGiQqHgAkHoAaItpIvIf9ImZ@Eylrj2dmN81fe@ece@f8zv/c2e/67fbN/f1Xnz/77Ov/fn3/2@27v5/dv//l7ue/vrj99890@@6fdPf29@f7q7Tb9GnTb2/6V2l7efUyXb8efvXnF5t0eXWz352li01/8TL9eLnbpP77/fn2cvcm7a7Hff1PN/3Frv82Xe93Q@4PZ@l8u027V/v@y7u3f9zff5MkzlIKOUu500Eyv4oNUllWH6SxbENeloywZFvWDqkIecozK0hDOMpINqJG1El2TnYCzrMgeawgCASBYEcM0ZKHZSmOsKyCsGwNYSkVYSnjkij1FWUvpRXLiCI8o5biBWGvs42qCgWVIEBBhVoKtRRqqR2SFRme1SIIv6iqSkEqMi4NIaoZYRsFVdpUaU6loOpEqaVSRnV2UEaNDiGFClonCL9oSctDSisNIdAKMv4iKh3CM/rSRJExwDYlj4IazWkU1OhQw7dGaY02NXxr9Ko559Ghhm@NIluwgzY1imz0qtEm6RpiyJAnOSMsqVlKRUihcKF/grVSC0KUdkplB05L6xCieC5NEaLMpEAptF1ou4AqtF1AFWUHvELvBV4xzoNXjG1AC1YIlIIVwlgIfoiPAY6CV5gNYWIFcsEZ7TJiyJCnuUMqQhRo5UYpqFpJ5m4pgFqJ4puCpY0UsBTfFCLFN4VIuWoKkWKe4psCo1w6BUYxT/FN8U0ZLoVInW0QKQ4qRMqEKVga7AVL8VLxUkc2DDVGz/g8GIZaLkhDCGCt5TFAcskIyUAb1hqGGtDWiGKjAW3YaEAb0MbYGh8Zw1CjB4ahxpfGlPfSA8NQw0ujB4aXRg8ML43ZNXpg9MBw1WiE0QPDUKMHxhQb@IarBr6Bb@Ab5M4oO/iOv46rzgfA87gkpRSEAPPskDvQjtPOUDv4zig7djvz7Njt4Dv4Drkzyg65Y7xD7kyx8wVx8B33HXxnnh18ZwScHjj4zig7PXB64IyyQ@5AO7wOr@O5M8UOdHQdUhGW@Bv4G3lcGuLI8MoAOuANTA4mO4COyik4HfAGdgdOB7wBb@B0YHLAG5gc8AYzHjgd8AZOB7zBtAe8oWMKB8AbeB5AB9ABdOB5YHcw9wF@MPeB8QF@gB/YHSM5dkfEi@HfMA3Z8zJsSdzsRGM@/BoDh2cP8iYph2V5@usQfSAzOyavnKvvg9Sn22YLb6tE3QLl5LwHRJNalsqYPmtHX5n0Y95h2T16djh50ohptK6hTlvSZno1895T5IShmenBrI2nwnRPX7SM2i3NRrfm/vpgTjna0fFef8cp12Vmsmev2mQs9PhM6iOOw4vWr/jiVTt5zGacWaec8E5uz/TQ8riMsnTPFznW7@@nXOwTbs8pNq4CLs@9Pv7V1t67@FVe9lc/AfDIt2lmJo/4tki59FUpL/4H "Jelly – Try It Online") I always wondered why `ÐḶ` and `ÐĿ` both existed until [this](https://codegolf.stackexchange.com/a/145780/66833) answer made the exact functionality of `ÐḶ` clear. ## How it works ``` D*L$SƊÐḶL - Main link. Takes an integer n on the left Ɗ - Group the previous 3 links into a monad f(n): D - Convert n to digits, D $ - Group the previous 2 links into a monad g(D): L - Get the length of D * - Raise each digit to the power of that length S - Sum ÐḶ - Repeatedly apply f(n) until a value is repeated. Then, apply f(n) to that value until it loops, and return the loop formed L - Take the length of the loop ``` ]
[Question] [ Given a nonempty list of nonnegative integers, consider rewriting it as an arithmetic problem where: * A plus sign (`+`) is inserted between pairs of numbers that increase from left to right (a.k.a. from the start of the list to the end). * A minus sign (`-`) is inserted between pairs of numbers that decrease from left to right. * A multiplication sign (`*`) is inserted between pairs of numbers that are equal. Said another way: any sublist `a,b` becomes `a+b` if `a<b`, `a-b` if `a>b`, and `a*b` if `a==b`. For example, the list ``` [12, 0, 7, 7, 29, 10, 2, 2, 1] ``` would become the expression ``` 12 - 0 + 7*7 + 29 - 10 - 2*2 - 1 ``` which [evaluates to](http://www.wolframalpha.com/input/?i=12+-+0+%2B+7*7+%2B+29+-+10+-+2*2+-+1) `75`. Write a program or function that takes in such a list and evaluates it, printing or returning the result. * Order of operations matters. Multiplications should be done before any addition or subtraction. * If the input list has one number, that should be what it evaluates to. e.g. `[64]` should give `64`. * Use of `eval` or `exec` or similar constructs is allowed. Here are some additional examples: ``` [list] expression value [0] 0 0 [1] 1 1 [78557] 78557 78557 [0,0] 0*0 0 [1,1] 1*1 1 [2,2] 2*2 4 [0,1] 0+1 1 [1,0] 1-0 1 [1,2] 1+2 3 [2,1] 2-1 1 [15,4,4] 15-4*4 -1 [9,8,1] 9-8-1 0 [4,2,2,4] 4-2*2+4 4 [10,9,9,12] 10-9*9+12 -59 [1,1,2,2,3,3] 1*1+2*2+3*3 14 [5,5,4,4,3,3] 5*5-4*4-3*3 0 [3,1,4,1,5,9,2,6,5,3,5,9] 3-1+4-1+5+9-2+6-5-3+5+9 29 [7637,388,389,388,387,12,0,0,34,35,35,27,27,2] 7637-388+389-388-387-12-0*0+34+35*35-27*27-2 7379 ``` **The shortest code in bytes wins. Tiebreaker is earlier answer.** [Answer] ## Python 2, 63 bytes ``` p=s='print-' for x in input():s+='*+-'[cmp(x,p)]+`x`;p=x exec s ``` Constructs and `eval`s the expression string. The arithmetic symbol is chosen by comparing the previous number `p` to the current one `x`. The symbol is appended followed by the current number. The first number is handled with a clever trick from Sp3000. The initial value of `p` is set to a string, which is bigger than any number and therefore causes a `-` before the first number. But, `s` is initialized to `print-` at the same time that makes the result start with `print--` (thanks to xsot for saving 2 bytes by initializing with `print`.) [Answer] # Pyth, ~~31~~ ~~26~~ ~~19~~ ~~17~~ ~~16~~ 15 bytes Expressions with `*` won't evaluate online, but they would theoretically work. 2 bytes thanks to Maltysen. ``` vsm+@"*-+"._-~k ``` [Test suite (with evaluation).](http://pyth.herokuapp.com/?code=vsm%2B%40%22%2a-%2B%22._-%7Ek&test_suite=1&test_suite_input=%5B0%5D%0A%5B1%5D%0A%5B78557%5D%0A%5B0%2C1%5D%0A%5B1%2C0%5D%0A%5B1%2C2%5D%0A%5B2%2C1%5D%0A%5B9%2C8%2C1%5D%0A%5B3%2C1%2C4%2C1%2C5%2C9%2C2%2C6%2C5%2C3%2C5%2C9%5D&debug=0) [The other cases (without evaluation).](http://pyth.herokuapp.com/?code=sm%2B%40%22%2a-%2B%22._-%7Ek&test_suite=1&test_suite_input=%5B0%2C0%5D%0A%5B1%2C1%5D%0A%5B2%2C2%5D%0A%5B15%2C4%2C4%5D%0A%5B4%2C2%2C2%2C4%5D%0A%5B10%2C9%2C9%2C12%5D%0A%5B1%2C1%2C2%2C2%2C3%2C3%5D%0A%5B5%2C5%2C4%2C4%2C3%2C3%5D%0A%5B7637%2C388%2C389%2C388%2C387%2C12%2C0%2C0%2C34%2C35%2C35%2C27%2C27%2C2%5D&debug=0) ## History * 31 bytes: `M+G@"*-+"->GH<GHv+sgMC,JsMQtJ\x60e` * 26 bytes: `M+G@"*-+"->GH<GHv+sgVQtQ\x60e` * 19 bytes: `vtssVm@"*-+"->Zd<~Z` * 17 bytes: `vtssVm@"*-+"._-~Z` * 16 bytes: `vssVm@"*-+"._-~k` * 15 bytes: `vsm+@"*-+"._-~k` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~18~~ ~~16~~ ~~15~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` I0;ð1g×⁹⁸œṗP€S ``` Uses no built-in eval. [Try it online!](http://jelly.tryitonline.net/#code=STA7w7AxZ8OX4oG54oG4xZPhuZdQ4oKsUw&input=&args=Wzc2MzcsMzg4LDM4OSwzODgsMzg3LDEyLDAsMCwzNCwzNSwzNSwyNywyNywyXQ) or [verify all test cases](http://jelly.tryitonline.net/#code=STA7w7AxZ8OX4oG54oG4xZPhuZdQ4oKsUwrDh-KCrEc&input=&args=WzBdLCBbMV0sIFs3ODU1N10sIFswLDBdLCBbMSwxXSwgWzIsMl0sIFswLDFdLCBbMSwwXSwgWzEsMl0sIFsyLDFdLCBbMTUsNCw0XSwgWzksOCwxXSwgWzQsMiwyLDRdLCBbMTAsOSw5LDEyXSwgWzEsMSwyLDIsMywzXSwgWzUsNSw0LDQsMywzXSwgWzMsMSw0LDEsNSw5LDIsNiw1LDMsNSw5XSwgWzc2MzcsMzg4LDM4OSwzODgsMzg3LDEyLDAsMCwzNCwzNSwzNSwyNywyNywyXQ). ### How it works ``` I0;ð1g×⁹⁸œṗP€S Main link. Input: A (list) I Increments; compute the deltas of all adjacent items of A. 0; Prepend a 0. ð Begin a new, dyadic chain. Left argument: D (0 plus deltas). Right argument: A 1g Compute the GCD of 1 and each item in D. This yields 1 for non-negative items, -1 for negative ones. ×⁹ Multiply each 1 or -1 with the corresponding item of A. This negates every item in A that follows a - sign. ⁸œṗ Partition the result by D. This splits at occurrences of non-zero values of D, grouping items with identical absolute value. P€ Take the product of each group. S Sum; add the results. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` Y'^l6MdZSh*s ``` This uses [@aditsu's very nice idea](https://codegolf.stackexchange.com/a/82725/36398) of run-length encoding. [**Try it online!**](http://matl.tryitonline.net/#code=WSdebDZNZFpTaCpz&input=Wzc2MzcsMzg4LDM4OSwzODgsMzg3LDEyLDAsMCwzNCwzNSwzNSwyNywyNywyXQ) ### Explanation ``` % Take input vector implicitly Y' % RLE. Produces two vectors: values and lengths ^ % Rise each value to the number of consecutive times it appears. This % realizes the product of consecutive equal values l % Push 1 6M % Push vector of values again d % Consecutive differences ZS % Sign function. Gives 1 or -1 (no 0 in this case) h % Concatenate horizontally with previous 1 * % Multiply. This gives plus or minus depending on increasing character s % Sum of vector. This realizes the additions or subtractions % Display implicitly ``` [Answer] # CJam, 20 ``` q~e`{~_W-g\:W@#*}%:+ ``` [Try it online](http://cjam.aditsu.net/#code=q%7Ee%60%7B%7E_W-g%5C%3AW%40%23*%7D%25%3A%2B&input=%5B7637%20388%20389%20388%20387%2012%200%200%2034%2035%2035%2027%2027%202%5D) **Explanation:** ``` q~ read and evaluate the input (array of numbers) e` RLE encode, obtaining [count number] pairs {…}% map each pair ~_ dump the count and number on the stack, and duplicate the number W- subtract the previous number (W is initially -1 by default) g get the sign of the result \ swap with the other copy of the number :W store it in W (for next iteration) @# bring the count to the top, and raise the number to that power * multiply with the sign :+ add all the results together ``` [Answer] # JavaScript (ES6), 54 ``` p=>eval(0+p.map(v=>x+='*-+'[(p>v)+2*(p<v)]+(p=v),x=1)) ``` `eval` receives a comma separated list of expressions and returns the value of the last one. **Test** ``` f=p=>eval(0+p.map(v=>x+='*-+'[(p>v)+2*(p<v)]+(p=v),x=1)) t=p=>(0+p.map(v=>x+='*-+'[(p>v)+2*(p<v)]+(p=v),x=1)) function Test() { var a=I.value.match(/\d+/g).map(x=>+x) // convert input to a numeric array var x=f(a),y=t(a) O.textContent='Value '+x+'\n(no eval '+y+')' } Test() ``` ``` #I { width:80%} ``` ``` <input value='12, 0, 7, 7, 29, 10, 2, 2, 1' id=I> <button onclick='Test()'>Test</button> <pre id=O></pre> ``` [Answer] # Julia, ~~76~~ 57 bytes ``` !x=[[" ""-*+"[2+sign(diff(x))]...] x]'|>join|>parse|>eval ``` My first time golfing Julia, so maybe there are obvious improvements. [Try it online!](http://julia.tryitonline.net/#code=IXg9W1siICIiLSorIlsyK3NpZ24oZGlmZih4KSldLi4uXSB4XSd8PmpvaW58PnBhcnNlfD5ldmFsCgpwcmludCghWzEyLCAwLCA3LCA3LCAyOSwgMTAsIDIsIDIsIDFdKQ&input=) Dennis saved a ton of bytes. [Answer] # Pyth - ~~23~~ ~~22~~ 20 bytes As with Kenny's, multiplication doesn't work online. ``` vs.i+\+@L"*+-"._M-Vt ``` [Test Suite without doing eval](http://pyth.herokuapp.com/?code=s.i%2B%5C%2B%40L%22%2a%2B-%22._M-Vt&test_suite=1&test_suite_input=%5B0%5D%0A%5B1%5D%0A%5B78557%5D+%0A%5B0%2C0%5D%0A%5B1%2C1%5D%0A%5B2%2C2%5D%0A%5B0%2C1%5D%0A%5B1%2C0%5D%0A%5B1%2C2%5D%0A%5B2%2C1%5D%0A%5B15%2C4%2C4%5D%0A%5B9%2C8%2C1%5D%0A%5B4%2C2%2C2%2C4%5D%0A%5B10%2C9%2C9%2C12%5D%0A%5B1%2C1%2C2%2C2%2C3%2C3%5D%0A%5B5%2C5%2C4%2C4%2C3%2C3%5D%0A%5B3%2C1%2C4%2C1%2C5%2C9%2C2%2C6%2C5%2C3%2C5%2C9%5D%0A%5B7637%2C388%2C389%2C388%2C387%2C12%2C0%2C0%2C34%2C35%2C35%2C27%2C27%2C2%5D&debug=0). [Answer] # R, 92 bytes There's likely still some good golfing that can be done here. ``` eval(parse(t=paste(i<-scan(),c(ifelse(d<-diff(i),ifelse(d>0,"+","-"),"*"),""),collapse=""))) ``` Ungolfed: ``` i = scan() # Read list from stdin d = diff(i) # Calculate difference between each element of list s = ifelse(d, # If d!=0 ifelse(d>0, # And if d>1 "+", # Return plus "-"), # Else return minus "*") # Else (i.e. d==0) return multiply. s = c(s,"") # Pad the list s with an empty string, so it's the same # length as i p = paste(i,s,collapse="")# Paste the elements of i and s into one long string. eval(parse(t=p)) # Evaluate the string as a language object. ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~34~~ 32 bytes ``` ~b≜ḅ⟨h⟨h≡^⟩l⟩ᵐs₂ᶠ{zh>₁&ttṅ|tt}ᵐ+ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vy7pUeechztaH81fkQHGnQvjHs1fmQPED7dOKH7U1PRw24Lqqgy7R02NaiUlD3e21pSU1AKltP//jzY3MzbXMbawAGJLKG2uY2ikYwCExiY6xqYgZGQORrH/owA "Brachylog – Try It Online") [Answer] # TI-BASIC, 146 bytes I'll format it nicely when not on mobile. Sleep escapes me, so you get this. Enjoy. ``` Prompt L₁ "(→Str1 For(A,1,dim(L₁ {0,1→L₂ {0,L₁(A→L₃ LinReg(ax+b) L₁,L₃,Y₁ Equ►String(Y₁,Str2 sub(Str2,1,-1+inString(Str2,"X→Str2 If A>1 Then L₁(A-1 2+(Ans>L₁(A))-(Ans<L₁(A Str1+sub("+*-",Ans,1→Str1 End Str1+Str2→Str2 End expr(Str1 ``` [Answer] # Javascript ES6, ~~64~~ 62 chars ``` a=>eval(a.map((x,i)=>x+('*+-'[x<a[++i]|(x>a[i])*2])).join``+1) ``` [Answer] # Java, 384 bytes ``` int s(int[]l){int n=l[0],m;for(int i=0;i<l.length-1;i++)if(l[i]<l[i+1])if(i<l.length-2&&l[i+1]!=l[i+2])n+=l[i+1];else{m=l[i+1];while(i<l.length-2&&l[i+1]==l[i+2])m*=l[(i++)+1];n+=m;}else if(l[i]>l[i+1])if(i<l.length-2&&l[i+1]!=l[i+2])n-=l[i+1];else{m=l[i+1];while(i<l.length-2&&l[i+1]==l[i+2])m*=l[(i++)+1];n-=m;}else{m=l[i];while(i<l.length-1&&l[i]==l[i+1])m*=l[i++];n+=m;}return n;} ``` **Ungolfed** [try online](http://ideone.com/tw9Gkw) ``` int s(int[] l) { int n=l[0], m; for(int i=0; i<l.length-1; i++) { if(l[i] < l[i+1]) { if (i<l.length-2 && l[i+1]!=l[i+2]) { n += l[i+1]; } else { m = l[i+1]; while(i<l.length-2 && l[i+1]==l[i+2]) m *= l[(i++)+1]; n += m; } } else if(l[i] > l[i+1]) { if (i<l.length-2 && l[i+1]!=l[i+2]) { n -= l[i+1]; } else { m = l[i+1]; while(i<l.length-2 && l[i+1]==l[i+2]) m *= l[(i++)+1]; n -= m; } } else { m = l[i]; while(i<l.length-1 && l[i]==l[i+1]) m *= l[i++]; n += m; } } return n; } ``` [Answer] # Javascript ES6, 79 chars ``` a=>eval(`${a}`.replace(/(\d+),(?=(\d+))/g,(m,a,b)=>a+('*+-'[+a<+b|(+a>+b)*2]))) ``` [Answer] ## Perl, 49 bytes **48 bytes code + 1 for `-p`** ``` s/\d+ (?=(\d+))/$&.qw(* - +)[$&<=>$1]/ge;$_=eval ``` ### Usage ``` perl -pe 's/\d+ (?=(\d+))/$&.qw(* - +)[$&<=>$1]/ge;$_=eval' <<< '12 0 7 7 29 10 2 2 1' 75 ``` ### Notes I learnt here that you can capture a lookahead in PCRE, although it's a little unintuitive (`(?=(\d+))` instead of `((?=\d+))`). It does make sense after reading though as you would be capturing a zero-length match (the lookahead) with the latter, and instead capture the match with the former). Thanks to [@ninjalj](https://codegolf.stackexchange.com/users/267/ninjalj) for saving 8 bytes! [Answer] ## Actually, 30 bytes ``` ;2@VpXdX`i-su"+*-"E`M' @o♀+εj≡ ``` Unfortunately, because the eval (`≡`) command only evaluates literals on TIO, this program does not work on TIO. Explanation: ``` ;2@VpXdX`i-su"+*-"E`M' @o♀+εj≡ ; duplicate input 2@V overlapping sublists of length <= 2 pXdX discard first and last element (length-1 sublists) `i-su"+*-"E`M map: for each pair of elements i-su flatten, subtract, sign, increment (results in a 0 if b < a, 1 if b == a, and 2 if b > a) "+*-"E select the correct operation ' @o put a space at the beginning of the list to pad it properly ♀+ pairwise addition (since addition is not defined for strings and integers, this just zips the lists and flattens the result into a single flat list) εj join with empty string ≡ eval ``` [Answer] # [R](https://www.r-project.org/), ~~120~~ 44 bytes ``` r=rle(scan());c(1,sign(diff(r$v)))%*%r$v^r$l ``` [Try it online!](https://tio.run/##bY7NCsIwEITveYqBbSERD/npug3SVxGkGimUHlLw9eNWr/IxzCzMwNZGIcJDlJgRPKISQBA25EHekF7BkIwsgp8ZYjAGJSlHJ@lmUDGy7i/q6ZspZlOmVqe6Pu0@3zfr3HW24bwvr80@llJs7d7Ouf7Ua7jVbm3/Hmof "R – Try It Online") The algorithm is similar to [this answer's](https://codegolf.stackexchange.com/a/82725/80010), but I only realized it after coding my answer. Much better than my original answer that was using `eval(parse)`. Fully leverages R's vectorized operations - does the `*` operation first using `rle(x)$values ^ rle(x)$lenghts` and dot-products this vector with `sign( diff( rle(x)$values ) )` (predended with `1`). [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ ~~16~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ü.S…*-+sè‚ζJJ.E ``` -2 bytes thanks to *@Emigna*. [Try it online](https://tio.run/##MzBNTDJM/f//8B694EcNy7R0tYsPr3jUMOvcNi8vPdf//6MNjXQMdMyB0MhSx9BAxwgIDWMB) or [verify all test cases](https://tio.run/##LY49DsIwDIV3TlF1hEcV54ckUxdAoitj1QEkTsAFOjEjRg6AOAETW3cO0YsEx61sy/b3bMvKnc50SRT2h21dFuPtUZT1cE/DtzqO/Wu5Xl2H99g/f5@mqXYJqSUNBc@mI0hBs1G3aBVHzj4453MPIaLxjBASMvFMyMHCchERRLRyLhO@HNlIT0eEGxjuHGRr7gxrlsPxsMaGs8l1fmRjPEwIHHHOHvK8guF1l1178e4P). **Explanation:** ``` ü # Pair-wise loop over the (implicit) input-list # i.e. [12,0,7,7] → [[12,0],[0,7],[7,7]] .S # Calculate the signum of the pair (-1 for a<b; 0 for a==b; 1 for a>b) # i.e. [[12,0],[0,7],[7,7]] → [1,-1,0] …*-+sè # Index over "*-+" (with wrap-around) # i.e. [1,-1,0] → ['-','+','*'] ‚ζ # Zip the two lists together (appending the operands to the numbers) # i.e. [12,0,7,7] and ['-','+','*','+'] # → [[12,'-'],[0,'+'],[7,'*'],[7,' ']] JJ # Join them together # [[12,'-'],[0,'+'],[7,'*'],[7,' ']] → '12-0+7*7 ' .E # Evaluate as Python code # i.e. '12-0+7*7' → 61 ``` [Answer] # PHP, 103 bytes Neat challenge. This got longer than expected. I think using `array_map` or similar won't improve the byte count, as anonymous functions are [still](https://wiki.php.net/rfc/arrow_functions) expensive in PHP. ``` foreach(fgetcsv(STDIN)as$v)(0<=$p?$o.=$p.('*-+'[($p>$v)+2*($p<$v)]):_)&&$p=$v;echo eval("return$o$v;"); ``` Runs from command line, will prompt for a comma separated list, like: ``` php array_to_math.php 12, 0, 7, 7, 29, 10, 2, 2, 1 ``` [Answer] ## PowerShell v2+, 62 bytes ``` -join($args|%{"$o"+'*+-'[($o-lt$_)+2*($o-gt$_)];$o=$_})+$o|iex ``` Takes input as space-separated command-line arguments, which gets converted into automatic array `$args`. We iterate through each element, using helper variable `$o` each iteration to remember what our previous entry was. We use a indexed-string to pull out the appropriate operator, done by performing math on the implicitly-converted Boolean values (e.g., if the previous entry is smaller, the `[]` evaluates to `1+2*0` so `'*+-'[1]` means the `+` is selected). The concatenated strings are left on the pipeline. We collect all of those snippets together (e.g., `3-`, `1+`, `4-`, etc.) with a `-join` operation, concatenate on the final number (implicitly converted to string), and pipe it to `iex` (alias for `Invoke-Expression` and similar to `eval`). [Answer] # [Japt](https://github.com/ETHproductions/japt), 25 bytes Would like to cut it shorter, but I couldn't make an eval-less version work. ``` S+Uä!- ®"*+-"gZÎì)íU OxU ``` [Try it online!](https://tio.run/##y0osKPn/P1g79PASRV2FQ@uUtLR1ldKjDvcdbj60RvPw2lAu/4rQ//@jzc2MzXWMLSyA2BJKm@sYGukYAKGxiY6xKQgZmYNRLAA "Japt – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) `-x`, ~~21~~ 19 bytes ``` änJ f mÎí*Uò¦ ®ÎpZÊ ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=5G5KIGYgbc7tKlXypiCuznBayg==&input=WzEyLDAsNyw3LDI5LDEwLDIsMiwxXQoteA==) --- ## Explanation ``` :Implicit input of array U J :Prepend -1 än :Get deltas f :Filter (remove 0s) m :Map Î : Signs í :Interleave U : Original input ò : Partition on ¦ : Inequality ® : Map each sub-array Z Î : Get first element p : Raise to the power of ZÊ : Length of Z * :Reduce each pair of elements by multiplcation :Implicitly reduce by addition and output ``` ]
[Question] [ ## Introduction A "lobster number", by my own designation, is a number that contains within itself all of its prime factors. The "lobster" description was inspired by the recent question "[Speed of Lobsters](https://codegolf.stackexchange.com/questions/217690/speed-of-lobsters)". The basic idea is that each prime factor can be made by lobsters munching away digits of the number until you are left with just the factor. Example: `51375` is a lobster number, since its prime factors are `[3,5,137]`, which can be made by lobsters thusly: `[**3**, 5**** / ****5, *137*]`. Another lobster number is `62379`, as the factors `[3,29,239]` can be formed as `[**3**,*2**9,*23*9]`. ## Challenge Given a number as input, return whether it is a lobster number or not. Preferentially this is a boolean output, such as 1 or 0, or True or False. Astute readers may realize that prime numbers are a trivial solution to this requirement, but since they don't allow the lobsters to eat any digits, they are out. Your program must not identify prime numbers as lobster numbers. This is similar to OEIS [A035140](https://oeis.org/A035140), but has the additional requirement that each digit of the factor must appear at least the same number of times in the number, and in the correct order. In other words, `132` is not a lobster number, since its factors are `[2,3,11]`, and the `11` cannot be made by munching away at just `132`. `312` is also not a lobster number, because its factors are `[2,3,13]`, and `13` is out of order. I believe the "mathematical" definition would be: "Determine if the number n is a composite number such that all prime factors of n are a subsequence of n". ## Test Cases ``` 59177 -> True 62379 -> True 7 -> False 121 -> True 187 -> False 312 -> False ``` As always, Standard Loopholes are forbidden. ## Note: It has come to my attention that the original reasoning I gave for not needing to handle 0 or 1 as input is faulty. However, requiring the proper output at this point would invalidate a number of answers. Therefore, let it hereby be known that neither 0 nor 1 are lobster numbers, but you also do not need to handle them as input (they are not valid test cases). If your code does handle them correctly, you may give yourself the Lobster Advocate Badge™. [Answer] # [Python 3](https://docs.python.org/3/), ~~155~~, ~~126~~, ~~124~~, ~~123~~, ~~120~~ ~~116~~, 113 bytes Yes! First python answer! Saved **21 bytes** due to a suggestion by Dominic van Essen to remove the `for` loop! Saved **8 bytes** because I realized I could use `t*=True/False` instead of `t+=[True/False]`. Saved another **2 bytes** right after I finished editing because I realized `t` could simply be set to the same value as `i` and `l`! Saved **1 byte** based off Danis's python 2 comment. Saved another **3 bytes** based off Tipping Octopus's comment. Saved another **4 bytes** due to Tipping Octopus again! Saved another **3 bytes** thanks to Dominic's suggestion to remove the `t` variable. # New Answer ``` x=input() n=int(x) i=l=2 while~-n: if n%i:i+=1 else:n//=i;l+=1;j=iter(x);l*=2*all(c in j for c in str(i)) print(l>4) ``` # How it works The `while` loop computes the prime factors of the input. If a prime factor is found, it checks if it is a subsequence of the input. `l` is multiplied by whether or not this is `True`. This takes advantage of the fact that python's `True` and `False` values act like 1s and 0s when you multiply by them. This means that instead of appending `True/False` to `t` and checking whether `all(t)` is `True` like in my old answer, I can just multiply `l` by `2*True/False` and check its value in the `print` statement. The `print` statement prints `True` if `l>4`. [Try it online!](https://tio.run/##HczBCsIwDIDhe54iF6GdyGj11BHfRaRjGSErXYbz4qvX6e27/H9527TotbWdWMtmzoMeMrd7YBKK8JpY8ueiCZBH1BMnPlMAzLLmpH1PPMzEluuRDNJR7B4i7omsOOO4VPxzterYeyj1N5f7zbcWYvgC "Python 3 – Try It Online") # Old Answer ``` x=n=int(input()) l=[] i=2 while i<=n: if n%i:i+=1 else:n/=i;l+=[i] t=[] for p in l:i=iter(str(x));t+=[all(c in i for c in str(p))] print(all(t)*len(l)>1) ``` [Try it online!](https://tio.run/##HY5BCsJADEX3OUU2wkQXUnXj1HiR0oXIlAZCOkwj1tOPjrsP7z34@ePzYudaNzYW8yCWXx6IQHkYQfgE71k0odzYIqBMaDuJcuAOMOmaoh1Zej3wICN4a6alYEYx1CgsnkpYvYSNqPef9VANz0YFm/ifjWeiEXJpF5ritNdkQeneUa2X6xc "Python 3 – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes That's basically this: "Determine if the number n is a composite number such that all prime factors of n are a subsequence of n". ``` ḋṀ⊆ᵛ? ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSuVv2obcOjpuZHHcuVSopKU/WUakDMtMScYiC79uGuztqHWyf8f7ij@@HOhkddbQ@3zrb//z/a1NLQ3FxHwczI2NxSRwHIMjQyBBIWQJaxoRFcwtTQ2Nw0FgA "Brachylog – Try It Online") ``` ḋṀ⊆ᵛ? (with implicit input n) ḋ get the prime factors of n Ṁ they must be Ṁany (at least 2 to filter out primes) ⊆ᵛ all of them must be an (ordered) subset of ? the input ``` [Answer] # [Zsh](https://www.zsh.org/) `-e -o glob_subst -o extended_glob`, ~~40~~ 38 bytes ``` >$1: for i (`factor $1`)>${i///*}*~$i: ``` [Try it online!](https://tio.run/##qyrO@K9RnFqioJuqoJuvkJ6TnxRfXJpUXALipVaUpOalpKbEg4T/26kYWnGl5RcpZCpoJKQlJpcAmSqGCZp2KtWZ@vr6WrVadSqZVv811ez0U1LL9PNKc3K4bGxsVOz//zc0MgQA "Zsh – Try It Online") Outputs via exit code: `0` is a lobster number, `1` is not a lobster number Explanation: * `>` - do nothing, and send the output to: + `$1:` - the input with a `:` appended (e.g. `51375:`). This is because `factor` outputs the input number itself, then a colon, then its factors, and we need to match based on that later. * `factor $1` - factorise the input (in the format `51375: 3 5 137`) * `for i` - for each element in the factorisation: + `${i}` - take that element + `///*` - prefix each character with a `*` (e.g. `*1*3*7`) + append `*~` + the input + `:` + `>`, `-o glob_subst` - do nothing, and try to output to a file matching that pattern (there is only one file in the directory, the one we created earlier): - at this point the pattern is something like `*1*3*7*~51375:` - `*` - match zero or more characters; so `*1*3*7*` tests for a subsequence. - `~`, `-o extended_glob` - the file must match `*1*3*7*` but *not* `51375:` itself - this is to prevent prime numbers from being matched. + `-e` - exit immediately if there is an error (no files match that pattern) and set the exit code to `1`. If all factors matched a file, there is no error and the exit code is `0`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 6 bytes ``` æ¨IfåP ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8LJDKzzTDi8N@P/f1NLQ3BwA "05AB1E – Try It Online") or [Try all cases!](https://tio.run/##S0oszvj/PzU5I19BN09B/fCyQys80w4vDVBXsFNIzk9J1UtMSuXiKs/IzElVKEpNTFHIzONKyedSUNDPLyjRzy9OTMpMhVJw9Qo2NjYKKmCFean//5taGpqbc5kZGZtbcplzGRoZchlamHMZGxpBxQA) **Commented:** ``` æ # get the powerset / all subsequences of the input ¨ # remove the last one (the input itself) If # get all prime factors of the input å # is each prime factor in the powerset? P # take the product ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~13~~ ~~10~~ 9 bytes *(`Πm` -> `Λ` simultaneously golfed-down by [Razetime](https://codegolf.stackexchange.com/users/80214/razetime)!)* ``` Λo€hṖd¹dp ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8f@52fmPmtZkPNw5LeXQzpSC////R5saGpub6phaGpqb65gZGZtb6pjrGBoZ6hhamOsYGxpBxGIB "Husk – Try It Online") Returns `0` (falsy) for non-lobster numbers, and a positive nonzero integer (truthy) for lobster numbers. **How?** ``` Λo p # is this true for each prime factor of input: € # index (or zero if absent) of d # its digits among hṖ # all subsets (in order, without full set) of d¹ # digits of input ``` [Answer] # [Python 2](https://docs.python.org/2/), 93 bytes Outputs via exit code: `0` if it is a Lobster number, `1` otherwise. ``` n=m=input() i=1 while~-m: i+=1 while m%i<1:m/=reduce(lambda s,c:s[c==s[:1]:],`n`,`i`)or i%n ``` [Try it online!](https://tio.run/##dY3LasMwEEX38xWDwcSmLu3YdRSLatf@QVcNAaeyIAPRA1lp601/3RXuupuBOdx7T1jSxbt2/brw1SBJwBSXfNF8G42xKIrVKavYhVuqamBFsEV/7m1O8V3@8a9rS34maR9UNNNNm@p6th/TGedGy/molZqPkk7y1IxubEYeax@RS7ciZkf2hcgu4a7sJ5ndnFD7yeDjDkt0kIk2IWH1tgTzGqOPDb6b6F/4k2f2bkO1/HeGtpm1H0gI2LedGEAAtQR0ENBRCy108AQ97DM/wPAL "Python 2 – Try It Online") The algorithm for determining subsequences was borrowed from [@xnor's answer](https://codegolf.stackexchange.com/a/180287/88546) to [Is string X a subsequence of string Y?](https://codegolf.stackexchange.com/q/5529/88546). A `TypeError` is raised when the subsequence check fails, and the `i%n` causes a `ZeroDivisionError` to occur on prime inputs. ### [Python 2](https://docs.python.org/2/), 92 bytes One byte can be saved using `exec`, at the cost of segfaulting on large inputs. ``` n=m=input() i=1 exec"i+=1\nwhile m%i<1:m/=reduce(lambda s,c:s[c==s[:1]:],`n`,`i`)or i%n\n"*n ``` [Try it online!](https://tio.run/##dY3BbsIwEETv@xUrSxEJjdRuKIRa9a39g54KSKGOJVYia8sx0Hx96tJzL3N4o5kXpnTy0sy3E58dkgZMccqJ7ttZjEqpWcxgWMIllRWwIfhtFD8Y2svfaij4lfTwaKLrL9aV5@Pw1R9xrK0ed9aYcafpoA91J13dcVf5iFzIXtRSZsSsyLoQWRIuinWvs5oTWt87fFpggQKZWBcSlh9TcO8x@ljjp4v@ja88spc7qvS/N3S/mVughoC2LayogQZW8Axr2EALW3j5AQ "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` DŒPḌḟiⱮÆfẠ ``` [Try it online!](https://tio.run/##y0rNyan8/9/l6KSAhzt6Hu6Yn/lo47rDbWkPdy34b324XeVR0xr3//9NLQ3NzXUUzIyMzS11FIAsQyNDIGEBZBkbGsElTA2NzU0B "Jelly – Try It Online") ## How it works ``` DŒPḌḟiⱮÆfẠ - Main link. Takes an integer n on the left D - Digits of n ŒP - Powerset of the digits Ḍ - Convert back to integers ḟ - Remove n from this list Æf - Yield the prime factors of n Ɱ - Over each prime factor: i - Index of the factor in the powerset, or 0 Ạ - All are true? ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 95 bytes ``` .+ $*_¶$& %O^$`. +`^(__+?)(\1)*¶ $#2$*__¶$.1¶ _¶((.)+¶(?=(.+¶)*((?<-2>\2)|.)+$(?(2).))){2,}.+$ ``` [Try it online!](https://tio.run/##FYoxDsIwDEV3XwMX2QlYsisIlYCMjFygasrQgYUBsQHX6gF6sWCm97/ee06v@@NWG7qMVSJgKMuMa2iuA44CEMeBSomZqVcOywy4Mm/@kahfH0TC0ZFPJE4ORPm4tXNv/HGDlMlYmPltm69ErHXXaUqwtzZ1kEBNQQ8JWrUf "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` .+ $*_¶$& ``` Duplicate the input, converting one copy to unary. ``` %O^$`. ``` Reverse both copies. (Reversing the unary copy has no effect, of course, other than being golfier.) Reversing the input allows it to be used for nondestructive subsequence matching (a simple subsequence matching Retina program works by destroying both strings on success). ``` +`^(__+?)(\1)*¶ $#2$*__¶$.1¶ ``` Repeatedly extract the smallest proper (and therefore necessarily prime) factor of the unary input, until it is reduced to 1. ``` _¶((.)+¶(?=(.+¶)*((?<-2>\2)|.)+$(?(2).))){2,}.+$ ``` Attempt to match the unary 1, followed by at least 2 factors, each of which can be matched against the reversed input by popping its previously captured characters as they are seen, followed by the reversed input. [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes *I got ninja'd..* ``` §&tΛo€Ṗd¹dp ``` [Try it online!](https://tio.run/##ARwA4/9odXNr///CpyZ0zptv4oKs4bmWZMK5ZHD///81 "Husk – Try It Online") Outputs truthy for a lobster number and falsy otherwise. This would be shorter if `all` returned 0 for empty lists. ## Explanation ``` §&tΛo€Ṗd¹dp p prime factorization of the input § fork: t is the list not composed of a single element? & and, Λo d are all the prime factors' digits € present in Ṗd¹ the powerset of the input's digits? ``` [Answer] # [Haskell](https://www.haskell.org/), ~~135~~ 128 bytes Saved 7 bytes thanks to @ovs! ``` f n=all(\x->x/=n&&(show n%show x))$foldl(\f x->[x|all((>0).mod x)f&&mod n x<1]++f)[][2..n] (a:b)%(c:d)=b%([c|a/=c]++d) _%x=x==[] ``` [Try it online!](https://tio.run/##bYxBDoIwEEX3nGIWQtqAaCGKEOtFamMqpYFYCgGMNfHuWIhLN39@5r38WoyPSut5VmCo0Bpd7fZid9QEARrr7gXGX4/FeKM6LZ2gwCnMfhYbXfY4bjvpuAqCpRiwZ8LDUGHGWRLHhntIFHfso7KQmN59xMqP2NHSORJ7N99SSynjcysaAxRk5wHoaoJpeE71230YSUgEh5xkWQTHJM1y/lOU0ONqOEBOLlKSLKwfGjPBBlrRA1L4N/UHrAPzFw "Haskell – Try It Online") [Answer] # [J](http://jsoftware.com/), 27 bytes ``` 1<[:*/](]#.@E.[-.-.)&":"+q: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DW2irbT0YzVilfUcXPWidfV09TTVlKyUtAut/mtypSZn5CuohxSVpqpD2GkKppaG5uYwjpmRsbkljGNoZMgF1eGWmFOM0AJXbmgBZxobGv0HAA "J – Try It Online") Takes list of prime factors `q:` and original input, and for each pair, formats each as a string `&":"+` and then applies the following verb in parens: `]#.@E.[-.-.` This verb set subtracts the factor digits from the input digits `-.` (leaving digits *not* in the factor) and then subtracts those from the input digits `[-.`, leaving only input digits that *are* in factor, with order preserved. We then check if the factor is a substring match of that `E.`, which returns a boolean list of length input, with a 1 at any index where a match begins. Finally we interpret that as a base 2 number and convert to an integer `#.@`. This means that for a true result we need *all* factors to be greater than or equal to 1, and at least 1 factor to be greater than 1. So we multiply all the results together `[:*/` and check if that is greater than 1 `1<`. [Answer] # [Wolfram Language](https://www.wolfram.com/language/), 118 bytes ``` i|->Catch@AllTrue[MemberQ[a=FactorInteger@i,{i,_}]&&Throw@False;a,LongestCommonSequence@##==#&@@ToString/@{#[[1]],i}&] ``` [Try it online!](https://tio.run/##TU/RSsQwEHz3K8IV@hSQtGg9SyFyUBAUlOtbCNcY99pAk5zpFoXSb6@9E@9un3aY2Z0Zq7AFq9BoNc/7ohycRuOdMJRsFOqWP3VdFQYQr2A/ILwLVZRKow/PDqGBwA0dDd1NMo6rNvhvXqquh1zRF@8a6HHjrfVuC18DOA08iooiijmv/BaDcc0tHyMhmJTUTLGU@YzLTU8KMo53a5ZllBzNJ0rG@yTN1he4MCen484SdiHYwzWVsuQfTfnNud3oKIGfA2iEz0X2tkRB8ZeoAnvoFIJY1ax@PKtIndSUNB5JndYrKa4eULIXTi5DOOfkVCCf518 "Wolfram Language – Try It Online") Pure function; uses the `|->` syntax, which is new in version 12.2. TIO is running version 12.0, so I've used Function FullForm there. Test cases: ``` 59177: expected True, got True 62379: expected True, got True 7: expected False, got False 121: expected True, got True 187: expected False, got False 312: expected False, got False ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~12~~ 15 bytes ``` &!P_Q.A}Ry`Q`MP ``` [Try it online!](https://tio.run/##K6gsyfj/X00xID5Qz7E2qDIhMME34P9/MyNjc0sA "Pyth – Try It Online") *-2 bytes by using ``` instead of `+k`, +5 to account for primes needing to return false.* [Answer] # [Python 2](https://docs.python.org/2/), 137 bytes ``` lambda n:(p(n)<1)*all(re.search('.*'.join(`d`),`n`)for d in range(2,n)if n%d<1and p(d)) p=lambda n:all(n%i for i in range(2,n)) import re ``` [Try it online!](https://tio.run/##XU7LasMwELzrKxZDiDYIgxxaNyG@5txDb23BqrWO1TprIanQ9uddK31Au4fZHZiZHf@ehomruW8e5tGcn6wB3ksvGQ8aN2YcZaAykgndINflZl0@T45la1tULbfYTwEsOIZg@ESyUoyuB17ZgzZswUuLKHzzm5wDeeUg@9xfHwp39lNIEGhOFFOEBuTVTte1gutqW@8ULJeu9AI3y7XVFQp689Qlsll7F15JwRcezRj/k8tC0Q3UvVDIjuJo3FgoKG5NjAWK3Copyr0@nJeXFgp@fuBewDK5Vy8TXogPjtPigUX3HXwfm4Ye508 "Python 2 – Try It Online") [Answer] # JavaScript (ES6), ~~80~~ 79 bytes Expects a string. ``` f=(n,m=n,k=2)=>n%k?k>n||f(n,m,k+1):m-k&&m.match([...k+''].join`.*`)&&f(n/k,m,k) ``` [Try it online!](https://tio.run/##fcxPC4IwGMfxe69CBumWOtmklsHs1ivoFoHDtHRuC7VOvvelRIf@0HN8vh9@tbiLLm@rax9qcyqsLTnUgeI6kJwinuq53MpUD0M5vQPpE7RRoXRdhZXo8ws8YIyl73lHXJtKZ3iRIdcdcSQnjmxudGeaAjfmDEsIlglhDCDkRJGzb2/F7KOvaMySP50BZ7xn34mm@wKEEvACvwbImoG/AzGh78A@AA "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: n, // n = initially the input as a string, // then an integer m = n, // m = copy of the input k = 2 // k = current divisor candidate ) => // n % k ? // if k is not a divisor of n: k > n || // stop the recursion if k > n f(n, m, k + 1) // otherwise: do a recursive call with k + 1 : // else: m - k && // if k is not equal to m m.match( // and we can find in m: [...k + ''] // the digits of k in the correct order .join`.*` // possibly with other digits in between ) && // then: f(n / k, m, k) // do a recursive call with n / k ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~264~~ ~~236~~ 219 bytes -45 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)! ``` i,j,k,b,n,r,z;char p[9],c[6];l(int*s){b=1;for(j=k=!strcpy(c,s);p[j]*b;j++)for(b=0;c[k]&&(c[k]==p[j]?c[k]=5,b=1,0:1);k++);b=b;}f(int*s){r=1;n=z=atoi(s);for(i=2;n>1;i++)for(;sprintf(p,"%d",i),n%i<1;n/=i)r&=i-z&&l(s);b=r;} ``` [Try it online!](https://tio.run/##fVFbb4IwFH73V3QskqLVCcbbSt0PQR6kwCywQtr6MA2/nR2YF8iSNYRz6HfOdwl89sl58yokL85xgnxtYlHOT/tGkIzkJCKSKHKh/HRUqAp2IeHBOqQFFtJMtHONmEvTUuGM5exFG8Wrb8yJdmgVZOEkotl06rR4xBaUB3lo27gtjLX4R9euCJCQxbvr0BymacQiWqd3AQUCkl3Y0ZQCA29LJphH5d6l4kZOdaVgPMUVscaxRYRD5Fj4sPjGhKNsJmYX2y7a9YgpWjcwjL6OQmIHXUcjBKfLZxJtIB08iAGAbsda7dzNxiLPi7W33Oz6FwPU9dzB53aALl3PQjXtLrpXlwgMGRBdUCg@WkOBbD0Pj@aW1Bpri/waNqFD/87dWePS6F/irvPRdga/qUgkfix3yFBuQNWXnVs9sfofe/FBHiRYTB86t8X6mVwl5qwkeBvVzQ8 "C (gcc) – Try It Online") But it's a shame that C needs all those bytes. I believe that a better approach could be found, so here is an ungolfed and highly commented version that you can use to get yourself into the problem and hopefully develop something better. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> // indexes int i,j,k; // int copy of the input s, used to find prime factors int n; // array to store char* copy of the prime factors of n char p[20]; // bool telling whether a particular digit of p // has been successfully "lobsted" in s int b; // checks whether a given factor p "lobsters" s int l(char*s) { // just copy of s, so that we can preserve the input // to check whether the next factors "lobster" it or not char c[6]; strcpy(c,s); // we don't do it at the start of the k-loop // because we want to continue the loop from // where we left it. 31 do not "lobster" 12345. // After checking for 3, we don't check for 1 from the beginning k = 0; // until p has digits to check for lobsterness for(j=0;p[j];j++) { // assume the digit can't be lobsted in c b = 0; // untill c has digit that could potentially // "lobster" the digit of p for(;c[k];k++) { // if the digit of p double equals one of the digits of c if(p[j]==c[k]) { c[k] = '*'; // delete the digit of c b = 1; // set "lobsted" to true break; } } // if a digit couldn't be lobsted if(!b) break; } // return 0 if at least one digit couldn't be lobsted, // return 1 if all of them were sucessfully lobsted return b; } // find factors of s and launch l() for each factor found int f(char*s) { // n is, initially, the int copy of the input n = atoi(s); // until a factor can be found in n for(i=2;n>1;i++) { // if i is a factor of n if( !(n%i) ) { // if the first factor found is the original number if(i==atoi(s)) return 0; // until i divides n, divide n by i for(;!(n%i);n/=i); // make a char[] copy of the factor i, named p sprintf(p,"%d",i); // if p doesn't "lobster" s if(!l(s)) return 0; } } // reachable only if each factor p "lobsted" the original number s return 1; } int main() { char test[6][6] = { "59177", "62379", "7", "121", "187", "312" }; for(int t = 0; t < 6; t++) { printf("%s", test[t]); for(int dots = 0; dots < 8-strlen(test[t]); dots++) { printf("."); } printf("%d\n\n", f(test[t])); memset(p,0,20); } return 0; } ``` And in case you want to golf from here, rather than start a new approach, here is [the same code without comments](https://tio.run/##hVPbjoIwEH3nKyobI1V0AbNeUvFH0AcpqBWsBurDZsO3u1NAoAraGNueuZ2eGej4QOn9i3Ea34IQrVIRsMvkuG6BNAWKmf@MJYwfJKYxLhAzT2ZEijOHnR53Cbp6jrUtQb/cY0OahinW/jQEK3ek3gz85DX/g9z0@mtQM8UNNEIushr3/SUxTq5Frt5pS06jEUZFxspBLr8OUnAZTKgXbUmkRipecrG9ISu4rvR@9nzxzp8EjlB2MByQF5vkY7fASbiLVDjTXk9ag1TPx82wrBYmCcUt4VLxrNB8/6Q5BxI7cWGGoq@UhLkO4WubsFqUZk3UM3ifYfRJMOa6ZX78YNPWhKoRRVrCv12GSXfm9AozJ6Afpt4PdPOtr1Qo7iCQdShmV4qdd4wb8pX1jIowFTCm8AP16ufrP0t7PtfNGpg50/myCShW27GV60KxTm1HR9lzU4CQyOcYthWawdYx7aU@ej/VzYKw2OKO6ZdZg4tIi8T5aYUWY/j24pAbVXBu@fCJPMpOdEzeTW1FL9jwDQeK@6pOG8tzeE5DAd22TMfCXWMOfc3u938 "C (gcc) – Try It Online") [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 126 bytes ``` param($n)(($u=2..($n-1)|?{!($n%($a=$_)-or(2..($a-1)|?{!($a%$_)}))})|?{$n-match(("$_"|% t*y)-join'.*')}).Count-eq$u.count-and$u ``` [Try it online!](https://tio.run/##bZBda8IwFIbv@yuyEmcitpAW13lRJoi73Zi7G0OyGOmkbVw@2Ib2t3enLauKHnpx@rzPeSndqW@pTSbzPBBKyxpv0n2945oXBJeUEOzSKAxhDxg9POxvYBsQzFO8ooHSpM14n/EB8IrCA@9wU3ArMkJ8vPIPA2RHvzTYqs9yGI6G4IRz5UobyC/sQtGuvFxjV1eeNyMeghmjGZmwOJmMEbbaSXqkU5YkF/QuipPpBW28Dc/NCWIRu9DY/RUxZtGV6/gEUnRAj0ovuMiCp4@tFBbtWxNbaSx48mcHUK5RivCqS7Q0LrcAbvGm81r@9rycO2NV0fW8z7qiZpZOCGlMu6d9Afy7Y3/v@q9QiAQ30m/cvr6Zl@7wvKdPF/@f2qVnzZVX1X8 "PowerShell Core – Try It Online") Takes an integer and returns a boolean ``` ($u=2..($n-1)|?{!($n%($a=$_) # finds the factors of the input -or(2..($a-1)|?{!($a%$_)}))}) # keep them only if they are prime |?{$n-match(("$_"|% t*y)-join'.*')} # add a .* between each digits of each prime factors and check if they match the input .Count-eq$u.count-and$u # Check that the input has factors and that they all match the input ``` ]
[Question] [ Your task is to form an expression equaling \$ 11111111111 \text{ (11 ones)} \$ using only the following characters: `1+()`. Keep in mind that the result is in base 10, and not some other base like binary. Of course, these expressions should follow the [order of operations](https://en.wikipedia.org/wiki/Order_of_operations). Furthermore, the only operations which should be performed are addition, multiplication, and exponentation. Some examples of valid expressions include $$ 1 + 1 + 1 = 3 $$ $$ (1 + 1)(1 + 1) = 4 $$ $$ (1 + 1)^{1 + 1 + 1} = 8 $$ $$ 1 + (1 + 1(1 + 1)^{1 + 1^{1 + 1}}) = 6 $$ Some examples of *invalid* expressions include $$ 11 + 11 \quad | \quad \text{concatenation of ones}$$ $$ 1 + ((1) \quad | \quad \text{unbalanced parentheses} $$ $$ \displaystyle\binom{1}{1 + 1} \quad | \quad \text{disallowed operation} $$ ## Scoring After forming an expression which equals \$ 11111111111 \$, your score will be calculated by the sum of the \$ \text{no. of 1} \$, the \$ \text{no. of +} \$, and the \$ \text{no. of} \$ pairs of parentheses. For example, \$ (1 + 1)(1 + 1)^{1 + (1)} \$ has a score of \$ 12 \$, because it has \$ 6 \$ \$ 1 \$s, \$ 3 \$ pluses, and \$ 3 \$ pairs of parentheses. The submission with the lowest score wins! [Answer] # score = ~~82~~ ~~71~~ 69 (34 ‘1’s + 23 ‘+’s + 12 parenthesis pairs) $$\begin{multline\*} 11111111111 = 1 + (1 + 1) \cdot {} \\ (1 + 1 + 1 + (1 + 1)^{(1 + 1)^{1 + 1 + 1}}(1 + ((1 + 1)(1 + 1 + 1))^{1 + 1 + 1})) \cdot {} \\ (1 + (1 + (1 + 1 + 1)^{1 + 1})^{1 + (1 + 1)^{1 + 1}}) \end{multline\*}$$ [Try it online!](https://tio.run/##ZY9RCoMwDIbfPUXoi4kdA9nzbjIG4joUREvrxoYUdoztel7EtVG36R6ahu//85Poe1s09W5QN21gD3EcH4YUJGAoKY3f9CZ27D7NR3WOGf6N0cJFo/ItiyA3Nct452jwa0XalHWL6ppVGJbdGqWrLFcojp3YgEgSFPSFLjD6JYSMgo0oampl/b2clDcXnyxSQVF2Oq2x9FhnRtVrAYPAS52FzRujvN5xrgTOkTDOOUDmDvrHM@0fryB1wcJEzmR2898WypbW96Wx/o7hDQ "Python 3 – Try It Online") ### Search program in [Rust](https://www.rust-lang.org/) This finds optimal solutions for up to about 8 digit numbers. Don’t try it on anything larger—it will eat all your memory. I constructed the above solution by manually writing \$11111111111 = 1 + 111110 \cdot 100001\$ and searching for optimal solutions to \$111110\$ and \$100001\$. ``` use std::env; #[derive(Clone, Debug)] enum Op { One, Add(u32, u32), Mul(u32, u32), Pow(u32, u32), } fn show(ops: &[Option<Op>], z: u32, prec: u32) { match ops[z as usize].as_ref().unwrap() { Op::One => print!("1"), Op::Add(x, y) => { if prec > 0 { print!("("); } show(ops, *x, 0); print!(" + "); show(ops, *y, 0); if prec > 0 { print!(")"); } } Op::Mul(x, y) => { if prec > 1 { print!("("); } show(ops, *x, 1); show(ops, *y, 1); if prec > 1 { print!(")"); } } Op::Pow(x, y) => { if prec > 2 { print!("("); } show(ops, *x, 3); print!("^{{"); show(ops, *y, 0); print!("}}"); if prec > 2 { print!(")"); } } } } fn main() { for target in env::args().skip(1).map(|arg| arg.parse().unwrap()) { let mut ops: Vec<Option<Op>> = vec![None; target as usize + 1]; let mut vs: Vec<Vec<u32>> = vec![]; while !ops[target as usize].is_some() { let mut v: Vec<u32> = vec![]; let mut visit = |x, op| { if let Some(x) = x { if x <= target { if ops[x as usize].is_none() { ops[x as usize] = Some(op); v.push(x); } } } }; let level = vs.len(); let score = level / 2; match level % 2 { 0 => { if score == 1 { visit(Some(1), Op::One); } for i in 1..score.saturating_sub(1) { let j = score - 1 - i; for u in &vs[i * 2..i * 2 + 2] { for v in &vs[j * 2..j * 2 + 2] { for &x in u { for &y in v { visit(x.checked_pow(y), Op::Pow(x, y)); } } } } } for i in 1..score { let j = score - i; for u in &vs[i * 2 - 1..i * 2 + 1] { for v in &vs[j * 2 - 2..j * 2 + 1] { for &x in u { for &y in v { visit(x.checked_mul(y), Op::Mul(x, y)); } } } } } } 1 => { for i in 1..score.saturating_sub(1) { let j = score - 1 - i; for u in &vs[i * 2..i * 2 + 2] { for v in &vs[j * 2..j * 2 + 2] { for &x in u { for &y in v { visit(x.checked_add(y), Op::Add(x, y)); } } } } } } _ => unreachable!(), } vs.push(v); } print!("{} = ", target); show(&ops, target, 0); println!(); } } ``` [Try it online!](https://tio.run/##7VfbbtpAEH3nKwaqIjslLiZvJiBV7WtLpUp9QRQ5ZoFNjG15vQ4E/Ot1Z40XfA2gpFIjdaUQ2D0zO5cz47HPWRDHnBFgwcwwiBP2G4134xnxaUiUz7brkA58IXd8oU4axOErGHmwbQCuER4lXz7NZgq/6XUAP9T91lduF7e@u4/ZrajRmDvAlrjresyA9njkBdR1bkfecNKBJwMSsOcTK/mqpreuzMBaAoqMn8BkwBl9IhPNZFOfzBVV486jb3qKRCd2eoaBtsJgiNqoEzSVlt5KjZLnwoV1BzaqQB1FxaLzxAgYQrdwIpbUqLTUfu4wyv2SfnbgCq/pFrBSCXyAopqM4KYseJ5tar1tUS4KImsno6C/VhT0Z13Va13VX8NVwcaTrvZey9WbmoT/2m4vS7gUjKJWbXx6L4lPlBbmyqTOoYrmrg@B6S9IANQB7BGGgb8Ylht7oJ6iq9oKa26HezvAD80zfUYyxZitRhuVrHgASdH/JNbtseyHMICQWM3xN@w6fXmjLHIsDn3SL@kJUzXiD9vEUUkG@7ikNoGmaBoFpRONsilzVyTXMXL69@qF6grNOSRlNEDMDhPueruKLGCOBPiHuG@NzIN1BSgFruF2IENQDUqBwqt13iEH41dyqLgKcmhNYpfrFRhSXKHmcbZE@@thUeO83fxOVA6rTUJii7AzzSbIxzKCWa6PrT1FfoReHrJ/WuwP31dWRrfcADLBTdUPKpvOISIi8UoSPV3tyOdNTXyqYyMqjIri0jUtuVNjZsB9M6DOYsr4HSp@xgARiHsMwt7aazT2Gmh9esRlXFzWDtmYwhX0NC35hyXWm5ygjRAOpfD9Xvj@XGGpoL0WGvgZ6IPERkiEZ0ocs7LWrCWxHshs6mFf3aTpOXT/E1x/PmnnI6IXl0olSS6gxEV0EBQ6UkK/nBKoIEML/V@mxQpnHkmLw/zzZmhR3tHr@9n/JvPX2WTie4Rk0@Gd4g2zaSrYxB2fmNbSvLNJU8m8OJVF8DmdDAdhxuUjQg6h2whp1Oqk000Gmsy@7WT43Z/lB@BE3naacg7AWTWOY12sbqx3cem/rbltLlh8PfoD "Rust – Try It Online") [Answer] # By hand - ~~118 112 111~~ 82 $$(1+(1+1)^{(1+1)^{1+1}}(1+(1+1)(1+(1+(1+1)^{1+1})^{1+1})^{1+1}))(1+(1+1+(1+1+1)^{1+1})(1+1+(((1+1)(1+1+1))^{1+1})^{1+1+1}))$$ **[Try it at Wolfram Alpha](https://www.wolframalpha.com/input/?i=%28%28%28%281%2B1%29%5E%281%2B1%2B1%29%28%28%281%2B1%2B1%29%5E%281%2B1%29%29%5E%281%2B1%2B1%2B1%29%29%2B%28%281%2B1%2B1%29%28%28%281%2B1%2B1%29%5E%281%2B1%29%29%5E%281%2B1%29%29%29%2B%281%2B1%29%5E%281%2B1%2B1%29%29%28%28%281%2B1%29%5E%281%2B1%2B1%2B1%29%2B1%29%5E%281%2B1%29%29%2B%28%281%2B1%29%5E%281%2B1%2B1%29%29%29%28%281%2B1%2B1%29%5E%281%2B1%2B1%2B1%29%29%2B2%29%28%281%2B1%2B1%29%5E%281%2B1%29%29%2B1%2B1)** This was found by working my way down from \$11111111111\$ looking for close divisibility considering factors which are close in construction to powers and is: $$(((8(9^4)+(3(9^2))+8)((16+1)^2)+8)81+2)9+2$$ There are \$16\$ parentheses pairs, \$40\$ ones, and \$26\$ additions. --- Previous @**111** $$((1+1)(1+1+1)^{1+1})^{(1+1)^{1+1+1}}+((1+1)(1+1+1)^{1+1}(1+1+1+1+1)^{1+1})^{1+1+1}+((1+1+1)^{1+1+1})^{1+1+1}+((1+1)(1+1+1)^{1+1})^{1+1+1}+(1+1)((1+1+1)^{1+1}+1)$$ **[Try it at Wolfram Alpha](https://www.wolframalpha.com/input/?i=%28%281%2B1%29%281%2B1%2B1%29%5E%281%2B1%29%29%5E%28%281%2B1%29%5E%281%2B1%2B1%29%29%2B%28%281%2B1%29*%28%281%2B1%2B1%29%5E%281%2B1%29%29*%28%281%2B1%2B1%2B1%2B1%29%5E%281%2B1%29%29%29%5E%281%2B1%2B1%29%2B%28%281%2B1%2B1%29%5E%281%2B1%2B1%29%29%5E%281%2B1%2B1%29%2B%28%28%281%2B1%29%281%2B1%2B1%29%5E%281%2B1%29%29%5E%281%2B1%2B1%29%29%2B%281%2B1%29%28%281%2B1%2B1%29%5E%281%2B1%29%2B1%29)** This is $$18^8+450^3+(3^3)^3+18^3+20$$ Where: \$18 = 2\times 9 = (1+1)(1+1+1)^{1+1}\$ \$8 = 2^3 = (1+1)^{1+1+1}\$ \$450 = 18\times 25 = (1+1)(1+1+1)^{1+1}(1+1+1+1+1)^{1+1}\$ \$20 = 2\times (9+1) = (1+1)((1+1+1)^{1+1}+1)\$ [Answer] # 69 operations $$1+(1+((1+1+1)^{1+1}+1)^{1+1+1+1+1})(1+1)\\ \cdot(1+1+1+(1+((1+1+1)(1+1))^{1+1+1})(1+1)^{(1+1)^{1+1+1}})$$ [Try it online!](https://tio.run/##XY9fCsIwDMbfd4rSlyWrCMNnbyKDMisbjK20U5RS2DH0el5kpplDGemf8Pu@pKl9jM3QH2Zzt04cRZ7np7lUQIs2BVaBzrgmS0RMIi6OfzPj1fl1VQHKX3mMONMjmXVtP4K56Q7S03tnbKdrA7IKcidkUYDEH4yJ4T9BYJRsiNnQG0/Tc6d6uFJnWUrM9Pm8xYqw1c70WwGSwENdpK8HZ0gP3FcJ7qPEUhcFMI/iPT3L9/RKUkgWJmolq5vvsTG@9ZS3ztM/5g8 "Python 3 – Try It Online") Verifier thanks to @AndersKaseorg 34 `1`s, 24 `+`s, 11 `()`s. Decomposition, by layers: * 11111111111 = 100001 \* 111110 + 1 * 100001 = 10^5+1 * 111110 = 55555\*2 * 55555 = 3 + 217\*256 * 217 = 6^3+1 * 256 = 2^2^3 I wrote a program to brute-force this, but I'm still working on the program. [Answer] ### score = 22222222221 The sequence $$1 + 1 +\ ... 1$$ where `...` is 11111111108 pairs of `1 +`. I think I can probably shorten this, though. [Answer] # Score: ~~113~~ 111 Breakdown: * ones: \$56\$ * plus signs: \$45\$ * pairs of parentheses: \$10\$ * no multiplication The expression below is in JS syntax, with \$p^q\$ computed as `p**[q]`. ``` (((1+1)**[1+1+1+1]+1+1)**[1+1+1+1]+((1+1)**[1+1+1+1]+1)**[1+1]+((1+1+1)**[1+1]+1+1+1)**[1+1])**[1+1]+((1+1+1+1+1+1)**[1+1+1]+(1+1)**[1+1+1+1])**[1+1]+1+1+1+1+1+1 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/e@nYPtfQ0PDUNtQU0srGkiBYKw2Oh@LCigPKofER@Ghq0KRBYujGYxqDAT@T87PK87PSdXLyU/X8NP8DwA "JavaScript (Node.js) – Try It Online") ## Formula $$(((1+1)^{1+1+1+1}+1+1)^{1+1+1+1}+((1+1)^{1+1+1+1}+1)^{1+1}+((1+1+1)^{1+1}+1+1+1)^{1+1})^{1+1}+((1+1+1+1+1+1)^{1+1+1}+(1+1)^{1+1+1+1})^{1+1}+1+1+1+1+1+1$$ which simplifies down to: $$\big((2^4+2)^4+(2^4+1)^2+(3^2+3)^2\big)^2+(6^3+2^4)^2+6$$ $$=(18^4+17^2+12^2)^2+232^2+6$$ $$=105409^2+232^2+6$$ $$=11111057281+53824+6$$ $$=11111111111$$ [Answer] # Score 92 (46 1's, 33 +'s, 13 parentheses) $$((1+1)(1+1+1)^{1+1})^{(1+1)^{1+1+1}}$$ $$+$$ $$((1+1)^{(1+1)(1+1+1)^{1+1}}+((1+1+1+1+1)(1+1+1)(1+1+1+1))^{1+1}+1)$$ $$\*$$ $$(1+1+1+1+1+1+1)^{1+1+1}$$ `18^8 + (2^18+60^2+1) * 7^3` `18^8 + 91,150,535` Similar to Jonathan Allen but I factorize the 91,150,535. **[Try at wolfram Alpha](https://www.wolframalpha.com/input/?i=%28%281%2B1%29%281%2B1%2B1%29%5E%7B1%2B1%7D%29%5E%7B%281%2B1%29%5E%7B1%2B1%2B1%7D%7D%2B%28%281%2B1%29%5E%7B%281%2B1%29%281%2B1%2B1%29%5E%7B1%2B1%7D%7D%2B%28%281%2B1%2B1%2B1%2B1%29%281%2B1%2B1%29%281%2B1%2B1%2B1%29%29%5E%7B1%2B1%7D%2B1%29%281%2B1%2B1%2B1%2B1%2B1%2B1%29%5E%7B1%2B1%2B1%7D)** **Check calculation Link to TIO, Ruby language** (wolfram alpha website is playing up for me) [Try it online!](https://tio.run/##KypNqvz/v0BBQ8NQ21BTC0SCaDBDE0RrIPggEW24AFYNEGltqKAGCg01EEQjC2ojmwBk/P8PAA "Ruby – Try It Online") [Answer] # 135 = 67 '1's + 49 '+'s + 19 parens 1st attempt with manual calculator fiddling: [![enter image description here](https://i.stack.imgur.com/UIFaR.png)](https://i.stack.imgur.com/UIFaR.png) ### Method * 11111111111 = 21649\*513239 * 21649 = 1 + ((2^4)\*3\*11\*41) * 513239 = 1 + (2\*11\*41\*569) * 569 = 2 + (3^4)\*7 * then the small numbers are built up manually [Try it on Wolfram-Alpha](https://www.wolframalpha.com/input/?i=%281%2B%281%2B1%29%5E%281%2B1%29%5E%281%2B1%29%281%2B1%2B1%29%281%2B1%2B1%2B%281%2B1%29%5E%281%2B1%2B1%29%29%281%2B%281%2B1%2B1%2B1%2B1%29%281%2B1%29%5E%281%2B1%2B1%29%29%29%281%2B%281%2B1%29%281%2B1%2B1%2B%281%2B1%29%5E%281%2B1%2B1%29%29%281%2B%281%2B1%2B1%2B1%2B1%29%281%2B1%29%5E%281%2B1%2B1%29%29%281%2B1%2B%281%2B1%2B1%29%5E%281%2B1%2B1%2B1%29%281%2B1%2B1%2B1%2B1%2B1%2B1%29%29%29) [Answer] # Score ~~115~~ ~~97~~ 93 \$ ((1+1)^{(1+1+1)^{1+1+1}}+((1+1+1)^{1+1+1}+1+1)((1+1+1)^{1+1}(((1+1)^{(1+1)^{1+1}}+1)^{1+1+1}+1+1+1+1+1)+1))((1+1+1)^{1+1+1+1}+1)+1 = (2^{3^3}+(3^3+2)(3^2((2^{2^2}+1)^3+5)+1))(3^4+1)+1 = (2^{27}+29(9(17^3+5)+1)))(82)+1 = (2^{27}+29(44263))(82)+1 = 135501355(82)+1 = 11111111111\$ Found by using @AndersKaseorg's Rust program to generate a solution for \$ 44263 \$. (I was using an old version of his program when I created my previous answer; the current version also finds this answer when I plug in \$ 1283627 \$.) [Answer] # Score 187 (87 `1`s, 68 `+`s, 32 `()` pairs) $$\begin{multline\*} \left(1+1\right)\left(1+1+1+1+1\right)\left(\left(1+1\right)^{\left(1+1+1\right)}+1+1+1\right) \\ \left(\left(1+1\right)^{\left(1+1+1+1+1\right)}+\left(1+1\right)^{\left(1+1+1\right)}+1\right) \\ \left(\left(1+1\right)^{\left(\left(1+1\right)^{\left(1+1+1\right)}\right)}+\left(1+1\right)^{\left(1+1+1\right)}+1+1+1+1+1+1+1\right) \\ \left(\left(1+1\right)^{\left(\left(1+1\right)^{\left(1+1+1\right)}+1+1+1+1+1\right)}+\left(1+1\right)^{\left(\left(1+1\right)^{\left(1+1+1\right)}+1\right)} \right. \\ \left. {} +\left(1+1\right)^{\left(\left(1+1\right)^{\left(1+1+1\right)}\right)}+\left(1+1\right)^{\left(1+1+1+1+1+1+1\right)}+1+1+1\right)+1 \end{multline\*}$$ [Try it online!](https://www.desmos.com/calculator/ezzk4gllap) Based on the fact that $$11111111110 = 2×5×11×41×271×9091$$ The formula is that, based on powers of two. ]
[Question] [ *See also: [Make a move on a Go board](https://codegolf.stackexchange.com/questions/17505/make-a-move-on-a-go-board).* # Task Go is a board game where two players (Black and White) place stones on the intersections of grid lines on a 19×19 board. Black moves first — for example, on D4:        [![go coordinates](https://i.stack.imgur.com/YkKPk.jpg)](https://i.stack.imgur.com/YkKPk.jpg) In this challenge, you must take a Go board coordinate like `D4` as input, and output an ASCII representation of a board with the first move played at the given point. > > ***Note that there is no column I.*** This is, historically, to reduce confusion with J and L. > > > This output consists of 19 lines, each containing 19 characters. The point with the stone on it is marked `O`. Empty points on the board are shown as `.`, except for the nine [star points](http://senseis.xmp.net/?StarPoint) (at `D4`, `D10`, `D16`, `K4`, `K10`, `K16`, `Q4`, `Q10`, and `Q16`), which are marked `*`. For example, given `F5` as an input, your answer’s output must be: ``` ................... ................... ................... ...*.....*.....*... ................... ................... ................... ................... ................... ...*.....*.....*... ................... ................... ................... ................... .....O............. ...*.....*.....*... ................... ................... ................... ``` And given `Q16` as input, your output must be: ``` ................... ................... ................... ...*.....*.....O... ................... ................... ................... ................... ................... ...*.....*.....*... ................... ................... ................... ................... ................... ...*.....*.....*... ................... ................... ................... ``` # Rules * You may write a function that takes the coordinate as an argument, or a program that reads the coordinate from the command line or from `STDIN`. * You may choose to accept input either in lower-case or upper-case, but your answer doesn’t need to handle both. * The input is *always* a single string like `a1` or `T19`, never a string + number or two strings. * If you write a full program, your answer must be printed to `STDOUT` as a string, optionally followed by a trailing newline. If your answer is a function, you may print to `STDOUT`, **or** return a string, **or** return an array/list of strings (rows), **or** return a two-dimensional array or nested list of characters. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The shortest answer in bytes wins. [Answer] # C, ~~212~~ ~~195~~ ~~193~~ ~~181~~ ~~171~~ ~~132~~ ~~103~~ 98 bytes *Saved 1 byte thanks to @FryAmTheEggman, 5 bytes thanks to @orlp* Call `f()` with the position to play (must be capitalized), and it prints out the resulting board. ``` i;f(char*p){for(i=380;i--;)putchar(i%20?i^20*atoi(p+1)+64-*p+(*p>72)?i%6^4|i/20%6^3?46:42:79:10);} ``` [Try it on ideone](http://ideone.com/mkwyCm). [Answer] # [MATL](https://github.com/lmendo/MATL), 33 bytes ``` '*O.'19: 6\4=&*Hj1&)Uw64-t8>-&(P) ``` [**Try it online!**](http://matl.tryitonline.net/#code=JypPLicxOTogNlw0PSYqSGoxJilVdzY0LXQ4Pi0mKFAp&input=UTE2) ### Explanation ``` '*O.' % Push string with needed characters. Will be indexed into 19: % Push numeric vector [1 2 ... 19] 6\4= % 1 for values that equal 4 mod 6, 0 for the rest &* % Multiply by transposed version of itself with broadcast. This gives % the 19×19 board with 0 instead of '.' and 1 instead of '*' H % Push 2. This will correspond to 'O' (stone) j % Input string, such as 'Q16' 1&) % Split into its first char ('Q') and then the rest ('16') U % Convert to number (16) w % Swap, to move 'Q' to top 64- % Subtract 64. Thus 'A' gives 1, 'B' gives 2 etc t8>- % Duplicate. Subtract 1 if it exceeds 8. This corrects for missing 'I' &( % Fill a 2 at coordinates given by the number and the letter P % Flip upside down, because matrix coordinates start up, not down ) % Index the string '*O.' with the 19×19 array containing 0,1,2. % Implicitly display ``` [Answer] ## C (gcc), ~~132~~ ~~128~~ 109 ``` i;m;f(char*s){for(i=380;i--;putchar(m?m^84-*s+(*s>73)|(i/20+1)^atoi(s+1)?m%6^4|i/20%6^3?46:42:79:10))m=i%20;} ``` [Ideone](https://ideone.com/wjUEbn) A function that prints the board to STDOUT. Requires the letter coordinate to be capital. Printing in one loop seems to be slightly shorter than the previous nested loop approach. [Answer] ## MATLAB, 135 bytes A first attempt, nothing clever, just to see how much better others can do: ``` function go(a) b=repmat('.',19); b(4:6:end,4:6:end)='*'; a=sscanf(a,'%c%d'); a(1)=a(1)-64; if a(1)>8 a(1)=a(1)-1; end b(20-a(2),a(1))='0' ``` Usage: ``` go('T19') ``` [Answer] # Ruby, ~~93~~ 91 bytes Takes input on the command line, e.g. `$ ruby script.rb Q16`. ``` 19.downto(1){|c|puts ([*?A..?T]-[?I]).map{|d|d+c.to_s==$*[0]??O:"DKQ"[d]&&c%6==4??*:?.}*""} ``` Test it on repl.it (wrapped in a lambda there since repl.it doesn't take command line arguments: <https://repl.it/CkvT/1> ## Ungolfed ``` 19.downto(1) do |row| puts ([*?A..?T] - [?I]).map {|column| if column + row.to_s == ARGV[0] "O" elsif "DKQ"[column] && row % 6 == 4 "*" else "." end }.join } ``` [Answer] ## Go, ~~319~~ 286 bytes ``` import(."strconv" ."strings") func g(c string)(s string){p:=SplitN(c,"",2) n,_:=Atoi(p[1]) for i:=19;i>0;i--{ for j:= 'a';j<'t';j++{ if j=='i'{ }else if n==i&&ContainsRune(p[0],j){s+="o" }else if((i==4||i==10||i==16)&&(j=='d'||j=='k'||j=='q')){s+="*" }else{s+="."}} s+="\n"} return} ``` Probably golfable quit a bit, i'm a begginner [Answer] # Ruby, ~~130~~ ~~128~~ 121 + 3 (`-n` flag) = 124 bytes Switched `-p` to `-n` because `puts b` is one byte shorter than `$_=b*$/` ``` ~/(.)(.+)/ b=(1..19).map{?.*19} (a=3,9,15).map{|i|a.map{|j|b[i][j]=?*}} b[19-$2.to_i][([*?A..?T]-[?I]).index$1]=?o puts b ``` [Answer] # Python, ~~148~~ ~~145~~ ~~136~~ ~~130~~ ~~121~~ ~~119~~ 116 Bytes *-3 Bytes thanks to @RootTwo* ``` lambda x,r=range(19):[[".*o"[[i%6==j%6==3,2][j==ord(x[0])-(x>"I")-65and-~i==int(x[1:])]]for j in r]for i in r[::-1]] ``` anonymous lambda function, takes input of the form "A1" (big letters) and outputs a list of lists of chars (len==1 strings in Python) [Answer] ## [><>](http://esolangs.org/wiki/Fish), ~~98~~ 96 bytes ``` '_U'i-:b)-0\ +*a$%cv?(0:i< {*+{4*\+ +4gf-o>1-:?!;:{:}=3*&::aa+%::0=2*&+&6%1-}-aa+,6%{*9=& =9^^ ``` Note that there is an `0x14` in the first row after the first `'`, and an `0x19` between the `9` and the first `^` of the last line. [Try it online!](http://fish.tryitonline.net/#code=JxRfVSdpLTpiKS0wXAorKmEkJWN2PygwOmk8CnsqK3s0KlwrCis0Z2Ytbz4xLTo_ITs6ezp9PTMqJjo6YWErJTo6MD0yKiYrJjYlMS19LWFhKyw2JXsqOT0mCj05GV5e&input=VDE) The input is mapped so that `A-T` become `1-19` (with 0 denoting an imaginary "newline" column) and the integer row number is decremented by 1. The program does a loop from 379 down to 0, choosing a char from the bottom row as it goes (offset by 15, to account for the fact that you can't enter a literal newline in the codebox). Newlines are checked via `i % 20 == 0`, and star points are checked by `((i%20-1)%6)*((i/20)%6) == 9`. [Answer] # F#, ~~241 237 225 216 214~~ 211 bytes ``` let G(c:string)=for k=1 to 380 do printf(if k%20=0 then"\n"elif"_ABCDEFGHJKLMNOPQRST".IndexOf c.[0]=k%20&&19-k/20=int(c.Substring 1)then"o"elif(k%20=4||k%20=10||k%20=16)&&(k/20=3||k/20=9||k/20=15)then"*"else".") ``` Tricky one this one ... I wonder if it can be made shorter. Edit: fixed a bug, added numbers some places removed numbers in others, somehow ended up with the same count. ~~Might try shuffling numbers around later~~ Done. Edit2: saved more bytes by spelling out one of the conditionals, counter intuitively. Edit3: Fixed another bug: should work now for pieces on the last rank and managed to save two bytes while I am at it, somehow. [Try it online](https://ideone.com/UPFfFf) [Answer] # [Retina](https://github.com/m-ender/retina), ~~134~~ ~~129~~ 122 bytes **11 bytes thanks to Martin Ender, and for inspiration of 1 more.** ``` S2=` [K-S] 1$& T`xL`d9d .+ $* $ aaab a bbbcbb b|c ¶$0 c ddd. d ...*.. b 19$*. 1(1)*¶1(1)*¶((?<-2>.+¶)*(?<-1>.)*). $3O O^$` ``` [Try it online!](http://retina.tryitonline.net/#code=UzI9YApbSy1TXQoxJCYKVGB4TGBkOWQKLisKJCoKJAphYWFiCmEKYmJiY2JiCmJ8YwrCtiQwCmMKZGRkLgpkCi4uLiouLgpiCjE5JCouCjEoMSkqwrYxKDEpKsK2KCg_PC0yPi4rwrYpKig_PC0xPi4pKikuCiQzTwpPXiRg&input=UTE) [Answer] ## Perl, 132 bytes *-3 bytes thanks to [@Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings)* ``` @v=eval"[('.')x19],"x19;@{$v[$_]}[@t]=("*")x3for@t=(3,9,15);pop=~/\d+/;$v[19-$&][($t=ord$`)-65-($t>73)]=O;map{say}map{join"",@$_}@v; ``` Takes command line input. Needs `-M5.010` tu run. For instance : ``` $ cat go_board.pl @v=eval"[('.')x19],"x19;@{$v[$_]}[@t]=("*")x3for@t=(3,9,15);pop=~/\d+/;$v[19-$&][($t=ord$`)-65-($t>73)]=O;map{say}map{join"",@$_}@v; $ perl -M5.010 go_board.pl Q16 ``` I think this could be shorter, but I couldn't figure out how... please let me know if you do! [Answer] ## Batch, ~~322~~ ~~310~~ 308 bytes ``` @echo off set/pi= set/aa=0,b=1,c=2,d=3,e=4,f=5,g=6,h=7,j=8,k=9,l=10,m=11,n=12,o=13,p=14,q=15,r=16,s=17,t=18,x=%i:~1%-1,y=%i:~,1%,z=y+1 for /l %%r in (18,-1,0)do call:l %%r exit/b :l set s=...*.....*.....*... call set t=%%s:~%1,1%% if %x%==%1 call set s=%%s:~,%y%%%o%%s:~%z%%% call echo %%s:.*=.%t%%% ``` Explanation: Starts by prompting for the stone on stdin. Then, sets variables for each possible column, so that it can evaluate the first character of the stone as a variable to get the `y` coordinate. Subtracts 1 from the `x` coordinate because it's 1-indexed and we want 0-indexed and also computes `z=y+1` as it will need that later. Then, loops `r` from 18 down to 0 for each row. Takes the string `...*.....*.....*...` and extracts the character at the `r`th position for later. On the `x`th row, the `y`th character is replaced with an `o`. Finally, the `.*`s are replaced with a `.` plus the previously extracted character; this is a no-op on rows 4, 10 and 16 but this is the shortest way to achieve that. (I have to use `.*` because replacing `*` is apparently illegal in Batch.) [Answer] ## PowerShell v2+, ~~157~~ 152 bytes ``` $x,$y=[char[]]$args[0];$a=,0*19;0..18|%{$a[$_]=,'.'*19};3,9,15|%{$i=$_;3,9,15|%{$a[$_][$i]='*'}};$a[-join$y-1][$x-65-($x-gt73)]='O';$a[18..0]|%{-join$_} ``` *(I think I ran into some sort of weird glitch with the comma-operator, so the array construction is a bit longer than it should be)* Takes input as an uppercase string via `$args[0]`, casts it as a char-array, stores the first letter into `$x` and the remaining letters into `$y`. This effectively splits the input into letter/number. We then construct our multidimensional array `$a`. We pre-populate an array of size `19` with `0`s using the comma-operator. We then loop `0..18` to make each element `$a[$_]` equal instead an array of periods, again using the comma operator. *(NB - In theory, this should be able to be condensed to `$a=,(,'.'*19)*19`, but that doesn't seem to work right with the indexing assignment ... I wound up getting whole columns set to `*`)* Next, we loop twice over `3,9,15` to set the corresponding elements to `*`. We then index into it in the right spot to set the stone `O`. To do so, we subtract `65` from `$x` (i.e, ASCII "A" is 65, and we're zero-indexed), and subtracts an additional one using a Boolean-to-int cast if `$x` is bigger than `73` (i.e., ASCII "I"). Now, our output is reversed (i.e., the upper-left would be `A1`), so we need to reverse the array with `$a[18..0]`. Finally, we output each line `-join`ed together to form a string. [Answer] # [><>](http://esolangs.org/wiki/Fish), 124 bytes Uses the exact same approach as my C answer. Input must be a capital letter followed by a decimal number. ``` 88*i:&-&'I')+0 v *a&-'0'v!?)0:i&<+ +**2a&~/*a'&'& :;!?:-1<o'O'v!?=&:& {*?!v'*'o63.>:6%4=}:a4*+'x'%aa*) *2a:/ av?% .37o<'.'< ``` [Try it online!](http://fish.tryitonline.net/#code=ODgqaTomLSYnSScpKzAgdgoqYSYtJzAndiE_KTA6aSY8KworKioyYSZ-LyphJyYnJgo6OyE_Oi0xPG8nTyd2IT89JjomCnsqPyF2JyonbzYzLj46NiU0PX06YTQqKyd4JyVhYSopCioyYTovICBhdj8lCi4zN288Jy4nPA&input=QTE) ## Explanation: ``` 88*i:&-&'I')+0 v 'Push 64-<first input char>+(<first input char> > 'I') *a&-'0'v!?)0:i&<+ 'Set register to 0, parse decimal integer into register. +**2a&~/*a'&'& 'Pop the -1 (EOF) from stack, multiply register by 20. 'Add result of first line to register. 'Push 380 onto stack. :;!?:-1<o'O'v!?=&:& 'Main loop, while top of stack is not 0. 'Subtract 1 from top of stack (loop counter) 'If current index is the playing piece index, print 'O' {*?!v'*'o63.>:6%4=}:a4*+'x'%aa*) 'If (index%6)=4 and (index+40)%120>100, print '*' *2a:/ av?% 'If (index%20)=0, print newline .37o<'.'< 'Otherwise, print '.' ``` [Answer] ## JavaScript, 138 bytes ``` s=>[...t="...*.....*.....*..."].map((c,i)=>t.replace(/\*/g,c).replace(/./g,(c,j)=>x-j|19-i-s.slice(1)?c:'o'),x=parseInt(s[0],36)*.944-9|0) ``` Returns an array of strings. Explanation: ``` s=>[... Parameter t="...*.....*.....*..." Pattern of lines 4, 10 and 16 ].map((c,i)=> Loop 19 times t.replace(/\*/g,c) Change the `*` to `.` on other lines .replace(/./g,(c,j)=> Loop over each character x-j|19-i-s.slice(1)?c:'o'), Change to o at the appropriate position x=parseInt(s[0],36)*.944-9|0) Compute the column number from the letter ``` [Answer] # R, ~~169~~ 161 bytes ``` f=function(p){S=substr;N=rep(".",114);N[61+6*0:2]="*";M=matrix(N,19,19);M[(S(p,2,3):1)[1],which(LETTERS[-9]==S(p,1,1))]="O";for(i in 19:1)cat(M[i,],"\n",sep="")} ``` With indents and newlines: ``` f=function(p){ S=substr N=rep(".",114) # 6 lines of dots N[61+6*0:2]="*" # Place the hoshis M=matrix(N,19,19) # Make the 19x19 board using vector recycling M[(S(p,2,3):1)[1], #grab and force coerce the row number to integer which(LETTERS[-9]==S(p,1,1))]="O" #Place the first stone for(i in 19:1) cat(M[i,],"\n",sep="") } ``` Usage: ``` > f("A19") O.................. ................... ................... ...*.....*.....*... ................... ................... ................... ................... ................... ...*.....*.....*... ................... ................... ................... ................... ................... ...*.....*.....*... ................... ................... ................... > f("D4") ................... ................... ................... ...*.....*.....*... ................... ................... ................... ................... ................... ...*.....*.....*... ................... ................... ................... ................... ................... ...O.....*.....*... ................... ................... ................... > f("K10") ................... ................... ................... ...*.....*.....*... ................... ................... ................... ................... ................... ...*.....O.....*... ................... ................... ................... ................... ................... ...*.....*.....*... ................... ................... ................... ``` [Answer] # Lua, 187 Bytes ``` function g(i)i:gsub("(%a+)(%d+)",function(a,b)q=string.byte(a)-64 r=b+0 end)for x=1,19 do s=""for y=1,19 do s=s..(x+y*19==r+q*19 and"o"or(x-4)%6+(y-4)%6==0 and"*"or"-")end print(s)end end ``` I don't feel too bad about 187 for this particular project. Lua still comes out as very clunky for Golfing, but I'm pretty proud of how far I can go with it. [Answer] # PHP, 280 268 263 261 255 218 216 bytes ``` <?php $a=ucfirst($argv[1]);$x=substr($a,0,1);$y=substr($a,1);$s=['DKQ',4,16,10];$i=85;while(64<$i--){$j=0;while($j++<20){echo($x==chr($i)&&$y==$j)?'O':((strpos($s[0],chr($i))>-1&&in_array($j,$s))?'*':'.');}echo"\n";} ``` My first golf. Usage: Save as a PHP file and call it by `php filename.php coordinate` e.g. `php go.php k13` ]
[Question] [ Take a 2-dimensional grid and draw a number of line segments on it to represent mirrors. Now pick a point to place a theoretical laser and an angle to define the direction it's pointing. The question is: if your follow the laser beam path for some specified distance, what coordinate point are you at? Example: ![laser example](https://i.stack.imgur.com/QrrmD.png) In this image, `L` is the location of the laser, `t` is it's angle (measured from the positive X axis), `M1`, `M2`, and `M3` are all line segment mirrors, and `E` is the point on the laser beam path after `D = d1 + d2 + d3 + d4` units, starting from `L`. # Goal Write the shortest program (in bytes) that outputs `E` given `L`, `t`, `D`, and a list of mirrors. (Use <http://mothereff.in/byte-counter> to count bytes.) # Input Format Input will come from stdin in the format: ``` Lx Ly t D M1x1 M1y1 M1x2 M1y2 M2x1 M2y1 M2x2 M2y2 ... ``` * All the values will be floating points matching this regex: `[-+]?[0-9]*\.?[0-9]+`. * There is always exactly one space between each number. * Requiring quotes around the input is allowed. * `t` is in degrees, but not necessarily in the `[0, 360)` range. (If you prefer you may use radians instead, just say so in your answer.) * `D` may be negative, effectively rotating the laser 180 degrees. `D` may also be 0. * There may be arbitrarily many mirrors (including none at all). * The order of the mirrors should not matter. * You may assume the input will come in multiples of 4 numbers. e.g. `Lx Ly t` or `Lx Ly t D M1x1` are invalid and will not be tested. No input at all is also invalid. The layout above might be input as: ``` 1 1 430 17 4.8 6.3 6.2 5.3 1.5 4.8 3.5 6 6.3 1.8 7.1 3 ``` (Note that the image was drawn freehand and these values are only approximations. Martin Büttner's input values of ``` 1 1 430 17 4.8 5.3 6.2 4.3 1.5 4.8 3.5 6 6.3 1.8 7.1 3 ``` will give more collisions though they do not match the sketch.) # Output Format Output should go to stdout in the format: ``` Ex Ey ``` These are also floats and may be in exponential form. # Notes * Mirrors may intersect each other. * Both sides of mirrors are reflective. * The beam may hit the same mirror many times. * The beam goes on forever. # Undefined Cases You may assume that the cases where * the laser starts on a mirror line segment * the laser beam hits the endpoint of a mirror * the laser beam hits the intersection between two mirrors are undefined and will not be tested. Your program may do anything if these occur, including throw an error. # Bonus Just for fun, I will award 200 bounty points to the highest voted submission that outputs a graphical representation of the problem (you could even write an interactive script). These bonus submission do not need to be golfed and can be lenient with how input and output are handled. They are distinct from the actual golfed submissions but **both should be submitted in the same answer**. *Note:* Only submitting a bonus answer is fine, you just wont be the accepted answer. To be accepted you must exactly follow the input/output spec (e.g. output only involves `Ex Ey`, not images), and be the shortest. [Answer] ## Ruby, 327 bytes (scroll to the bottom) ## Mathematica, bonus answer ![enter image description here](https://i.stack.imgur.com/jOilg.gif) I'm only going for the graphical submission right now. I might port this to Ruby later and golf it if I feel like it. ``` (* This function tests for an intersection between the laser beam and a mirror. r contains the end-points of the laser, s contains the end-points of the mirror. *) intersect[r_, s_] := Module[ {lr, dr, nr, ds, ns, \[Lambda]}, (* Get a unit vector in the direction of the beam *) dr = r[[2]] - r[[1]]; lr = Norm@dr; dr /= lr; (* Get a normal to that vector *) nr = {dr[[2]], -dr[[1]]}; (* The sign of dot product in here depends on whether that end-point of the mirror is to the left or to the right of the array. Return infinity if both ends of s are on the same side of the beam. *) If[Apply[Times, (s - {r[[1]], r[[1]]}).nr] > 0, Return[\[Infinity]]]; (* Get a unit vector along the mirror. *) ds = s[[2]] - s[[1]]; ds /= Norm@ds; (* And a normal to that. *) ns = {ds[[2]], -ds[[1]]}; (* We can write the beam as p + λ*dr and mirror as q + μ*ds, where λ and μ are real parameters. If we set those equal and solve for λ we get the following equation. Since dr is a unit vector, λ is also the distance to the intersection. *) \[Lambda] = ns.(r[[1]] - s[[1]])/nr.ds; (* Make sure that the intersection is before the end of the beam. This check could actually be slightly simpler (see Ruby version). *) If[\[Lambda] != 0 && lr/\[Lambda] < 1, Infinity, \[Lambda]] ]; (* This function actually does the simulation and generates the plot. *) plotLaser[L_, t_, distance_, M_] := Module[ {coords, plotRange, points, e, lastSegment, dLeft, \[Lambda], m, p, d, md, mn, segments, frames, durations}, (* This will contain all the intersections along the way, as well as the starting point. *) points = {L}; (* The tentative end point. *) e = L + distance {Cos@t, Sin@t}; (* This will always be the currently last segment for which we need to check for intersections. *) lastSegment = {L, e}; (* Keep track of the remaining beam length. *) dLeft = distance; While[True, (* Use the above function to find intersections with all mirrors and pick the first one (we add a small tolerance to avoid intersections with the most recent mirror). *) {\[Lambda], m} = DeleteCases[ SortBy[{intersect[lastSegment, #], #} & /@ M, #[[1]] &], i_ /; i[[1]] < 1*^-10][[1]]; (* If no intersection was found, we're done. *) If[\[Lambda] == \[Infinity], Break[]]; (* Reduce remaining beam length. *) dLeft -= \[Lambda]; (* The following lines reflect the beam at the mirror and add the intersection to our list of points. We also update the end-point and the last segment. *) p = lastSegment[[1]]; d = -Subtract @@ lastSegment; d /= Norm@d; md = -Subtract @@ m; md /= Norm@md; mn = {md[[2]], -md[[1]]}; AppendTo[points, p + \[Lambda]*d]; d = -d + 2*(d - d.mn*mn); e = Last@points + dLeft*d; lastSegment = {Last@points, e}; ]; (* Get a list of all points in the set up so we can determine the plot range. *) coords = Transpose@Join[Flatten[M, 1], {L, e}]; (* Turn the list of points into a list of segments. *) segments = Partition[points, 2, 1]; (* For each prefix of that list, generate a frame. *) frames = Map[ Graphics[ {Line /@ M, Red, Point@L, Line /@ segments[[1 ;; #]]}, PlotRange -> { {Min@coords[[1]] - 1, Max@coords[[1]] + 1}, {Min@coords[[2]] - 1, Max@coords[[2]] + 1} } ] &, Range@Length@segments]; (* Generate the initial frame, without any segments. *) PrependTo[frames, Graphics[ {Line /@ M, Red, Point@L}, PlotRange -> { {Min@coords[[1]] - 1, Max@coords[[1]] + 1}, {Min@coords[[2]] - 1, Max@coords[[2]] + 1} } ] ]; (* Generate the final frame including lastSegment. *) AppendTo[frames, Graphics[ {Line /@ M, Red, Point@L, Line /@ segments, Line[lastSegment], Point@e}, PlotRange -> { {Min@coords[[1]] - 1, Max@coords[[1]] + 1}, {Min@coords[[2]] - 1, Max@coords[[2]] + 1} } ]]; (*Uncomment to only view the final state *) (*Last@frames*) (* Export the frames as a GIF. *) durations = ConstantArray[0.1, Length@frames]; durations[[-1]] = 1; Export["hardcoded/path/to/laser.gif", frames, "GIF", {"DisplayDurations" -> durations, ImageSize -> 600}]; (* Generate a Mathematica animation form the frame. *) ListAnimate@frames ]; ``` You can call it like ``` plotLaser[{1, 1}, 7.50492, 95, { {{4.8, 5.3}, {6.2, 4.3}}, {{1.5, 4.8}, {3.5, 6}}, {{6.3, 1.8}, {7.1, 3}}, {{5, 1}, {4, 3}}, {{7, 6}, {5, 6.1}}, {{8.5, 2.965}, {8.4, 2}}, {{8.5, 3.035}, {8.6, 4}}, {{8.4, 2}, {10.5, 3}}, {{8.6, 4}, {10.5, 3}} }] ``` That will give you an animation in Mathematica and also export a GIF (the one at the top for this input). I've slightly extended the OPs example for this, to make it a bit more interesting. ### More examples A tube with slightly diverging walls but a closed end: ``` plotLaser[{0, 0}, 1.51, 200, { {{0, 1}, {20, 1.1}}, {{0, -1}, {20, -1.1}}, {{20, 1.1}, {20, -1.1}} }] ``` ![enter image description here](https://i.stack.imgur.com/DFUW5.gif) An equilateral triangle and an initial direction that is almost parallel to one of the sides. ``` plotLaser[{-1, 0}, Pi/3 + .01, 200, { {{-2.5, 5 Sqrt[3]/6}, {2.5, 5 Sqrt[3]/6}}, {{0, -5 Sqrt[3]/3}, {-2.5, 5 Sqrt[3]/6}}, {{0, -5 Sqrt[3]/3}, {2.5, 5 Sqrt[3]/6}} }] ``` ![enter image description here](https://i.stack.imgur.com/oIWKv.gif) One more: ``` plotLaser[ {0, 10}, -Pi/2, 145, { {{-1, 1}, {1, -1}}, {{4.5, -1}, {7.5, Sqrt[3] - 1}}, {{11, 10}, {13, 10}}, {{16.5, Sqrt[3] - 1}, {19.5, -1}}, {{23, -1}, {25, 1}}, {{23, 6}, {25, 4}}, {{18, 6}, {20, 4}}, {{18, 9}, {20, 11}}, {{31, 9}, {31.01, 11}}, {{24.5, 10.01}, {25.52, 11.01}}, {{31, 4}, {31, 6}}, {{25, 4.6}, {26, 5.6}}, {{24.5, 0.5}, {25.5, -0.5}}, {{31, -1}, {33, 1}}, {{31, 9}, {33, 11}}, {{38, 10.5}, {38.45, 9}} } ] ``` ![enter image description here](https://i.stack.imgur.com/L2VYw.gif) ## Ruby, golfed answer ``` x,y,t,p,*m=gets.split.map &:to_f u=q=Math.cos t v=r=Math.sin t loop{k=i=p u=x+q*p v=y+r*p m.each_slice(4){|a,b,c,d|((a-u)*r-(b-v)*q)*((c-u)*r-(d-v)*q)>0?next: g=c-a h=d-b l=(h*(x-a)-g*(y-b))/(r*g-q*h) f=(g*g+h*h)**0.5 t,k,i=g/f,h/f,l if l.abs>1e-9&&l/i<1} i==p ?abort([u,v]*' '): p-=i x+=q*i y+=r*i n=q*k-r*t q-=2*n*k r+=2*n*t} ``` This is basically a direct translation of the Mathematica solution to Ruby, plus some golfing and making sure it meets the I/O criteria. [Answer] # Python 3(~~421C 390C~~,366C) Use `builtin.complex` as 2d vector. So ``` dot = lambda a, b: (a.conjugate() * b).real cross = lambda a, b: (a.conjugate() * b).imag ``` In order to beat the 368C Ruby solution, I've find a quite compact method to calculate point reflection along a mirror. And also used some complex algebra to reduce more characters. These can be easily found in the ungolfed code. Here's the golfed version. ``` C=lambda a,b:(abs(a)**2/a*b).imag J=1j x,y,r,d,*a=map(float,input().split()) p=x+y*J q=p+d*2.718281828459045**(r*J) M=[] while a:x,y,z,w,*a=a;M+=[(x+y*J,z-x+w*J-y*J)] def T(m):x,y=m;d=C(y,r)+1e-9;t=C(y,x-p)/d;s=C(r,x-p)/d;return[1,t][(1e-6<t<1)*(0<s<1)] while 1: r=q-p;m=f,g=min(M,key=T) if T(m)==1:break p+=r*T(m);q=(q/g-f/g).conjugate()*g+f print(q.real,q.imag) ``` ## Ungolfed ``` # cross product of two vector # abs(a)**2 / a == a.conjugate() cross = lambda a, b: (abs(a)**2 / a * b).imag # Parse input x, y, angle, distance, *rest = map(float, input().split()) start = x + y * 1j # e = 2.718281828459045 # Using formula: e**(r*j) == cos(r) + sin(r) * j end = start + distance * 2.718281828459045 ** (angle * 1j) mirrors = [] while rest: x1, y1, x2, y2, *rest = rest # Store end point and direction vector for this mirror mirrors.append((x1 + y1 * 1j, (x2 - x1) + (y2 - y1) * 1j)) def find_cross(mirror): # a: one end of mirror # s: direction vector of mirror a, s = mirror # Solve (t, r) for equation: start + t * end == a + r * s d = cross(s, end - start) + 1e-9 # offset hack to "avoid" dividing by zero t = cross(s, a - start) / d r = cross(end - start, a - start) / d return t if 1e-6 < t < 1 and 0 < r < 1 else 1 def reflect(p, mirror): a, s = mirror # Calculate reflection point: # 1. Project r = p - a onto a coordinate system that use s as x axis, as r1. # 2. Take r1's conjugate as r2. # 3. Recover r2 to original coordinate system as r3 # 4. r3 + a is the final result # # So we got conjugate((p - a) * conjugate(s)) / conjugate(s) + a # which can be reduced to conjugate((p - a) / s) * s + a return ((p - a) / s).conjugate() * s + a while 1: mirror = min(mirrors, key=find_cross) if find_cross(mirror) == 1: break start += (end - start) * find_cross(mirror) end = reflect(end, mirror) print(end.real, end.imag) ``` # Bonus: HTML, Coffeescript, Realtime Adjustment & Calculation This is, you drag any end points(or lazer, mirros), then the track is rendered. It also support two types of input, the one described in the question and the one used by @Martin Büttner. The scaling is also adjusted automatically. For now it doesn't has animation. Maybe I'll improve it later. However, dragging the white points and you can see another type of animation. [Try it online here](http://zhanruiliang.github.io/where_does_the_lazer_go/) yourself, it's funny! The whole project can be found [Here](https://github.com/ZhanruiLiang/where_does_the_lazer_go) ![case 1](https://i.stack.imgur.com/UqtAB.png) ![case 2](https://i.stack.imgur.com/J8y71.png) ## Update Here I provide an interesting case: ``` 0 0.6 -0.0002 500.0 0.980785280403 -0.195090322016 1.0 0.0 1.0 0.0 0.980785280403 0.195090322016 0.980785280403 0.195090322016 0.923879532511 0.382683432365 0.923879532511 0.382683432365 0.831469612303 0.55557023302 0.831469612303 0.55557023302 0.707106781187 0.707106781187 0.707106781187 0.707106781187 0.55557023302 0.831469612303 0.55557023302 0.831469612303 0.382683432365 0.923879532511 0.382683432365 0.923879532511 0.195090322016 0.980785280403 0.195090322016 0.980785280403 6.12323399574e-17 1.0 6.12323399574e-17 1.0 -0.195090322016 0.980785280403 -0.195090322016 0.980785280403 -0.382683432365 0.923879532511 -0.382683432365 0.923879532511 -0.55557023302 0.831469612303 -0.55557023302 0.831469612303 -0.707106781187 0.707106781187 -0.707106781187 0.707106781187 -0.831469612303 0.55557023302 -0.831469612303 0.55557023302 -0.923879532511 0.382683432365 -0.923879532511 0.382683432365 -0.980785280403 0.195090322016 -0.980785280403 0.195090322016 -1.0 1.22464679915e-16 -1.0 1.22464679915e-16 -0.980785280403 -0.195090322016 -0.980785280403 -0.195090322016 -0.923879532511 -0.382683432365 -0.923879532511 -0.382683432365 -0.831469612303 -0.55557023302 -0.831469612303 -0.55557023302 -0.707106781187 -0.707106781187 -0.707106781187 -0.707106781187 -0.55557023302 -0.831469612303 -0.55557023302 -0.831469612303 -0.382683432365 -0.923879532511 -0.382683432365 -0.923879532511 -0.195090322016 -0.980785280403 -0.195090322016 -0.980785280403 -1.83697019872e-16 -1.0 -1.83697019872e-16 -1.0 0.195090322016 -0.980785280403 0.195090322016 -0.980785280403 0.382683432365 -0.923879532511 0.382683432365 -0.923879532511 0.55557023302 -0.831469612303 0.55557023302 -0.831469612303 0.707106781187 -0.707106781187 0.707106781187 -0.707106781187 0.831469612303 -0.55557023302 0.831469612303 -0.55557023302 0.923879532511 -0.382683432365 0.923879532511 -0.382683432365 0.980785280403 -0.195090322016 ``` And the result is: ![circle](https://i.stack.imgur.com/HbnRZ.png) [Answer] ## HTML JavaScript, ~~10,543~~, ~~947~~ 889 I fixed a bug and made sure the output meets the question spec. The webpage below has the golfed version and also the graphical bonus version. I also fixed a bug pointed out by @Ray which saved 58 characters. (Thanks Ray.) You can also run the golfed code in a JavaScript console. (Now I'm using a 2mW green laser.) **Golf Code** ``` a=prompt().split(" ").map(Number);M=Math,Mc=M.cos,Ms=M.sin,P=M.PI,T=2*P,t=true;l=new S(a[0],a[1],a[0]+a[3]*Mc(a[2]),a[1]+a[3]*Ms(a[2]));m=[];for(i=4;i<a.length;)m.push(new S(a[i++],a[i++],a[i++],a[i++]));f=-1;for(;;){var h=!t,d,x,y,n,r={};for(i=0;i<m.length;i++)if(i!=f)if(I(l,m[i],r))if(!h||r.d<d){h=t;d=r.d;x=r.x;y=r.y;n=i}if(h){l.a=x;l.b=y;l.e-=d;l.f=2*(m[f=n].f+P/2)-(l.f+P);l.c=l.a+l.e*Mc(l.f);l.d=l.b+l.e*Ms(l.f);}else break;}alert(l.c+" "+l.d);function S(a,b,c,d){this.a=a;this.b=b;this.c=c;this.d=d;this.e=D(a,b,c,d);this.f=M.atan2(d-b,c-a)}function D(a,b,c,d){return M.sqrt((a-c)*(a-c)+(b-d)*(b-d))}function I(l,m,r){A=l.a-l.c,B=l.b-l.d,C=m.a-m.c,L=m.b-m.d,E=l.a*l.d-l.b*l.c,F=m.a*m.d-m.b*m.c,G=A*L-B*C;if(!G)return!t;r.x=(E*C-A*F)/G;r.y=(E*L-B*F)/G;H=r.d=D(l.a,l.b,r.x,r.y),O=D(l.c,l.d,r.x,r.y),J=D(m.a,m.b,r.x,r.y),K=D(m.c,m.d,r.x,r.y);return(H<l.e)&&(O<l.e)&&(J<m.e)&&(K<m.e);} ``` **Input** ``` 1 1 7.50492 17 4.8 6.3 6.2 5.3 1.5 4.8 3.5 6 6.3 1.8 7.1 3 ``` **Output** ``` 14.743305098514739 3.759749038188634 ``` You can test it here: <http://goo.gl/wKgIKD> ![enter image description here](https://i.stack.imgur.com/Ld3Qm.png) **Explanation** The code in the webpage is commented. Basically I calculate the intersection of the laser with every mirror assuming the laser and mirrors are infinitely long. Then I check if the intersection is within the finite length of the mirror and the laser. Then I take the closest intersection, move the laser to that point, and continue until the laser misses all the mirrors. Very fun project. Thanks for asking this question! **Readable code** ``` // a = input array // M = Math, Mc = M.cos, Ms = M.sin, P=M.PI, T=2*P, t=true // l = laser segment // m = array of mirror segments // i = loop variable // S = segment class (this.a=x1,b=y1,c=x2,d=y2,e=len,f=theta) // D = distance function // I = intersect function // f = last mirror bounced from // h = hits a mirror // n = next intersecing mirror // d = distance to mirror // x = intersection point x // y = intersection point y // r = mirror intersection result (d,x,y) // b = number of bounces (FOR DEBUGGING) // A,B,C,E,F,G,H,J,K,L,O temp variables // s = laser segment array // get input array var a = prompt().split(" ").map(Number); // some constants var M = Math, Mc = M.cos, Ms = M.sin, P = M.PI, T = 2 * P, t = true; // laser segment var l = new S(a[0], a[1], a[0] + a[3] * Mc(a[2]), a[1] + a[3] * Ms(a[2])), s = []; // mirror segments var m = []; for (var i = 4; i < a.length;) m.push(new S(a[i++], a[i++], a[i++], a[i++])); // bounce until miss var f = -1, b = 0; for (; ;) { // best mirror found var h = !t, d, x, y, n, r = {}; // loop through mirrors, skipping last one bounced from for (var i = 0; i < m.length; i++) if (i != f) if (I(l, m[i], r)) if (!h || r.d < d) { h = t; d = r.d; x = r.x; y = r.y; n = i } // a mirror is hit if (h) { // add to draw list, inc bounces s.push(new S(l.a, l.b, x, y)); b++; // move and shorten mirror l.a = x; l.b = y; l.e -= d; // calculate next angle l.f = 2 * (m[f = n].f + P / 2) - (l.f + P); // laser end point l.c = l.a + l.e * Mc(l.f); l.d = l.b + l.e * Ms(l.f); } else { // add to draw list, break s.push(new S(l.a, l.b, l.c, l.d)); break; } } // done, print result alert("X = " + l.c.toFixed(6) + ", Y = " + l.d.toFixed(6) + ", bounces = " + b); PlotResult(); // segment class function S(a, b, c, d) { this.a = a; this.b = b; this.c = c; this.d = d; this.e = D(a, b, c, d); this.f = M.atan2(d - b, c - a) } // distance function function D(a, b, c, d) { return M.sqrt((a - c) * (a - c) + (b - d) * (b - d)) } // intersect function function I(l, m, r) { // some values var A = l.a - l.c, B = l.b - l.d, C = m.a - m.c, L = m.b - m.d, E = l.a * l.d - l.b * l.c, F = m.a * m.d - m.b * m.c, G = A * L - B * C; // test if parallel if (!G) return !t; // intersection r.x = (E * C - A * F) / G; r.y = (E * L - B * F) / G; // distances var H = r.d = D(l.a, l.b, r.x, r.y), O = D(l.c, l.d, r.x, r.y), J = D(m.a, m.b, r.x, r.y), K = D(m.c, m.d, r.x, r.y); // return true if intersection is with both segments return (H < l.e) && (O < l.e) && (J < m.e) && (K < m.e); } ``` [Answer] # Python - 765 Good challenge. This is my solution which gets input from stdin and outputs to stdout. Using @Martin Büttner's example: ``` python mirrors.py 1 1 70.00024158332184 95 4.8 5.3 6.2 4.3 1.5 4.8 3.5 6 6.3 1.8 7.1 3 5 1 4 3 7 6 5 6.1 8.5 2.965 8.4 2 8.5 3.035 8.6 4 8.4 2 10.5 3 8.6 4 10.5 3 7.7094468894 3.84896396639 ``` Here is the golfed code: ``` import sys;from cmath import* l=[float(d) for d in sys.argv[1:]];c=180/pi;p=phase;q=exp;u=len;v=range def o(l): L=l[0]+1j*l[1];t=l[2]/c;D=l[3];S=[L,L+D*q(1j*t)];N=[[l[i]+1j*l[i+1],l[i+2]+1j*l[i+3]] for i in v(4,u(l),4)];a=[];b=[] for M in N: z=S[1].real-S[0].real;y=M[0].real-M[1].real;x=S[1].imag-S[0].imag;w=M[0].imag-M[1].imag;d=M[0].real-S[0].real;f=M[0].imag-S[0].imag;g=z*w-x*y;h=w/g;j=-y/g;m=-x/g;n=z/g;a.append(h*d+j*f);b.append(m*d+n*f) i=1;e=-1 for k in v(u(N)): if 1>b[k]>0: if i>a[k]>1e-14: i=a[k];e=k if e>-1: L=S[0]+i*(S[1]-S[0]);M=N[e];l[0]=L.real;l[1]=L.imag;l[2]=c*(p(M[1]-M[0])+p(q(1j*p(M[1]-M[0]))*q(1j*-t)));l[3]=D*(1-i) return l J=S[0]+i*(S[1]-S[0]) print J.real, J.imag return J.real, J.imag while u(l)>2: l=o(l) ``` And here is the ungolfed code with a bonus figure ![mirrors](https://i.stack.imgur.com/47blB.png) ``` import sys from cmath import* import matplotlib import matplotlib.pyplot as plt l=[float(d) for d in sys.argv[1:]] def nextpos(l): L=l[0]+1j*l[1] t=l[2]/180*pi D=l[3] S=[L,L + D * exp(1j * t)] MM=[[l[i]+1j*l[i+1],l[i+2]+1j*l[i+3]] for i in range(4,len(l), 4)] a=[] b=[] for M in MM: #determine intersections a11 = S[1].real-S[0].real a12 = M[0].real-M[1].real a21 = S[1].imag-S[0].imag a22 = M[0].imag-M[1].imag b1 = M[0].real-S[0].real b2 = M[0].imag-S[0].imag deta = a11*a22-a21*a12 ai11 = a22/deta ai12 = -a12/deta ai21 = -a21/deta ai22 = a11/deta a.append(ai11*b1+ai12*b2) b.append(ai21*b1+ai22*b2) #determine best intersection mina = 1 bestk = -1 for k in range(len(MM)): if 1>b[k]>0: if mina>a[k]>1e-14: mina=a[k] bestk=k if bestk>-1: #determine new input set L=S[0]+mina*(S[1]-S[0]) M=MM[bestk] l[0]=L.real l[1]=L.imag angr=phase(exp(1j*phase(M[1]-M[0]))*exp(1j *-t)) l[2]=180/pi*(phase(M[1]-M[0])+angr) l[3]=D*(1-mina) return l J= S[0]+mina*(S[1]-S[0]) print J.real, J.imag return J.real, J.imag #plotting xL = [l[0]] yL = [l[1]] fig = plt.figure() ax = fig.add_subplot(111,aspect='equal') for i in range(4,len(l), 4): plt.plot([l[i],l[i+2]],[l[i+1],l[i+3]], color='b') while len(l)>2: #loop until out of lasers reach l = nextpos(l) xL.append(l[0]) yL.append(l[1]) plt.plot(xL,yL, color='r') plt.show() ``` [Answer] # Matlab (388) ## Plot ![plot](https://i.stack.imgur.com/uxlju.png) ![plot2](https://i.stack.imgur.com/tFN5e.png) ## Concepts ### Reflection Points For calculating the reflection points we basically have to interesect two straight lines. One with the point p0 and vector v, the other between the two points p1,p2. So the equation to solve is (s,t are parameters): p0+t*v = s*p1+(1-s)\*p2. The parameter s is then a barycentric coordinate of the mirror so if 0 ### Mirroring The mirroring of v is pretty simple. Let us assume that ||v|| = ||n|| = 1 where n is the normal vector of the current mirror. Then you can just use the formula v := v-2\*\*n where <,> is the dot product. ### Validity of step While computing the nearest 'valid' mirror we have to consider some criterias that make it valid. First the interception point of the mirror must lie between the two endpoints, so it must be 0 ## Program ``` p = [1 1 430 17 4.8 5.3 6.2 4.3 1.5 4.8 3.5 6 6.3 1.8 7.1 3]; hold on grid on for i=2:length(p)/4 i = i*4+1-4 p2=p(i+2:i+3)'; p1=p(i:i+1)' plot([p1(1),p2(1)],[p1(2),p2(2)],'r-') text(p1(1),p1(2),['m' num2str((i+3)/4-1)]) end %hold off history = p(1:2)'; currentPosition = p(1:2)';%current currentDirection=[cos(p(3)*pi/180);sin(p(3)*pi/180)]; while p(4)>0%as long as we do not have finished our distance distanceBuffer = Inf%distance next point buffer intersectionBuffer = NaN %next point buffer for i=2:length(p)/4%number of mirrors i = i*4+1-4 %i is now the index of the firs coordinate of the mirror %calculate all crosspoints p2=p(i+2:i+3)'; mirrorVector = p2-p(i:i+1)'; % idea: p0+s*currentDirection = s*p1+(1-s)*p2 solving for s,t r=[currentDirection,mirrorVector]\[p2-currentPosition]; if r(1)<distanceBuffer && 0.001< r(1) && r(1)<p(4) &&0<=r(2) && r(2)<=1 %search for the nearest intersection distanceBuffer=r(1); intersectionBuffer=r(1)*currentDirection+currentPosition; mirrorBuffer = mirrorVector end end if distanceBuffer == Inf %no reachable mirror found endpoint = currentPosition+p(4)*currentDirection; counter = counter+1 history = [history,endpoint]; break else %mirroring takes place counter = counter+1 history = [history,intersectionBuffer]; currentPosition=intersectionBuffer; normal = [0,-1;1,0]*mirrorBuffer;%normal vector of mirror normal = normal/norm(normal) disp('arccos') currentDirection = currentDirection-2*(currentDirection'*normal)*normal; %v = v/norm(v) p(4)=p(4)-distanceBuffer end end history plot(history(1,:),history(2,:)) ``` ## Slightly golfed (388) ``` p=[1 1 430 17 4.8 5.3 6.2 4.3 1.5 4.8 3.5 6 6.3 1.8 7.1 3]; c=p(1:2)' b=pi/180 v=[cos(p(3)*b);sin(p(3)*b)] f=p(4) while f>0 q=Inf for i=2:length(p)/4 b=p(i+2:i+3)' u=b-p(i:i+1)' r=[v,u]\[b-c] s=r(1) t=r(2) if s<q&&0.001<s&&s<f&&0<=t&&t<=1 q=s n=s*v+c m=u end end if q==Inf disp(c+f*v) break else c=n g=[0,-1;1,0]*m g=g/norm(g) v=v-2*(v'*g)*g f=f-q end end ``` ]
[Question] [ This sentence employs two a’s, two c’s, two d’s, twenty-eight e’s, five f’s, three g’s, eight h’s, eleven i’s, three l’s, two m’s, thirteen n’s, nine o’s, two p’s, five r’s, twenty-five s’s, twenty-three t’s, six v’s, ten w’s, two x’s, five y’s, and one z. Such sentences are called [autograms](http://en.wikipedia.org/wiki/Autogram). Your task is to write a program or function that has a similar property: it takes as input a byte, and outputs an integer representing the number of times that byte appears in the program's source code. It should output 0 if its input doesn't appear in its source. **Your program must not read its own source code**, directly or indirectly, but instead all the data it needs to give its output must be hard-coded, quine style. Your program must be at least one byte in length. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest entry (in bytes) wins. I won't accept an answer, so feel free to compete for the shortest solution in your favourite language. You are strongly encouraged to include an explanation in your post. ## Leaderboards Below are leaderboards both for overall score and per language: ``` var QUESTION_ID=162408,OVERRIDE_USER=21034;function answersUrl(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 commentUrl(e,s){return"https://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] # [Octave](https://www.gnu.org/software/octave/), 44 bytes ``` @(x)sum([[39,'(())*,239==@[[]]msuxx']]==x)*2 ``` [Try it online!](https://tio.run/##dYxBCoMwEEX3PUU2ZWZkEKorKQPeI80iiBYXRhtNSXv5VCktddHl@7z3x2ax9zZ1kud5qjHSHAbUuqwYEIkyLspKpNbamGEOMYIxIpGyIk1@vCpRsI82fPPqlNXWiazzJ4PzYfK9WzrUvp0GuyAcG6WAT@zcE4Prb6HF7ZuIGC4O@Ov1/zzD@ndgZb23jy447HhnGkov "Octave – Try It Online") The result of the function, when using each of the characters in the function as input: ``` ' ( ) * , 2 3 9 = @ [ ] m s u x 2 4 4 2 2 2 2 2 4 2 4 4 2 2 2 4 ``` All other input characters returns a zero. The fact that I had to escape `'` made this a whole lot longer. In order to account for the 4 parentheses, I just had a duplicate in the string. However, duplicating apostrophes takes apostrophes, so this just takes us further from the correct result. Therefore, I had to count the number of apostrophes with its ASCII-value, `39`. This of course meant I had to check for the characters `3` and `9` too, making it all a lot longer. [Answer] # Excel, 84 bytes ``` =IFERROR(MID("65496331125442343343233",FIND(A1,"""123456789,()=MINORFADEOMEN"),1),0) ``` `Find()` will look for the value in cell `A1` within the string `"123456789,()=MINORFADEOMEN` (the `"""` at the beginning is to escape the character and will evaluate to just `"`). Based on the result of `Find()`, the `Mid()` function will return the corresponding character from the string of numbers. This string was created through iteration until it stopped changing. If the character in `A1` is not found, `Find()` returns an error so the `IfError()` function escapes that to return `0` instead. The `OMEN` at the end of the string being searched in the `Find()` function are duplicate letters so their position will never be returned but they were needed to adjust the character counts. Without them, there was an endless loop of changing counts. The letter arrangement is stylistic choice. [Answer] # JavaScript (ES6), 70 bytes Doesn't read the source of the function, but this is quite long. Takes input as a 1-character string. ``` i=>~(n='\\34=\'in(|)0257?:.>[]Odefx~'.indexOf(i))?'3733544333'[n]||2:0 ``` [Try it online!](https://tio.run/##VY9Pa8JAFMTvforXHtxdEpc0m1SIjVKEQqHgwd6Mh/zZTTamu5KsRWj0q6cbvbS3NzPwmzd1@p12eSuPZqZ0wQcRDzJeXrGKUZKwIE6QVLgnnh/OVxFd7vabgovzFVGpCn7eCCwJWSE2ZywMAsYY2ql93/uRNwjd4gxi8BaQwQv44bM9HIfAzwQgt8HWtFKVVLT6a12l7drW44wsbIprGwucEwLTKeRadbrhtNElRp8Vh06f2pyPvkml6pALtQvoEYFjuc54kYmlSGE5DzHgw0ijRt8LMaHdsZHG4mnDVWkqmMETuf8F/9veXt8/tmCXwB96BKU2MOp61C50lT41BWT8Zh5uEy6Ty/AL "JavaScript (Node.js) – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 1 byte This wouldn't be valid if following strictly the quine rules, but the OP explicitely allowed it [in a comment](https://codegolf.stackexchange.com/questions/162408/autogram-programs#comment393488_162408). ``` x ``` [Try it online!](https://tio.run/##K0otycxLNPz/vwKIAA "Retina – Try It Online") In retina a single-line program counts the occurrences of that regex in the input. This challenge is solved by any single ASCII character except ```, `.`, `+`, `*`, `?`, `[`, `(`, `)`, `^`, `$`, `\` and newline. [Answer] # [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~88~~ 57 bytes ``` x=>"\\\"(())==>>??..::3300CCaaiinoossttx".Contains(x)?3:0 ``` [Try it online!](https://tio.run/##LY69asMwFIVn6ymE6CBBKwzenEoeDJlSKHToUHcQquwIEgl0b4uL8bPfqiSc8fx8x8OTB0@M@YsD4K8lL8VdWbOxpgF0GD3/yfGLv7iYJGCJafn45K4soGpiY2@/gOGqj9/JP9/sRx4TWj5zQ6uxYpomIaVSxlg7DFr3fde17Tg6F2PKGQBxFXrMCSsB5KqGrm/pwNicS3D@fIdyqLM3br12p9YW5EvQ7yViOMUU5IPYYO/5NktQu1AHtv@LSJAkRY4MWRr@AA "C# (Visual C# Compiler) – Try It Online") Returns **3** if the string contains the passed char, otherwise returns 0. The string contains each character of the code atleast once and exactly the amount required to have the char **3** times in the code. -31 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) [Answer] # [Haskell](https://www.haskell.org/), 66 bytes The first two versions are essentially a quine which filters the required characters and then takes the length: ``` q c=length.filter(==c)$id<>show$"q c=length.filter(==c)$id<>show$" ``` [Try it online](https://tio.run/##hcoxDsMgDADAr1hVBlh4QcySrn2EFdxghZgAlvp82h90uO0yjZNLmXLdtRs8ySi8qlZJ4NwavZ8Ndiysh@XwlmLcHeLuF0lrHLl@lsffMC8SBYSDbatqrDYgRoS7ixoEaD@ZKc32BQ "Haskell – Try It Online") or [test with all characters!](https://tio.run/##jU67DoIwFN35ipOGBIhCdDXURUeddAOHplRpLC2PEhb/HQsOGhc9y725555Hybq7UGqUVW1aiz2zLDkabWSBMEy3UTQ24FQJfbNlcpXKijaklEe@LNJtV5rBJz8fRq9iUoOiMB5Q9/Zk24OGD7IzhdjkmmCxAHf7J03iN8iX7iw6u8EsmyIQMqVg3RFZkK@CJLlEnpMMpWjFbAy4@J9N8z8@piovzHnc@XZ9hQxrPMADpPEcuJx2Sh1/mYbzHZsn "Haskell – Try It Online")\* --- ### Alternative without `(<>)`, 72 bytes ``` q c=length.filter(==c)$(++)<*>show$"q c=length.filter(==c)$(++)<*>show$" ``` [Try it online](https://tio.run/##jcrBDYAgDADAVRrjQyRhAsvHSQhWIWIRaOL46Ag@7nfBtZNS6r2Ax0R8SDB7TEJ1QvRqnLRWy2xbyM84/Dn9cpEB4SBZMwuxNLAW4a6RBQyUTyC39fIC "Haskell – Try It Online") or [test with all characters!](https://tio.run/##jU49D4IwFNz5FZeGBLBCdDXUxdVNN2AgpVpiAaElLP53bHHQOHHLe3n37kOW@iGUmucenCnR3o1MbrUyYggZ45EfUhqlm6OW3eSTNT@z15R1C4aq84DnaC5mOLfwQU5dJQ55S0ApuN1/aRJ/Qf50V6HNAYvMRSAslYKxR2RBvguSpIg8K5mkGMRiDNj4NWXzdU@u0AdLKrfuemyQYY8XeIA0XmK3bmfM8oUb1nru3w "Haskell – Try It Online") --- ### Non-quine alternative, ~~87~~ 86 bytes Might still be improved, but I'm happy that I got it down to only three different groups. I like this one the best, even though it counts the most bytes. It's computes the character/byte count by as a sum of *2,3* and *7* (note how some characters are in multiple groups): ``` u t=sum[fst e|e<-[(2," ()-237<=dflnst|"),(3," ()[\\]`mstu"),(7,"\",ee")],t`elem`snd e] ``` [Try it online](https://tio.run/##Hci9DoMgEADgV7kwQYIddHARlz4GkEDCWU2BNt6x@e70Z/iWb4/0xJx7b8CGWrEbMeCFy2DlqAVINYzTvJi05Up8CaXl9G/rnA@FuP1q1sIJjSiU1xwwYwlUE6DvJR4VDDyQ76/KWJlgXQ28z6My3KB97RhTxw8 "Haskell – Try It Online") or [test with all characters!](https://tio.run/##bY9Ba4NAEIXv/orHUFDJGtrkEAh6yrW39uYsKDrB0FVDdiUX/7tdtaWl6Vx2eMPb976mtB9izDQNcJkd2vxsHWSUNMmjnSJEcbLbH9KsPpvOupFiFe0XOWfWRWvdMEsHRUxKhGKtXCFG2sJ2NURPQVteOmSo@wC4Du7N3V47PIFOfS1H7gibDSq//z5T8jP0x/cu1h2x2GzT3xGVxsB5EXnIz@F2q@PAW@6N3GT52IfTv3D8QMcrHn/xfRPyisjklZmSHzDnkussTSqf6eOQ4wUjqhBpslRR855l/q7nZ0A1fQI "Haskell – Try It Online") --- \* imports `(<>)` because TIO's GHC version is 8.0.2 [Answer] # [Python 2](https://docs.python.org/2/), ~~54~~ ~~52~~ 32 bytes -20 bytes thanks to ovs ``` ("''+.23cnotu()"*2+'"*'*3).count ``` [Try it online!](https://tio.run/##JYzLCoMwEEX3@YphNnloBeNOyJeULsqYUKHMiB0Fvz5VXJ7DuXc59CMcK8mUEyJWh9Y2XRyIRTfnMcTGYrBh8B3JxlrP6NmPj/5lSsr7@@uuqTdFViCYGX5ZbzUagGWdWYHa4sindOn75cT6Bw "Python 2 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~11 10~~ 8 bytes Thanks [Leo](https://codegolf.stackexchange.com/users/62393/leo?tab=profile) for -2 bytes! ``` #sD"#sD" ``` [Try it online!](https://tio.run/##yygtzv7/X7nYRQmE////r66kDgA "Husk – Try It Online") ### Explanation This makes sure that it only uses ASCII (because `show` would mess it up) and that each character is contained twice: ``` #sD"#sD" -- character as input, eg. '"' "#sD" -- string literal (note the redundant '"'): "#sD" D -- double: "#sD#sD" s -- show: "\"#sD#sD\"" # -- number of occurences: 2 ``` ## Standard quine extension, 11 bytes ``` #hS+s"#hS+s ``` [Try it online!](https://tio.run/##yygtzv7/XzkjWLtYCUz@//9fXUkdAA "Husk – Try It Online") ### Explanation ``` #hS+s"#hS+s -- character as input, eg. '"' "#hS+s -- string literal: "#hS+s" S+ -- join with itself: ("#hS+s"++) s -- | and itself shown: "\"#hS+s\"" -- : "#hS+s\"#hS+s\"" h -- init: "#hS+s\"#hS+s" # -- number of occurences in string: 1 ``` [Answer] # Java 10, ~~164~~ ~~81~~ 57 bytes ``` q->"q-->>\\\"..ccoonttaaiiss(())??33::00".contains(q)?3:0 ``` Port of [*@Hyarus*' C# answer](https://codegolf.stackexchange.com/a/162552/52210), so make sure to upvote him! **Explanation:** [Try it online.](https://tio.run/##lVCxbsJADN35CuuW3AnlFClbUJOpY1kYCYPrhHIQLiRnkBCiv546IVLVsdKdZD/b7/n5iDeMj9VpoAZDgA90/rEAcJ7rfo9Uw3pMJwBIb7h3/gvIrAR8ypcXGNkRrMHDGwxdnKsujvO8LEtlLVHbemZE50LQ2piiSNMsSxJlSQqiFnRnijRLhtVCyC7Xz0bIZs5b6yo4S9MsvN0Bmtc@uE12lg7YB21s5QI7Tyzhvu3fkQ6a4pzrwFqPPYbMtDHAhEUQ/Um/o9nPr5tJeaqO82L4pbq5B67Ptr2yvchC3HhNS5WVrJbe0hgrM3M9h/kW/77EDw) ``` q-> // Method with String parameter and integer return-type "q->\\\"..ccoonttaaiiss(())??33::00".contains(q)? // If the string above contains the input character 3 // Return 3 : // Else: 0 // Return 0 ``` --- **Old [quine](/questions/tagged/quine "show questions tagged 'quine'") 164-bytes answer:** ``` c->{var s="c->{var s=%c%s%1$c;return s.format(s,34,s).replaceAll(%1$c[^%1$c+c+']',%1$c%1$c).length();}";return s.format(s,34,s).replaceAll("[^"+c+']',"").length();} ``` **Explanation:** [Try it online.](https://tio.run/##jZHBasMwDIbvfQphFmKT1DC200IHe4D10mPWgqe6bTrHCbYSGCV79cxJM7rcCpbRJ8vyL/msWrU87796NMp7eFeFvSwACkvaHRRqWA84BgA5npQDFFkIdcHC8qSoQFiDhRX0uHy9tCHFr9jNjTDy0eMDZk5T4yx4eahcqYj79Ok59UI6XZvw1JsxfMjLd8OeYBJv43RwBxPSaHukExdZx@6pxPIdm2ow9v92ny2C7rr5NEH3JL@tij2UoXe@IVfYY74FJa6Nk/bEYx@PTf@hniPMkc0R59jN8Seexnkb5qhmPJ3mfVWy@fakS1k1JOsgkozlmLCXD2KJleFvxFSo638B) ``` c->{ // Method with char parameter and integer return-type var s="c->{var s=%c%s%1$c;return s.format(s,34,s).replaceAll(%1$c[^%1$c+c+']',%1$c%1$c).length();}"; // Unformatted source code return s.format(s,34,s) // Create the formatted source code (the quine), .replaceAll("[^"+c+']',"") // remove all characters not equal to the input, .length();} // and return the length ``` [quine](/questions/tagged/quine "show questions tagged 'quine'")-part: * The String `s` contains the unformatted source code. * `%s` is used to input this String into itself with the `s.format(...)`. * `%c`, `%1$c` and the `34` are used to format the double-quotes. * `s.format(s,34,s)` puts it all together Challenge part: * `.replaceAll("[^"+c+']',"")` removes all characters except those equal to the input. * `.length()` then takes the length of this String. --- NOTE: `.split(c).length` (with `String` input instead of `char`) may seem shorter, but has two problems: 1. The first character gives an incorrectly result, so if `c` (with `c->` as leading part) is input, it will incorrectly return one character too few. This can be fixed by adding `+(c==99?1:0)` in both the source code and unformatted source code String (and changing `.split(c)` to `.split(c+"")`, but then we still have the following problem: 2. If a regex character (i.e. `$`) is input, the `.split` will interpret it as a regex, giving an incorrect result. [Answer] # [Haskell](https://www.haskell.org/), 58 bytes ``` f c=sum[2|x<-succ '!':"f c=sum[2|x<-succ '!':,x==c]",x==c] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00h2ba4NDfaqKbCRre4NDlZQV1R3UoJu7BOha1tcqwShPqfm5iZp2CrkJ5a4pyRWKRgZ2erUFCUmVeioKeQ9r8YAA "Haskell – Try It Online") or [verify the solution](https://tio.run/##pY8xD4IwFIR3f8WTmBSSgoaERemko/8AGGop0FhaQh8JA/8dqzi6ecvLXb68y3XcPaXWq@oHOyLcOPLkrhyuDQjmpr5IlzmP3SQEkD05B79jOjMmqmA7a8@VAQa1hR14cchjaCVerUFp0H3CYVQG4QBmehShoMpR19lJ1xEsIPK4IOWJJAkp0ywjFQUtEZTzT33/BTbUOy1Ni13YKI1yDH15xCP6Bo/sC1V/DHkB "Haskell – Try It Online"). Same byte count alternatives: ``` f c=sum[2|x<-tail$show"f c=sum[2|x<-tail$show,x==c]",x==c] f c=sum[1|x<-id<>show$"f c=sum[1|x<-id<>show$,x==c]",x==c] ``` --- ### [Haskell](https://www.haskell.org/), 90 bytes ``` sum.($zip"1234\"$,.[\\]opu+()iklmsz652"$[4,4,11,3,3,3,16,5,3,3,3,3,3,3,3]++[2,2..]).lookup ``` [Try it online!](https://tio.run/##LcYxCsMgFADQq4gISfBX0JhsmXqBjAV1kFJbiUapdcnha6GEt7yXLdsjhObQolupkfXk8BlzMUqNCTCltUm50n7wW4jlmCeBiZIggXMY//gM09mToVQJEIyZgYWUtppbtH5HC8pvv38QQQ510LXv3QX7LO1yu67rDw "Haskell – Try It Online") or [verify the solution](https://tio.run/##tY8xb4MwEIX3/IoTQgIL4xYHsiRMydghYyWbwXEcsDA2wmaJ@ttLacpf6HvLvdOnO71O@F4Zs@hhdFOAiwiCfGgfdhZqvvh5IGn81GNU0H3JoxgTxnnjxjlLke7N4J@HikYxK3GJiwLvXy4OuNrGzU2WMYopIQ0ixrl@HpdB6PUF3B3sYJWAUw6tCmdng7LBv5bjpG2AGOx8Y6nE2mPfudncEXyBPOUs4e8JIQmnVZU0GIwKoP161II8wh@6JqNsG7r0oU1QU1rXEgmEf8G3eoOafyz6LR9GtH7JP8/X6w8 "Haskell – Try It Online"). Uses the fact that `sum Nothing = 0` and e.g. `sum (Just 4) = 4`. [Answer] # [Smalltalk](https://en.wikipedia.org/wiki/Smalltalk), 112 ~~132~~ bytes Smalltalk isn't exactly known for its golfing suitability :-) Method defined in class Character (tested in VA Smalltalk and Squeak, should work in other dialects such as VisualWorks and Pharo as well): ``` a^(0to:6),#(10 18)at:(#('' ',[]^|+68cForu' '#0adefln' '1it' '()' ':s' ' ' '''')findFirst:[:s|s includes:self])+1 ``` Characters occurring in the source are grouped by occurrence count. The groups are tested for the first one which contains the receiver, and the matching occurrence count is returned. ### Old method: ``` a^('''''((((())))):::[[[[]]]]^^^^^0000066666aaaacccccdddddeefffFFFFFiiilllnnnnnrrrrrsssTTTTTuuuu'includes:self)ifTrue:[6]ifFalse:[0] ``` Every character that does appear in the method appears exactly 6 times (by being repeated in the string constant), so the method just checks whether the receiver is contained in the string and returns 6 if it is, 0 otherwise. After defining the method as above, you can validate it using ``` | code | code := Character sourceCodeAt: #a. ((0 to: 255) collect: [:b | b asCharacter]) reject: [:c | c a = (code occurrencesOf: c)] ``` The result should be empty. [Answer] # JavaScript, 31 bytes ``` f=c=>~-`f=${f}`.split(c).length ``` [Try it online](https://tio.run/##LcuxDsIgEADQXyGNw5GmN7vQn3BUkyMUKg3eESGVxNhfx8W3v83utrhXzHViWXzvwTgzHxMFc/qEL2HJKVZwGpPntT66Ey6SPCZZ4YqI7N/q4iv8w5n0HZ82QzNzGwdl1DAGaFrjJpHpxqT7Dw) [Answer] # [Python 2](https://docs.python.org/2/), 57 bytes ``` lambda c,s='lambda c,s=%r:(s%%s).count(c)':(s%s).count(c) ``` [Try it online!](https://tio.run/##TYxBCsMgFAX3PcVr4PMVbBZdCvYk3Zgv0kCiQQ00vbxtd9nNzGK2o71yuvfonn3x6xQ8xFTHJ6ZiVSWqepS8p6ZE8z@cvMdcIJgTBhArbUbr/CRhWVMute3X9/EZ7AXYypwamApuD1BgUmIQfwfdvw "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes ``` 2"D34çýs¢"D34çýs¢ ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fSMnF2OTw8sN7iw8tQmL@/394LwA "05AB1E – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 96 bytes ``` n"n"=15;n"="=14;n" "=2;n";"=13;n"\\"=3;n"\""=25;n"0"=2;n"1"=4;n"2"=4;n"3"=4;n"4"=5;n"5"=5;n n3=0 ``` [Try it online!](https://tio.run/##bY3LDoIwEEX3fgWZuIBEI8@NOF/CZdEFCrFODNKd/16HVuLGpJlzO73pGc3rPljrvZAQF02rU1krE@JS0eq1UgLEgaT7tZfH94J4bZcRVURNvFaagEQqzr1hEqwnWBSIHlCC8BOoRXRBZfj6QiZEJyjfugWCCVRuodpCjaAFNfj5afcwk/BznmTZd6k72EFuy5heJ7sMc8rsMpNlb3c5moOk7tz12Yn/dXr/AQ "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), 109 bytes ``` n 'n'=15;n '='=14;n ' '=14;n ';'=13;n '\\'=3;n '\''=25;n '0'=2;n '1'=5;n '2'=4;n '3'=4;n '4'=5;n '5'=5;n n3=0 ``` [Try it online!](https://tio.run/##nY3LCsIwEEX3fkUowqRQsU3aVZ0vsS6yiDYYB6nJzn@PeVTcCIKre@bODGdWj6u2NgRiQIDdMEbACH0C9oYxgkwwTYAFAFDk6zZCyg4wzwIw/8g1@7UfSpLENiisfgtFEX6UySnFn85qc1OG8L4Yctsj943VdHEzPxvr9MIRfa3q@ukPO9UQ83v8tj@FFw "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), 122 bytes ``` n 'n'=21 n '='=14 n ' '=14 n '\n'=12 n '\\'=4 n '\''=32 n '0'=2 n '1'=5 n '2'=5 n '3'=3 n '4'=5 n '5'=5 n nnnnnn4'''''''=0 ``` [Try it online!](https://tio.run/##bY7BDsIgDIbvPgVZTLolMw623eyTiAcO0y1iY@a4@e4IBTwYe/k/Wpp@s3ndJ2u9JwEEqOQuAALKIYIooMNMKiYNmFoA2HOrC3sxJeAYU@Xsw4eYQ36PKYlrgFTYeYNVua6pnGcSX9LJIDNLZGYN5ujBEEUYVIGowjCUzpjh16baPcxC@FwX2vbn2rV2ots219fFbtNaI7rGNM3bnQ6mJeGO@G9@8R8 "Haskell – Try It Online") # Explanations These answers are not terribly sophisticated. It is a series of declarations, one for each character present in the program. At the end we have a catch all that returns 0 for characters not present in the program. I use a couple of tricks to minimize the number of characters necessary in the program and from there I fiddled with things until the numbers turned out just right. You can see that I've padded the variable name in the last declaration, in all 3 of them. The difference between the 3 programs is whether I chose to use a new line or `;` for line breaks and whether I chose to take Chars as input or Strings. The `;` approach doesn't seem inherently superior to the others it just gets luck and ends up shorter, however it does seem that using Strings is a better idea than Chars because Chars require spaces after the function name an Strings do not. [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 140 bytes ``` [S S S N _Push_0][S N S _Duplicate][S N S _Duplicate][T N T S _Read_STDIN_as_character][T T T _Retrieve][S S S T S S T N _Push_9][T S S T _Subtract][S N S _Duplicate][N T S S T N _If_0_Jump_to_Label_TAB][S S S T N _Push_1][T S S T _Subtract][S N S _Duplicate][N T S S N _If_0_Jump_to_Label_NEWLINE][S S S T S T T S N _Push_22][T S S T _Subtract][N T S T N _If_0_Jump_to_Label_SPACE][N S T N _Jump_to_Label_PRINT][N S S S T N _Create_Label_TAB][S S S T S S T S T N _Push_37][N S T N _Jump_to_Label_PRINT][N S S S N _Create_Label_NEWLINE][S S S T S S S S T N _Push_33][N S T N _Jump_to_Label_PRINT][N S S T N _Create_Label_SPACE][S S S T S S S T T S N _Push_70][N S S N _Create_Label_PRINT][T N S T _Print_as_integer] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. 70 spaces, 37 tabs, and 33 new-lines used. Usually I use the Create Labels in the order `NSSN`, `NSSSN`, `NSSTN`, `NSSSSN`, `NSSSTN`, `NSSTSN`, `NSSTTN`, etc. But because printing a number where the binary `S=0`/`T=1` is used affects the number I need to output, I used the labels `NSSN`, `NSSSN`, `NSSTN`, and `NSSSTN` instead, which gave the perfect amount of spaces/tabs to be printed with the binary numbers `SSSTSSSSTN` (33; amount of new-lines), `SSSTSSTSTN` (37; amount of tabs), and `SSSTSSSTTSN` (70; amount of spaces). ### Explanation in pseudo-code: ``` Character c = STDIN-input as character If c is a tab: Print 37 Else if c is a new-line: Print 33 Else if c is a space: Print 70 Else Print 0 ``` ### Example runs: **Input: space** ``` Command Explanation Stack Heap STDIN STDOUT STDERR SSSN Push 0 [0] SNS Duplicate top (0) [0,0] SNS Duplicate top (0) [0,0,0] TNTS Read STDIN as character [0,0] {0:32} \n TTT Retrieve [0,32] {0:32} SSSTSSTN Push 9 [0,32,9] {0:32} TSST Subtract top two (32-9) [0,23] {0:32} SNS Duplicate top (23) [0,23,23] {0:32} NTSSTN If 0: Jump to Label_TAB [0,23] {0:32} SSSTN Push 1 [0,23,1] {0:32} TSST Subtract top two (23-1) [0,22] {0:32} SNS Duplicate top (22) [0,22,22] {0:32} NTSSN If 0: Jump to Label_NEWLINE [0,22] {0:32} SSSTSTTSN Push 22 [0,22,22] {0:32} TSST Subtract top two (22-22) [0,0] {0:32} NTSTN If 0: Jump to Label_SPACE [0] {0:32} NSSTN Create Label_SPACE [0] {0:32} SSSTSSSTTSN Push 70 [0,70] {0:32} NSTN Jump to Label_PRINT [0,70] {0:32} NSSN Create Label_PRINT [0,70] {0:32} TNST Print as integer [0] {0:32} 70 error ``` Program stops with an error: No exit defined. [Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0FBgQsIgYiTi1OBk5MTKADEIA6QBkqBOQpoImABoGqoNJDJxQXGMMVgabgYVEgBIQRTBTYDZD1QgBPoGgA) (with raw spaces, tabs, and new-lines only). **Input: tab** STDIN will be `\t` (`9`) instead, in which case it will be `0` at the first `If 0` check, goes to `LABEL_TAB`/`NSSSTN`, and will push and print `37` instead. [Try it online](https://tio.run/##XY1dCsAwCIOf4ylytVEK29tggx7fpaE/MFTUL0Hbeb31uY9SM0mGQokAAQio@qIuyQt/xEDuIWuMcE2z5cUG4kbT5Rv9vQAy8QE) (with raw spaces, tabs, and new-lines only). **Input: new-line** STDIN will be `\n` (`10`) instead, in which case it will be `0` at the second `If 0` check, goes to `Label_NEWLINE`/`NSSSN`, and will push and print `33` instead. [Try it online](https://tio.run/##XY1RCoAwDEO/k1PkaiID/RMUPH7NwqYgbWn7Etp72692HsvaqiTR4QQhAAauvrhbyqIfCbB7yB7J1DRHftlA@tB05UZ/b4AqPg) (with raw spaces, tabs, and new-lines only). **Input: anything else** Any other input-character will do `NSTN` (Jump to Label\_PRINT) after the third `If 0` check, printing the `0` that was still on the stack (which we've duplicated at the very beginning). [Try it online](https://tio.run/##XY1RCsAwCEO/4ylytVEK69@ggx3fpaHtYKioL0Gfs921X0epmSRDoUSAAARUY1GX5IU/YiD3lDVGuJbZ8mYT8UPL5RvjvQAyyws) (with raw spaces, tabs, and new-lines only). [Answer] # [Japt](https://github.com/ETHproductions/japt), 27 bytes ``` \Ua"" a a a " ÄU\\\"a "aU Ä " ÄU\\\"a " // Given this string literal, aU // find the last index of the input Ä // and add +1. \Ua"" a a a // Do nothing useful, but make the results match. ``` Longer than the existing Japt answer, but uses a different approach. Has the inherent limitation that all chars need to occur a unique number of times. Takes input as a string. [Try it online!](https://tio.run/##y0osKPn/PyY0UUlJIREMlRQOt4TGxMQoAZmJoUDO///qieoA "Japt – Try It Online") [Answer] ## Perl, 130 bytes ``` +print+0+((0)x40,6,6,0,3,43,0,0,0,22,12,6,3,5,2,4,0,1,0,0,0,1,0,1,(0)x28,1,0,1,(0)x6,1,(0)x4,1,(0)x4,1,1,1,0,2,0,1,0,0,0,5)[ord<>] ``` Has no newline or other whitespace. Reads a line from the standard output, but only cares about its first bytes, then prints the number of times that byte occurs in its own source code in decimal, without a newline. The program is straightforward. Most of the source code is occupied by a literal table that gives the answer for the each possible byte. Trailing zeros are omitted, and adjacent zeros are run-time compressed, but there's no special trick other than that. The rest of the program simply reads the input and looks up the answer in the table. For example, the part `22, 12, 6, 3, 5, 2, 4, 0, 1, 0` in the source code gives the frequency of digits, so there are 22 zeroes, 12 ones, 6 twos etc in the source code. As a result, if you enter `0` to the standard input of the program, the program will print `22`. [Answer] # [C (gcc)](https://gcc.gnu.org/), 1033 bytes ``` #include <stdio.h> int main(int argc,char *argv[]){int r=0*14811;switch((int)argv[1][0]){case' ':r=6;break;case'"':r=3;break;case'#':r=2;break;case'%':r=2;break;case'\'':r=101;break;case'(':r=5;break;case')':r=5;break;case'*':r=5*1*1;break;case'.':r=2;break;case':':r=51;break;case';':r=103;break;case'<':r=2;break;case'=':r=52;break;case'>':r=2;break;case'[':r=4;break;case'\\':r=3;break;case']':r=4;break;case'0':r=11;break;case'1':r=20;break;case'2':r=20;break;case'3':r=9;break;case'4':r=7;break;case'5':r=12;break;case'6':r=3;break;case'7':r=2;break;case'8':r=5;break;case'9':r=2;break;case'a':r=106;break;case'b':r=51;break;case'c':r=55;break;case'd':r=4;break;case'e':r=102;break;case'f':r=2;break;case'g':r=4;break;case'h':r=4;break;case'i':r=10;break;case'k':r=51;break;case'l':r=2;break;case'm':r=2;break;case'n':r=8;break;case'o':r=2;break;case'p':r=2;break;case'r':r=108;break;case's':r=53;break;case't':r=8;break;case'u':r=2;break;case'v':r=3;break;case'w':r=2;break;case'{':r=3;break;case'}':r=3;break;}printf("%d",r);} ``` [Try it online!](https://tio.run/##ZZPNroIwFIT39ykIxvATNRRRUcQXQRa1IDQqmoK6MDw7l5ZNm9k1X@bMmU5TtqwYG4YZb9j9XZTWse0K/lzVpz/edNaD8saVByoqtmA1FZY/Hj9Z7v0kFmngkygmJGm/vGO1K8WeUpA8C0YVo23pWM5BpNvkIkp6SxSxJVnrZCZJqJM5kLMjEQmIDl3JNjrxgPiK@MQ3Jlew4KB0hiiZVhpZjzCYqkEDnUCUSRIZFzpDDzmIApXACEWUd6CjENFaor1OIkl2OtkocyPmFjLt4CoxVLwHDZ2aM979ggUzhQyvAjooJy/D/wobK5irgfDJSUc3DHUH7weQRpJYJ0/QvICIab8x16oARuUdmL/B6gMP9QXNDzS9TvqXGH/s1bXnhb0QXtIPwxD@Aw "C (gcc) – Try It Online") This is by NO means a golfed answer, but it was fun to try to accomplish this challenge in a language which I am not familiar with. It wasn't a particularly difficult challenge until it came time to find the occurrences of the digits, now THAT was a challenge. Had to do a little creative balancing :) [Answer] # [C (gcc)](https://gcc.gnu.org/), 192 bytes ``` F(J){J=J-70?J-40?J-41?J-74?J-'{'?J-'}'?J-39?J-48?J-49?J-50?J-51?J-52?J-53?J-54?J-55?J-56?J-57?J-47?J-61?J-63?J-45?J-58?J-59?0:1:23:23:23:1:2:3:3:4:4:14:14:10:10:15:6:4:2:2:25:1:1:1;}//84332211 ``` [Try it online!](https://tio.run/##PYzPCoJAGMTvPsUSRBpJ7j81Jbp18BXKg2xmHrLYrIv47Ns3JjkfP4aZWU3YGOPc0S@CodgXYRIdilBN4IREEVbDChxBuUOVAnAaS42lFoAE8EZrIAYSjIEYuxgTNbX4i94dooxnQs5HNpMkReK/i6bTWUyRgDStSPm43aZKSiE4d23Xs3vVdj5MZRuzYeZWWbYm/zmVARs8Rt/csj2r@kfrTyUvg/xf2vpF5RHNnD4t5Vd/sbycu8WG@jm3df@2HYtyb3ROpV8 "C (gcc) – Try It Online") Probably possible to golf down further. Uses a comment at the end as a 'scratch space' to add extra digits. When I have to change a digit from X to Y, I change one of the Y's in the scratch to an X to compensate. Other than that this is just a function that takes an integer, using the assignment trick to return a value based on a large ternary conditional. [Answer] # x86 .COM, 17 bytes, controversial ``` 0120 BF2001 MOV DI,0120 (120 be the current address) 0123 B91100 MOV CX,0011 0126 AE SCASB 0127 7502 JNZ 012B 0129 FEC4 INC AH 012B E2F9 LOOP 0126 012D C1E808 SHR AX,8 0130 C3 RET ``` # 36 bytes ``` 0100 BF???? MOV DI,(an copy of this code) 0103 B91200 MOV CX,0012 0106 AE SCASB 0107 7503 JNZ 010C 0109 80C402 ADD AH,02 010C E2F8 LOOP 0106 010E C1E808 SHR AX,8 0111 C3 RET ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 30 bytes ``` ⊢⊢⊢11-11-11-'''''''1''⊢-⍳⍳0'⍳⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhEddiyDI0FAXgtQhwFBdHSiq@6h3MxAZqIPorkX/H/VNBWpKUwCp4IJzDJHYQFVIPF1kmd7NSDwDJHai@n8A "APL (Dyalog Classic) – Try It Online") ## Explanation In APL, single quotes within strings are escaped by doubling, so `'''''''1''⊢-⍳⍳0'` is the string `'''1'⊢-⍳⍳0`, which contain every character used in the program. APL arrays are by default 1-indexed, and the index-of function, interestingly, returns `1 + max index` if the element is not found. So, by using index-of on the string and the input returns ``` Input Index Count ' 1 10 1 4 7 ⊢ 6 5 - 7 4 ⍳ 8 3 0 10 1 <other> 11 0 ``` As one can see, `11 - index` gives the count of the character in the program. So, the basic algorithm is ``` 11-'''''''1''⊢-⍳⍳0'⍳⊢ ``` The rest is bloating the character counts to allow them to fit nicely into the slots. [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 bytes ``` Qi"QiUè² " ²èU ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=UWkiUWlV6LIgIiCy6FU=&input=J7In) --- ## Explanation ``` :Implicit input of character string U "QiUè² " :String literal Qi :Append a quotation mark ² :Repeat twice èU :Count the occurrences of U ``` [Answer] # [V](https://github.com/DJMcMayhem/V), 12 bytes ``` ñéÑ~"qpxøÖa ``` [Try it online!](https://tio.run/##K/v///DGwysPT6xTKiyoOLzj8DShxP9AsWkA "V – Try It Online") Hexdump: ``` 00000000: f1e9 d17e 2271 7078 f8d6 1261 ...~"qpx...a ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` “;⁾w⁸a2”;⁾“”w⁸a2 ``` [Try it online!](https://tio.run/##y0rNyan8//9RwxzrR437yh817kg0etQwF8QBigFZEKH/D3dvOdz@qGkNEB2d9HDnDCAdidDG5aCsogoA "Jelly – Try It Online") Every character appears exactly twice. ``` “;⁾w⁸a2”;⁾“”w⁸a2 “;⁾w⁸a2”;⁾“” the string ;⁾w⁸a2“” w⁸a2 return 2 if input in string ``` [Answer] # x86, ~~42~~ 40 bytes Here I use the same strategy as others: Create a string copy of the program with unique bytes, then return 2 in `al` if the input `al` is in the string. If we allow ourselves to read code that is actually run, we get [l4m2's solution](https://codegolf.stackexchange.com/a/162429/17360). I got to make use of a cool string instruction `scasb`. To the best of my knowledge, there are no duplicate bytes, but this is something I'd easily screw up. Loading the string address takes 5 bytes but I'm not aware of any shorter solution (64-bit `lea` of `rip` with offset takes 6 bytes). -2 by jumping backwards to avoid using `02` twice. ``` .section .text .globl main main: mov $0xff, %eax start: push $20 # program length pop %ecx # counter mov $str, %edi # load string loop: scasb # if (al == *(edi++)) jne loop1 mov $2, %al # ret 2 end: ret loop1: loop loop # do while (--counter) xor %eax, %eax # ret 0 jmp end str: .byte 0x6a,0x14,0x59,0xbf,0xf4,0x83,0x04,0x08 .byte 0xae,0x75,0x03,0xb0,0x02,0xc3,0xe2,0xf8 .byte 0x31,0xc0,0xeb,0xf9 ``` Hexdump (of binary file format elf32-i386, as obj file unfortunately has `00` bytes for `str` address): ``` 000003e0 6a 14 59 bf f4 83 04 08 ae 75 03 b0 02 c3 e2 f8 |j.Y......u......| 000003f0 31 c0 eb f9 6a 14 59 bf f4 83 04 08 ae 75 03 b0 |1...j.Y......u..| 00000400 02 c3 e2 f8 31 c0 eb f9 |....1...| ``` --- # x86, 256 bytes Boring answer that is the equivalent of a giant comment. Input in `cl`, immediately returns 1 in `al`. I'll make an actual answer when I have the free time. ``` 00000039 b0 01 c3 00 02 03 04 05 06 07 08 09 0a 0b 0c 0d |................| 00000049 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d |................| 00000059 1e 1f 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d |.. !"#$%&'()*+,-| 00000069 2e 2f 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d |./0123456789:;<=| 00000079 3e 3f 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d |>?@ABCDEFGHIJKLM| 00000089 4e 4f 50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d |NOPQRSTUVWXYZ[\]| 00000099 5e 5f 60 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d |^_`abcdefghijklm| 000000a9 6e 6f 70 71 72 73 74 75 76 77 78 79 7a 7b 7c 7d |nopqrstuvwxyz{|}| 000000b9 7e 7f 80 81 82 83 84 85 86 87 88 89 8a 8b 8c 8d |~...............| 000000c9 8e 8f 90 91 92 93 94 95 96 97 98 99 9a 9b 9c 9d |................| 000000d9 9e 9f a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 aa ab ac ad |................| 000000e9 ae af b1 b2 b3 b4 b5 b6 b7 b8 b9 ba bb bc bd be |................| 000000f9 bf c0 c1 c2 c4 c5 c6 c7 c8 c9 ca cb cc cd ce cf |................| 00000109 d0 d1 d2 d3 d4 d5 d6 d7 d8 d9 da db dc dd de df |................| 00000119 e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 ea eb ec ed ee ef |................| 00000129 f0 f1 f2 f3 f4 f5 f6 f7 f8 f9 fa fb fc fd fe ff |................| ``` [Answer] # [R](https://www.r-project.org/), 135 bytes Inspired by [this Python answer](https://codegolf.stackexchange.com/a/162451/80010). Previous versions were broken. Thanks to @Giuseppe for pointing out that `paste` was not required it saved 18 bytes or so. `lengths(regmatches(z,gregexpr(x,z)))`is from [this answer](https://stackoverflow.com/a/12427831/9670603). ``` function(x,z=rep(c("afilo2679=:","hmpu15'","nstxz","cgr","e","()",'"',","),c(2:5,7,9,15,16)))sum(lengths(regmatches(z,gregexpr(x,z)))) ``` [Try it online!](https://tio.run/##pZA/a8MwEMV3fYoiD7qDK8QBJ9jEY7ZMbUYvRkh2wH@EJIPqL@@ePXQrFDrc6Qm94/10frO3980uk46veYJEa@2NAw2yta9hPl@uZV1Jkv3olrxQrKYQ08qn7jx3wwUoSUlFLJE0nKuCrlRSXlB@QcSwjDCYqYt9AG@6sY26NwFW6vhmkvN7KvtQbJkFWUsUIku1@itU8zsVPzX/51JChNlHCK1zwxdjPO7P5/3jkwYTo/GBTlW5hxCzk6w4zCK@ZZT4Sz8zx4J20qaBo@PhO2zbNw "R – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 36 bytes ``` f=(x)->#[x|c<-Vec(Str("f=",f)),x==c] ``` [Try it online!](https://tio.run/##K0gsytRNL/j/P81Wo0JT1045uqIm2UY3LDVZI7ikSEMpzVZJJ01TU6fC1jY59n9iQUFOpUaygq6dQkFRZl4JkKkE4igppGkkA1UpBKeWaMD0ArVpav4HAA "Pari/GP – Try It Online") [Answer] # Ruby, 48 bytes ``` ->x{%q[->x{%q[].count(x.chr)*2}].count(x.chr)*2} ``` `%q[str]` is a more convenient way to write a string literal than `"str"` because it can be nested inside itself without any escaping. So I just put the entire code except for the copy inside it, then double the count. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 10 bytes ``` “;Ṿċƈ”;Ṿċƈ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rwxzrhzv3Hek@1vGoYS6M@f//sQ4A "Jelly – Try It Online") Reads a character from STDIN. **12 bytes** ``` Ḣ“Ḣċ;Ṿ¤”;Ṿ¤ċ ``` [Try it online!](https://tio.run/##y0rNyan8///hjkWPGuYAySPd1g937ju05FHDXAjjSPf////VgZLqAA "Jelly – Try It Online") Using input from command line argument. Also 12 bytes: ``` ẇ“Ṿẇ¤Ḥ”Ṿ¤Ḥ“” ``` [Try it online!](https://tio.run/##y0rNyan8///hrvZHDXMe7twHZBxa8nDHkkcNc4E8KHMOkPf//391IEcdAA "Jelly – Try It Online") ]
[Question] [ In traditional [Tetris](http://en.wikipedia.org/wiki/Tetris), there are 7 distinct [tetromino](http://en.wikipedia.org/wiki/Tetromino) bricks, each denoted by a letter similar to its shape. ``` # # # # # ## # # ### ## ## # ## ## ## # ## ## I O L J T Z S ``` Consider the arrangements of these bricks that can make a solid W×H rectangle, for some positive integers W and H. For example, using 2 I's, 1 L, 1 J, 2 T's, and 1 S, a 7×4 rectangle can be made: ``` IIIITTT LIIIITJ LTTTSSJ LLTSSJJ ``` The same bricks can be rearranged (by moving and rotating but **not flipping**) into a different 7×4 pattern: ``` IJJTLLI IJTTTLI IJSSTLI ISSTTTI ``` Now consider using a rectangular block of code in place of the first arrangement. For example this 7×4 bit of Python 3, which prints `Tetris` to stdout: ``` p=print x='Tet' y='ris' p(x+y)# ``` According to the first Tetris arrangement its 7 "bricks" are... ``` x ' int y ' ='r is p=pr t p( ='Te )# x +y ``` In the other arrangement (one of many possible) they are unintelligible as code: ``` r#)x(x= p'r'=y' ='istpT p+ytnie ``` But, given the bricks separately, it might be possible to piece them back together properly. This is the basis of the challenge. # Challenge This is a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge. There are two competing roles, the *Jumblers* and the *Rebuilders*. The Jumblers submit answers with blocks of code that have been broken down into Tetris bricks. The Rebuilders attempt to rebuild these blocks **in the separate question dedicated for them: [Jumblers vs Rebuilders: Coding with Tetris Bricks - Area for Rebuilder Answers](https://codegolf.stackexchange.com/questions/40187/jumblers-vs-rebuilders-coding-with-tetris-bricks-area-for-builder-answers).** ### Jumblers Using only [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) (hex codes 20 to 7E) write a W×H rectangular program. When run, it must output the **sole** word `Tetris` to stdout (or closest alternative). **Do not post this code in your answer; don't give W or H either.** Break it up into some arrangement of Tetris bricks like the example above and post these in your answer. (Your code may contain spaces but since they are hard to distinguish, it's best to use some other character in place of spaces and tell people what you used.) The harder it is to rebuild your program the better. There may be many ways to rearrange your code-bricks into a rectangle, possibly with different dimensions. What the code does when run in these different arrangements doesn't matter as long as at least one arrangement prints `Tetris` to stdout. The only other restriction is that W \* H be less than 1025. Jumblers should specify their programming language (and version). ### Rebuilders Your goal is to take a Jumbler's code-bricks and put them back into their original order, so `Tetris` is printed when the code is run. If the working arrangement you find isn't the one the Jumbler had in mind that's too bad for them. Remember that only translation and rotation are allowed in rearrangements, not mirroring. # Scoring Each time a submission is rebuilt it is considered "cracked" and is no longer in the running. The first Rebuilder to rebuild a submission gets the credit for it. If an answer goes uncracked for 72 hours the Jumbler should reveal the solution and will be henceforth immune from being cracked. A Jumbler must do this to win, since otherwise it will be unclear if there even was a solution. The winning Jumbler is the uncracked answer with the smallest area (W \* H = 4 \* num of bricks). In case of ties the highest voted answer wins. The accepted answer for this question will be the winning Jumbler. The winning Rebuilder is the user who cracks the most submissions. In case of ties it goes to whomever cracked the most cumulative area. # Notes * You may not rebuild your own submissions. (But otherwise you may take on both roles.) * Rebuilders may not attempt to crack the same answer more than once. # Scoreboard Sorted from oldest submission to newest. ``` +--------------+-------------+------------------+---------+----------+----------------+-------------------------------------------+-------------------------------------------+ | Jumbler | Language | Area | Immune? | Rebuilt? | Rebuilder | Link | Solution Link | +--------------+-------------+------------------+---------+----------+----------------+-------------------------------------------+-------------------------------------------+ | xnor | Python 3 | 212 | no | yes | foobar | https://codegolf.stackexchange.com/a/40142 | https://codegolf.stackexchange.com/a/40203 | | xnor | Python 3 | 340 | no | yes | feersum | https://codegolf.stackexchange.com/a/40146 | https://codegolf.stackexchange.com/a/40189 | | es1024 | C | 80 | no | yes | user23013 | https://codegolf.stackexchange.com/a/40155 | https://codegolf.stackexchange.com/a/40210 | | Ethiraric | Brainfuck | 108 | yes | | | https://codegolf.stackexchange.com/a/40156 | | | Qwertiy | JavaScript | 420 | yes | | | https://codegolf.stackexchange.com/a/40161 | | | user23013 | Befunge | 360 | yes | | | https://codegolf.stackexchange.com/a/40163 | | | user23013 | CJam | 80 | yes | | | https://codegolf.stackexchange.com/a/40171 | | | Geobits | Java | 360 | yes | | | https://codegolf.stackexchange.com/a/40180 | | | Dennis | CJam | 60 | yes | | | https://codegolf.stackexchange.com/a/40184 | | | xnor | Python 3 | 160 | yes | | | https://codegolf.stackexchange.com/a/40192 | | | COTO | C | 72 | yes | | | https://codegolf.stackexchange.com/a/40198 | | | es1024 | C | 780 | yes | | | https://codegolf.stackexchange.com/a/40202 | | | Gerli | Mathematica | 72 | no | yes | Martin Büttner | https://codegolf.stackexchange.com/a/40230 | https://codegolf.stackexchange.com/a/40242 | | Hydrothermal | JavaScript | 80 | yes | | | https://codegolf.stackexchange.com/a/40235 | | | Sam Yonnou | GolfScript | 48 (frontrunner) | yes | | | https://codegolf.stackexchange.com/a/40239 | | | feersum | Matlab | 48 | | | | https://codegolf.stackexchange.com/a/40310 | | | Beta Decay | Python 3 | 484 | | | | https://codegolf.stackexchange.com/a/40312 | | | potato | Python 3 | 176 | | | | https://codegolf.stackexchange.com/a/40341 | | +--------------+-------------+------------------+---------+----------+----------------+-------------------------------------------+-------------------------------------------+ ``` (Thanks to <http://www.sensefulsolutions.com/2010/10/format-text-as-table.html> for table formatting.) [User COTO](https://codegolf.stackexchange.com/a/40231) made an excellent tool for playing with code-bricks. I've turned it into a convenient snippet: ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>function parseSpec(s){function first(){var e,t;t=S.findIndex(function(t){return(e=t.findIndex(function(e){return/\S/.test(e)}))!=-1});return t==-1?null:[e,t]}function at(e){var t=e[0],n=e[1];return n>=0&&n<S.length&&t>=0&&t<S[n].length?S[n][t]:" "}function wipe(e){var t=e[0],n=e[1];if(n>=0&&n<S.length&&t>=0&&t<S[n].length)S[n][t]=" "}var P,S=s.split("\n").map(function(e){return e.split("")});var oPats=$(".proto-tet [pat]").get().map(function(e){return{sPat:eval("["+$(e).attr("pat")+"]"),e:e,block:function(e){return[at(e)].concat(this.sPat.map(function(t){return at([e[0]+t[0],e[1]+t[1]])}))},wipe:function(e){this.sPat.forEach(function(e){return wipe([P[0]+e[0],P[1]+e[1]])})},match:function(e){return!/\s/.test(this.block(e).join(""))}}});window.oPats=oPats;while(P=first()){var oPat=oPats.find(function(e){return e.match(P)});if(!oPat){orphan(at(P));wipe(P);continue}createPiece(oPat.e,oPat.block(P));wipe(P);oPat.wipe(P)}}function createPiece(e,t){function r(e){var t=$(this).position();G.isIgnoreClick=false;G.eDrag=this;G.iOffsets=[e.clientX-t.left,e.clientY-t.top]}function i(){if(G.isIgnoreClick)return;var e=$(this);s($(".proto-tet ."+e.attr("rr")),function(e,t){return n[t-1]},e.css("left"),e.css("top"));e.remove()}function s(e,t,n,s){e.clone().html(e.html().replace(/@(\d)(\d)/g,t)).appendTo("body").on("mousedown",r).click(i).css({left:n,top:s})}var n=[];s($(e),function(e,r,i){return n[r-1]=t[i-1]},18+G.iSpawn%8*18*4+"px",18+~~(G.iSpawn/8)*18*4+"px");G.iSpawn++}function init(){$(document).on("mouseup",function(){return G.eDrag=null}).on("mousemove",function(e){if(G.eDrag){var t=$(G.eDrag),n=Math.round((e.clientX-G.iOffsets[0])/18)*18,r=Math.round((e.clientY-G.iOffsets[1])/18)*18,i=t.position();if(n!=i.left||r!=i.top)G.isIgnoreClick=true;t.css({left:n+"px",top:r+"px"})}})}function orphan(e){error("Spec character not a part of any block: '"+e+"'")}function error(e){$(".error").css("display","block").append("<div>"+e+"</div>")}function go(){$(init);$(function(){parseSpec($("#spec").val())});$("#spec").remove();$("#info").remove();$("#go").remove()}var G={eDrag:null,isIgnoreClick:true,iSpawn:0};Array.prototype.findIndex=function(e){for(var t=0;t<this.length;t++){if(e(this[t]))return t}return-1};Array.prototype.find=function(e){var t=this.findIndex(e);if(t==-1)return;else return this[t]}</script><style>.proto-tet, .spec{display: none;}.tet-I{color: darkgreen;}.tet-J{color: orangered;}.tet-L{color: navy;}.tet-T{color: darkred;}.tet-O{color: darkcyan;}.tet-S{color: darkviolet;}.tet-Z{color: darkorange;}body > .tet{position: absolute;cursor: move;-webkit-touch-callout: none;-webkit-user-select: none;-khtml-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none;border-collapse: collapse;}.tet td{width: 18px;height: 18px;font: bold 14px "Courier New",monospace;text-align: center;vertical-align: middle;padding: 0;}.error{z-index: 1024;position: absolute;display: none;color: red;font-weight: bold;background-color: white;}textarea{font-family: "Courier New", Courier, monospace;}</style><div id='info'>Put code-bricks here and hit OK. Re-run the snippet to restart.<br>(You may need to replace spaces in code-bricks with some other character first.)</div><textarea id='spec' rows='16' cols='80'>ABCD&nbsp;&nbsp;a&#13;&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;b&nbsp;&nbsp;&nbsp;Oo&#13;&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;c&nbsp;&nbsp;&nbsp;oo&#13;&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;d&#13;&#10;&#13;&#10;&nbsp;E&nbsp;&nbsp;&nbsp;&nbsp;h&#13;&#10;&nbsp;F&nbsp;&nbsp;efg&nbsp;&nbsp;&nbsp;hg&nbsp;&nbsp;&nbsp;GFE&#13;&#10;&nbsp;GH&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;f&nbsp;&nbsp;&nbsp;H&#13;&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;e&#13;&#10;&#13;&#10;&nbsp;I&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;IJK&#13;&#10;&nbsp;J&nbsp;&nbsp;&nbsp;l&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;L&#13;&#10;LK&nbsp;&nbsp;&nbsp;kji&nbsp;&nbsp;kl&#13;&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;j&#13;&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;i&#13;&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t&#13;&#10;&nbsp;OP&nbsp;&nbsp;&nbsp;p&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;QR&nbsp;&nbsp;&nbsp;&nbsp;rs&#13;&#10;MN&nbsp;&nbsp;&nbsp;&nbsp;on&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ST&nbsp;&nbsp;&nbsp;q&#13;&#10;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;m&#13;&#10;&nbsp;W&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;z&#13;&#10;&nbsp;XY&nbsp;&nbsp;&nbsp;&nbsp;zxw&nbsp;&nbsp;&nbsp;&nbsp;yx&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Y&#13;&#10;&nbsp;Z&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;y&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;w&nbsp;&nbsp;&nbsp;&nbsp;WXZ</textarea><br><button id='go' type='button' onclick='go()'>OK</button><div class="proto-tet"><table class="tet tet-I tet-I0" rr="tet-I1" pat="[1,0],[2,0],[3,0]"><tr><td>@11</td><td>@22</td><td>@33</td><td>@44</td></tr></table><table class="tet tet-I tet-I1" rr="tet-I2" pat="[0,1],[0,2],[0,3]"><tr><td>@11</td></tr><tr><td>@22</td></tr><tr><td>@33</td></tr><tr><td>@44</td></tr></table><table class="tet tet-I tet-I2" rr="tet-I3" ><tr><td>@40</td><td>@30</td><td>@20</td><td>@10</td></tr></table><table class="tet tet-I tet-I3" rr="tet-I0"><tr><td>@40</td></tr><tr><td>@30</td></tr><tr><td>@20</td></tr><tr><td>@10</td></tr></table><table class="tet tet-J tet-J0" rr="tet-J1" pat="[0,1],[-1,2],[0,2]"><tr><td></td><td>@11</td></tr><tr><td></td><td>@22</td></tr><tr><td>@33</td><td>@44</td></tr></table><table class="tet tet-J tet-J1" rr="tet-J2" pat="[0,1],[1,1],[2,1]"><tr><td>@31</td><td></td><td></td></tr><tr><td>@42</td><td>@23</td><td>@14</td></tr></table><table class="tet tet-J tet-J2" rr="tet-J3" pat="[1,0],[0,1],[0,2]"><tr><td>@41</td><td>@32</td></tr><tr><td>@23</td><td></td></tr><tr><td>@14</td><td></td></tr></table><table class="tet tet-J tet-J3" rr="tet-J0" pat="[1,0],[2,0],[2,1]"><tr><td>@11</td><td>@22</td><td>@43</td></tr><tr><td></td><td></td><td>@34</td></tr></table><table class="tet tet-O tet-O0" rr="tet-O1" pat="[1,0],[0,1],[1,1]"><tr><td>@11</td><td>@22</td></tr><tr><td>@33</td><td>@44</td></tr></table><table class="tet tet-O tet-O1" rr="tet-O2"><tr><td>@30</td><td>@10</td></tr><tr><td>@40</td><td>@20</td></tr></table><table class="tet tet-O tet-O2" rr="tet-O3"><tr><td>@40</td><td>@30</td></tr><tr><td>@20</td><td>@10</td></tr></table><table class="tet tet-O tet-O3" rr="tet-O0"><tr><td>@20</td><td>@40</td></tr><tr><td>@10</td><td>@30</td></tr></table><table class="tet tet-L tet-L0" rr="tet-L1" pat="[0,1],[0,2],[1,2]"><tr><td>@11</td><td></td></tr><tr><td>@22</td><td></td></tr><tr><td>@33</td><td>@44</td></tr></table><table class="tet tet-L tet-L1" rr="tet-L2" pat="[1,0],[2,0],[0,1]"><tr><td>@31</td><td>@22</td><td>@13</td></tr><tr><td>@44</td><td></td><td></td></tr></table><table class="tet tet-L tet-L2" rr="tet-L3" pat="[1,0],[1,1],[1,2]"><tr><td>@41</td><td>@32</td></tr><tr><td></td><td>@23</td></tr><tr><td></td><td>@14</td></tr></table><table class="tet tet-L tet-L3" rr="tet-L0" pat="[-2,1],[-1,1],[0,1]"><tr><td></td><td></td><td>@41</td></tr><tr><td>@12</td><td>@23</td><td>@34</td></tr></table><table class="tet tet-S tet-S0" rr="tet-S1" pat="[1,0],[-1,1],[0,1]"><tr><td></td><td>@21</td><td>@12</td></tr><tr><td>@43</td><td>@34</td><td></td></tr></table><table class="tet tet-S tet-S1" rr="tet-S2" pat="[0,1],[1,1],[1,2]"><tr><td>@41</td><td></td></tr><tr><td>@32</td><td>@23</td></tr><tr><td></td><td>@14</td></tr></table><table class="tet tet-S tet-S2" rr="tet-S3"><tr><td></td><td>@30</td><td>@40</td></tr><tr><td>@10</td><td>@20</td><td></td></tr></table><table class="tet tet-S tet-S3" rr="tet-S0"><tr><td>@10</td><td></td></tr><tr><td>@20</td><td>@30</td></tr><tr><td></td><td>@40</td></tr></table><table class="tet tet-Z tet-Z0" rr="tet-Z1" pat="[1,0],[1,1],[2,1]"><tr><td>@11</td><td>@22</td><td></td></tr><tr><td></td><td>@33</td><td>@44</td></tr></table><table class="tet tet-Z tet-Z1" rr="tet-Z2" pat="[-1,1],[0,1],[-1,2]"><tr><td></td><td>@11</td></tr><tr><td>@32</td><td>@23</td></tr><tr><td>@44</td><td></td></tr></table><table class="tet tet-Z tet-Z2" rr="tet-Z3"><tr><td>@40</td><td>@30</td><td></td></tr><tr><td></td><td>@20</td><td>@10</td></tr></table><table class="tet tet-Z tet-Z3" rr="tet-Z0"><tr><td></td><td>@40</td></tr><tr><td>@20</td><td>@30</td></tr><tr><td>@10</td><td></td></tr></table><table class="tet tet-T tet-T0" rr="tet-T1" pat="[1,0],[2,0],[1,1]"><tr><td>@11</td><td>@22</td><td>@33</td></tr><tr><td></td><td>@44</td><td></td></tr></table><table class="tet tet-T tet-T1" rr="tet-T2" pat="[-1,1],[0,1],[0,2]"><tr><td></td><td>@11</td></tr><tr><td>@42</td><td>@23</td></tr><tr><td></td><td>@34</td></tr></table><table class="tet tet-T tet-T2" rr="tet-T3" pat="[-1,1],[0,1],[1,1]"><tr><td></td><td>@41</td><td></td></tr><tr><td>@32</td><td>@23</td><td>@14</td></tr></table><table class="tet tet-T tet-T3" rr="tet-T0" pat="[0,1],[1,1],[0,2]"><tr><td>@31</td><td></td></tr><tr><td>@22</td><td>@43</td></tr><tr><td>@14</td><td></td></tr></table></div><div class="error"></div> ``` [Answer] # Java : 360 area > > # Bounty: 500 > > > Reconstructing these things is hard! That's probably why there aren't too many robbers participating in this challenge. However, I *want* to see mine cracked. So, instead of giving the solution after 72 hours, **I'm putting up 500 rep to the first successful cracker.** To clarify, I will add a +500 bounty to the answer post and award it to your crack if you reassemble these pieces into any working, rectangular Java program that outputs "Tetris". I am not preemptively activating the bounty, because I don't feel like wasting rep if nobody answers. > > > There is no end date to this offer. It's valid as long as I'm a member here. To ensure I see your answer, ping me with a comment below. > > > I've triple-checked to make sure the pieces (and code) are valid, but if a trusted user wants to confirm this, I can email/something the solution to them. Obviously, that would exempt them from posting it and collecting the bounty. > > > Made of a mix of all seven piece types. To make things easier(?) I've made sure that all pieces of the same type are rotated to the same orientation. Since Java has parts that can't be changed much, I've left the *really* obvious parts as simple I-blocks to get it started. **Note:** Since Java has a few mandatory spaces, I've replaced them with underscores (`_`)below for layout purposes. There are 11 of them total, and they should all be converted to spaces to run the code. No other whitespace is present in the code, any below is just for positioning. There are: * 41 I * 15 O * 11 J * 8 L * 6 T * 6 S * 3 Z **Have fun!** ``` ------------- I clas s_X{ publ ic_s tati c_vo id_m ain( Stri ng[] 2;c* p(b- (b-c _voi nt_a Syst em.o ut.p rint 1,c= d=1, e=3, new_ int[ ;b++ for( 1008 ?1:2 )a); ccc+ ==++ pf}( for( (b); p(b+ --b- or(d 1?1: +1;e for( =1); ------------- O a) *2 b= r( 12 <3 36 [c *1 ++ b< 6] 64 64 7] ]- <1 1; 89 0; ;p c) =0 ic st ch at ar d/ 1; -------------- T {in ] +b( 5 d/2 ; d<< ) ;;; 1 =1) ( ------------- L 2=[ + ]b* 8 =1) ] <<b < }_} d 3=b ) +[[ = =c, = -------------- J o ;b= , 2;) f 2;c * =][ c f=d + e1+ e =;; d _p( i <++ = ){_ [ f+e ---------------- S t_ ;f c+ 1) +< ;p 64 <6 b= ;p )) (; --------------- Z 4, -1 ;= ff ;f 0; ``` [Answer] # Brainfuck, 108 area This code was made of 27 I pieces. ``` -.[> .<++ .<++ [>++ [>++ -]++ ]>.- -]>[ -]>+ ]>++ +.+- +[>+ +-+- ++[> ++[> ++]- ++++ ++++ +++< +++< +<-] --<- <-]> <><+ >+.> >++[ >+<< ``` I don't know if there is any way other than bruteforce to find the answer. If there is, i'd really like to know how. [Answer] ## Python 3: 212 area [Rebuilt] My code is broken up into the following 53 `I`-pieces, which I've written one per line alphabetically. ``` (358 0048 0396 0796 0824 0981 1013 1314 1330 1438 1502 2285 2317 2479 2585 2955 3116 3738 3818 4169 4356 4360 4632 4800 5016 5153 5256 5394 5598 5631 5758 5840 6312 6425 6539 7045 7156 7163 7329 7624 7674 8164 8250 8903 9%38 9009 94)) 9413 9748 etri prin s'* t('T ``` Have fun! [Answer] # JavaScript - Area 80 Seems like a lot of these answers are just using lots of I pieces and maybe an O piece or two, so I threw this together with some of the more interesting shapes. * 7 I pieces * 1 L piece * 1 J piece * 4 O pieces * 6 T pieces * 1 S piece Each piece is separated by two spaces. The two hash signs are actually spaces in the code. ``` l n \ / ; + r o - x c v ( i g ( 5 o a ; s ) o // #c ns -> ) " d l e l wi ( " 4 n r ; " x65 log ;/ ") ]. "c "(# o+\ ave ow" t"o "Te [" ``` Have fun! [Answer] ## Javascript, area 420 Only I-blocks. ``` !!!( !!!+ !!!+ !!![ !!!] !!!] !!!] !!!] !!!] !!'! !![] !!]] !(!+ !(![ !+!] !+!] !+"+ !++) !++[ !++[ !++[ !++[ !++] ![+[ !](+ (!!' (!!+ (!(] (++! (['[ )!'! )[)[ )]]! +++" +++) ++++ +++[ +++] ++]) +[+[ +[[[ +]'+ +]'] +]+[ +]+[ +]]! +]]! +]]! +]]! +]]' +]][ +]]] [!!+ [!!+ [!!+ [!!+ [!!+ [!!] [!+! [![[ [![[ [((! [))! [){! [+'+ [++) [++] [[)+ [[+[ [[[! [[[' [[[+ [][] []]] [{[[ ]!(! ]!]+ ]['[ ][[! ][[! ][[! ][[! ][[( ][[+ ][[+ ][[[ ][[[ ][]] ][}! ]]T] ]][( ]]]! ]]]! ]]]' ]]]) ]]]] ]}]] a['! e]'( l++[ v).! {[[[ {]g] })') }]]] ``` No any standard obfuscators were used. All code including obfuscation and making this sorted list of blocks is made by less then 16 lines of my own code. --- It's time to show how it was made: ``` x="+[],+!![],+!![]+!![],+!![]+!![]+!![],+!![]+!![]+!![]+!![],+!![]+!![]+!![]+!![]+!![],+!![]+!![]+!![]+!![]+!![]+!![],+!![]+!![]+!![]+!![]+!![]+!![]+!![],+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![],+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]".split(/,/g) res={} for(q=0; q<x.length; ++q) res[eval(x[q])]=x[q] function add(str) { for(q=0;q<Math.min(str.length,10);++q) res[eval(x=str+"["+res[q]+"]")]=x } add("({}+[])") add("(![]+[])") add("(!![]+[])") add("([][[]]+[])") code = 'eval('+Array.prototype.map.call('console.log("Tetris")',function(x){return res[x]||"'"+x+"'"}).join("+")+')' res=[] console.log(code) code.replace(/(.)(?=.{104}(.).{104}(.).{104}(.))/g,function(m,a,b,c,d){res.push(a+b+c+d)}) eval(res.map(function(x){return x[0]}).join("")+res.map(function(x){return x[1]}).join("")+res.map(function(x){return x[2]}).join("")+res.map(function(x){return x[3]}).join("")) console.log(res.sort().join("\n")) ``` So, it's just call to `eval` with obfuscated `'console.log("Tetris")'` argument, which is 420 symbols in length. It is splitted into 4 lines of 105 symbols and read by columns and alphabetical sorted. Obfuscation for 10 digits is hardcoded, for other symbols used first 10 symbols from 4 combinations passed to `add` function. If there is no obfuscation for some symbol it is passed as is. [Answer] # C, 80 area Made of 12 `I` pieces and 8 `O` pieces. C syntax is always fun. `I` pieces in no particular order: ``` c[] // starts with a space ','n ',;} (q){ ,', // ends in a space u>6/ T2sr char main q/** t#1' ts(c ``` `O` pieces: ``` q< pu 't i' Ir $' /} ); '? re ', `: "e i> ={ ,0 ``` [Answer] # CJam, 60 (15 O's) ``` 71 05 37 23 36 04 27 69 32 :i 12 93 bi i] 43 69 44 71 71 -# 70 10 25 44 cb 93 20 *G 9B 62 ``` ### Solution > > `27` > > `10` > > `96` > > `17` > > `54` > > `04` > > `52` > > `96` > > `71` > > `37` > > `12` > > `93` > > `43` > > `62` > > `29` > > `03` > > `07` > > `40` > > `44` > > `23` > > `72` > > `13` > > `]B` > > `i9` > > `*b` > > `Gi` > > `6#` > > `3-` > > `ib` > > `:c` > > > [Answer] # Befunge, 360 area 90 `O`-pieces. ``` " #6 " #^ # # # 4 + $ + 0> + v_ 0 > 3 # > \ ^ /1 _ v8 v $, ~ *= !! 00 !< v> "! < "< #^ "> ^< "v # "v w\ # # # |_ #* _* #0 .@ #3 ~# #? t@ #^ RI #v ~> #~ ~# $ !4 &v v# *# "# ** >^ +1 >^ +5 , +^ S" - #" -# 2\ -~ # 0 |> 00 00 0< v\ 2, +# 2v ^v 3# < 3# >2 3~ ^- 47 31 6 6# 70 "T 8# :\ :# # :$ $* :0 3< < #$ <* <| << >> <> <> <@ > <~ 2, > 7< >$ ^6 >> << >v |g \ ^ \_ ! ^ <s _! >9 _$ ET kr > m~ #3 q~ ~+ r^ c t~ , v ? v/ _$ v4 >> v7 ># v< ># v< ># v> :^ v~ 1/ zr $ ~# #~ ~# \# ~$ 7> ~3 $_ ~v \$ ~~ ~# ``` You can [try it here](http://www.quirkster.com/iano/js/befunge.html). > > > ``` > 3#~#~vm~00-~q~\_:$:#r^&v_!!<v< > >2\#\$#300 #~+ !$* #c v#>9v>># > "v0< 36 v < ~~ ^<~^ <<<@\ -##v > w\v\# 6# ?#$~#/12,<s>> >^ 2\~> > "> +>$ +:0 _ #2,v/$ >>v4v7- 3~ > ^<0>^6v_3<v84 +#_$!4<<>>>##"^- > <*8#> #0 v ~v~2v#~~#kr"v "zr"< > <|:\7<.@$,*=1/^v~##~ ># #6 $#^ > #*+1# 3# 0470 >vv< ## ~$t~ "<> > _*>^|_< > 31|>|g>## #7>, #^<> > 70_$#^+^~3 +** >v>!!+5#3*#"!#? > "TETRIS"$_$ >^\ :^00 ,~#"#< t@ > ``` > > > > There are probably other solutions. I didn't rotate the bricks. > > > [Answer] # GolfScript 48 `I` pieces: ``` !;.. )+?; ``` `O` pieces: ``` .[ ;* .( ): ++ -\ ``` `T` pieces: ``` +]\ +++ ;). );. . * , ) ``` `J` pieces: ``` . ) * (@@ :?, .,: ``` ### Solution > > `.[!)):,.` > > `):;+:?,*` > > `;*.?;).+` > > `++.;),*+` > > `.(..;).+` > > `-\(@@\]+` > > > [Answer] ## Python 3: 340 area [Rebuilt] Made of 85 `I`-pieces, given here alphabetized one per line. ``` #Four spaces #Four spaces #Four spaces #Four spaces #Four spaces #Four spaces #Four spaces #Four spaces #Four spaces )) #Two spaces 0290 0398 0866 0887 0892 0992 1108 1268 1297 1339 1555 1722 1817 1848 1930 2328 2521 2611 2747 3179 3192 3245 3284 3334 3613 3862 4086 4629 4639 4674 4695 4781 4968 5723 5742 5791 5938 6011 6069 6180 6231 6265 6269 6444 6564 6776 6884 7116 7253 7348 7440 7527 7743 7873 8064 8291 8808 8843 9305 9324 9458 9460 9586 9869 ==== a,b, abcd c)-d etri pow( prin s'*( t('T ``` As a Python list: ``` [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ')) ', '0290', '0398', '0866', '0887', '0892', '0992', '1108', '1268', '1297', '1339', '1555', '1722', '1817', '1848', '1930', '2328', '2521', '2611', '2747', '3179', '3192', '3245', '3284', '3334', '3613', '3862', '4086', '4629', '4639', '4674', '4695', '4781', '4968', '5723', '5742', '5791', '5938', '6011', '6069', '6180', '6231', '6265', '6269', '6444', '6564', '6776', '6884', '7116', '7253', '7348', '7440', '7527', '7743', '7873', '8064', '8291', '8808', '8843', '9305', '9324', '9458', '9460', '9586', '9869', '====', 'a,b,', 'abcd', 'c)-d', 'etri', 'pow(', 'prin', "s'*(", "t('T"] ``` [Answer] ## Python 3: 160 area After [feersum's crack](https://codegolf.stackexchange.com/a/40142/20260), I tried to tighten up my code to make it harder to avoid cryptographic mumbo-jumbo. It's made of 40 `I` pieces, listed one per row: ``` ') #Two spaces )-d) *'Te ,b,c 0484 0824 2448 2562 3094 3762 3896 4052 4233 4562 5266 5277 5400 5885 5927 5965 6080 6720 6808 6884 7568 7856 7963 8609 8639 8665 8732 8892 9206 9893 ==== abcd ow(a prin t((p tris ``` As a Python list: ``` ["') ", ')-d)', "*'Te", ',b,c', '0484', '0824', '2448', '2562', '3094', '3762', '3896', '4052', '4233', '4562', '5266', '5277', '5400', '5885', '5927', '5965', '6080', '6720', '6808', '6884', '7568', '7856', '7963', '8609', '8639', '8665', '8732', '8892', '9206', '9893', '====', 'abcd', 'ow(a', 'prin', 't((p', 'tris'] ``` Changed: * Reordered string multiplication to try to force `pow` to be used * Fewer spaces (though shorter numbers) * No `1`'s I am worried about the many factors of the area though. [Answer] # C - Area 72 **Blocks:** ``` I J _______ L ______ O __ Z _ _______ T ______ / \ / \ / \ / \ " e m " T ) 6 }; ii 3" (. \nn {6" ]"0 i%s i t p , & m 1 -] ar "\ f( t 8 e T s )" .[ 0x ,f ai 0r " "" (t [" )" 61 4+ \____ ____/ S ``` Since the only other C submission was cracked. ;) A neat 72 characters. Pure obfuscation. No NP-hard problems to solve or huge integers to factor. Borrows some tricks from one of the greats. **Spaces are represented using `.`s. No actual `.`s appear in the solution.** I've triple-checked the solution to ensure validity of the pieces. [Answer] # CJam, 80 area 20 `O`-pieces. ``` I `7 &d 'X +5 7m -2 `- -6 #b -O U[ 3Z Pi 4" 2X 43 P" ?< 5b D: .= FH uL K` ~C QT :c [^ +9 aj ^F hD dP tn 6 uq KG x6 CF ``` > > `-24"hD&d ID:uqx6tn-OajFH43[^+5?<3ZK`-6QT` > > ``-2XdP'X`7.=KGCF6 U[^FuLP"+97m5bPi~C#b:c` > > > > I didn't rotate the bricks. > > > [Answer] # C - Area 780 There are 195 pieces in total. No comments were used. Nothing particularly complicated. Note: all backslashes (`\`) are to be replaced with spaces. 95 `I` Pieces: ``` ____ x12 incl \edu \\\\ \\\\ \\\\ dts< h.oi *_*> _,_( int\ __;\ ,_(_ _*_, =__, __"* +|_; r__+ ahct )=pu _\ra f\ch edep #t_, y___ *_;_ (_;- ){__ ,<_\ 9"=_ +__* ___; _+>_ _??< +__* *__, __*_ *=+_ __:- ___- _+__ ,___ ,__, _,*& *\&* _,*_ _++, +,__ ++++ +__= _++, ,,,_ ___+ =+__ ?++_ ___+ =__+ ,<_* __+* &+;* +*__ __*_ __+, ++?~ __-9 _?__ __*_ (_+_ [**( _<&_ };__ _@A: (nia @@@@ AAAA AAAA ~~~~ _++; _&,) A__+ ~~__ g_"" _;}_ +*__ ``` 35 `O` Pieces: ``` __ __ (x18) )_ __ _* _\ _; ,- _* __ ~) "{ +_ +_ *_ ,_ __ _) ~~ a~ _, __ __ ,) _: __ +* __ __ +, *+ _+ AA AA __ ,+ ``` 18 `L` Pieces: ``` ___ _ (x2) _;* _ _=_ + __* _ +__ _ **_ & +*_ _ &*& , ++, _ _*_ _ ;;_ " __+ _ AAA ~ "*) ; ___ ( ,_- _ _~^ _ ``` 25 `J` Pieces: ``` _+= + +,_ _ *__ ; ;;_ \ _,_ ) ~~~ _ ___ A ~;( _ ;__ i _;m A =__ _ a;a A ="A a ~_\ o o_a a ~~~ _ 99- _ *9_ _ __) _ __* < +_, _ _++ = _+_ _ ++_ _ _+: _ ``` 10 `T` Pieces: ``` _ ,__ + *?_ = **= _ __+ _ :_+ _ _+_ _ (_- + ++, + ___ * __: ``` 4 `Z` Pieces: ``` =* ++ *+ __ t_ -~ __ f( ``` 8 `S` Pieces: ``` _, _, __ __ (x2) -_ __ (x2) _9 ~_ 99 __ __ ], ``` ### Solution > > `#include <stdio.h> > typedef char _________; int (* > _____)()=putchar;____(_,___,__ > ,______) _________*__,* *___,* > ______;{__="9>?_|";______=*___ > ;--_;--_<*__++?++*______,_+=_+ > _:___,__,___;_<*__++?*______+= > *______,++______,__,*______+=* > ______,__,++______,*&*______+= > *______,++______,* &*______+=* > ______,++______,*&*&*______+=* > ______,++______,_,*______+=*&* > ______,_+=_+_:__,_;_<*__++?++* > ______++,++*______++,++*______ > ++,++*______++,++*&*______++,_ > ,++*______,_+=_+_+_+_:______;_ > <*__++?~_____(_-_+_-_)^~_____( > *______),++*___,_____,_,_+=*&* > ______,_+_:_____(_+_-_-_);;_<* > __?--*______:___;}_________ _[ > 999-99-99],*__=_;main(______){ > _________*___="AAA@@@@@~~~~~~" > "~~~~~~aAAAAAaAAAAAAAAAAAAA;;" > "aa~~~~~~~~~a;a";_____:____((* > ___-______),&__);if(__,*++___) > goto _____;++______;++______;}` > > > [Answer] # Wolfram, area 72 Everywhere you see a dash (-), replace it with a space ## i ``` h01- r*1/ ``` ## j ``` 6 115 ``` ## l ``` m +1C t *0e e ,,[ ``` ## o ``` r4 a+ ``` ## s ``` 10 -1 +1 Pr ``` ## z ``` ro 8* ac -1 od +1 ``` ## t ``` --F { ,50 0 /]} -- fixed bracket directions 0 1-, , 01C 0 tni 4 ``` [Answer] # MATLAB, area 48 Unfortunately, it does not seem to work in Octave. ``` - ^-1 ' 'u" v'+ e [[' ; '.i ] lmi a kv hW .x ). 3) t; b( 'p ('l; .]'e ``` [Answer] # Python 3 176 Area I don't use underscores in this program, so I decided to replace all spaces with underscores for added readablity. Make sure to replace them back to spaces when failing to put it back together. ## I Blocks: ``` 1456 "jtr \)\~ tris ],i) t="" 2697 t(t[ _r+2 _r_i ``` ## O Blocks: ``` i_ s_ _; 32 6# an ". +- t) in n( _[ "" (c ap ri ``` ## L Blocks: ``` = #14 . \n" ; "(t i T%" o :=i r ioj 6 mp# ``` ## J Blocks: ``` 6 2(h 5 574 # "=t 7 spl f o__ s (s_ n ];# 0 t=_ * #)( ``` ## T Blocks: ``` =_1 _ 295 r 21, r ,2) . ``` ## Z Blocks: ``` 46 "" "5 3" #t )n 1t ), ``` ## S Blocks: ``` ge 34 nt 68 ``` [Answer] # Python 3 ## Area - 484 Spaces replaced by `%`. There are some comments used as padding. Quite a bit of repetition of code. May be quite complicated. ### 121 Os ``` 41 )+ %r 1- :# 1# %r 1- 01 ,+ a1 n+ )) 0+ h1 r- #0 ## -- ge 11 1- hr 1- -- -1 ap 0+ +1 +' h0 r+ :1 ## 11 1- )) 0+ a0 p+ n0 d+ f% oz -1 0+ hr 1- n0 d+ a0 p+ a1 n+ +0 1+ hf .= i1 %- f% oa a1 n+ (c 0+ (0 1+ 0, 1+ i1 n+ in 1+ r+ %= -0 1+ fo %l n' d' -- =1 p1 %- -; -a -; -h a1 n+ pe 0+ pe 0+ -1 0+ n0 d+ 11 0- a0 p+ i1 n+ hz .= n0 d+ ## )# 5) 1+ g( 1- %1 r- (c .j (0 c+ 11 0- (z n( g( 1- 41 )+ )s )' in 1+ r+ %= ap in g( 1- 01 ,+ -a -n (l 1+ pt e( %1 r- -# ]# (1 f+ g1 (- h. l= 01 ,+ h. pr :1 ## :# 1# (1 z+ r+ %= +1 0+ p0 e+ r% += (a 0+ hz .= +0 1+ (0 c+ )) 0+ #0 ## q% 1- g1 e- -0 1+ #0 ## pe 0+ -1 h) 61 )+ an 1+ -- ng fo %f )0 )+ f% oz -= -[ 11 )+ q1 %- :# 1# +0 1+ -- =r j1 %- ho ri #- ra (0 c+ i1 n+ ,1 8- r+ %= %1 r- ## 0# ``` ]
[Question] [ Produce this square snowflake. ``` XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XX X X X X X X X X X X X X X X XX X XXXX XXXXX XXXXX XXXXX XXXXX XXXXX XXXXX XXXX X XX X X X X X X X X X X X X XX X X XXX XXXX XXXX XXXX XXXX XXXX XXXX XXX X X XXX XX X X X X X X X X X X X X X X X X X X XX XXX X X XXXX XXX XXX XXXXX XXX XXX XXXXX XXX XXX XXXX X X XX X X X X X X XX X X X XXX XXX XXX XXXX XXXX XXX XXX XXX X X X XXX XXX XX X X X X X X X X X X X X XX XXX XXX X X X X XXXX XXXXX XXX XXX XXX XXX XXXXX XXXX X X X X XXXXX XX X X X X X X X X X X XX XXXXX X X X X X XXX XXXX XXXXX XXXXX XXXX XXX X X X X X XXXX XX XXX XX X X X X X X X X X X X X XX XXX XX XXXX X X X XXXX XXX XX XXXX XXXX XX XXX XXXX X X X XX XX X X X X XXX XXX XXX XXX XXX XXX XXX XXX X X X X XXXX XX XXX XXX XX X X X X X X XX XXX XXX XX XXXX X X X X X X X XXXX XXXXX XXXXX XXXX X X X X X X X XXXXX XXXXX XX X X X X XX XXXXX XXXXX X X X X X X X X XXX XXXX XXXX XXX X X X X X X X X XXX XXX XXXX XX XXX XX X X X X X X XX XXX XX XXXX XXX XXX X X X X X X XXXX XXX XXX XXXX X X X X X X XXXXX XXX XX XX XXX XXXXX X X X X X X X X X XXX XXX XXX XXX X X X X X X X X X XXX XXXX XXXX XXX XXX XX X X XX XXX XXX XXXX XXXX XXX X X X X X X X X X XXXX XXXX X X X X X X X X X XXXXX XXXXX XXXXX XX XX XXXXX XXXXX XXXXX X X X X X X X X X X XXX XXX X X X X X X X X X X XXXX XXX XXX XX XXXX XX XXX XX XX XXX XX XXXX XX XXX XXX XXXX X X X X XXX X X X X XXX X X X X XXX X X X X XXXX XXX XXX XX XXXX XX XXX XX XX XXX XX XXXX XX XXX XXX XXXX X X X X X X X X X X XXX XXX X X X X X X X X X X XXXXX XXXXX XXXXX XX XX XXXXX XXXXX XXXXX X X X X X X X X X XXXX XXXX X X X X X X X X X XXX XXXX XXXX XXX XXX XX X X XX XXX XXX XXXX XXXX XXX X X X X X X X X X XXX XXX XXX XXX X X X X X X X X X XXXXX XXX XX XX XXX XXXXX X X X X X X XXXX XXX XXX XXXX X X X X X X XXX XXX XXXX XX XXX XX X X X X X X XX XXX XX XXXX XXX XXX X X X X X X X X XXX XXXX XXXX XXX X X X X X X X X XXXXX XXXXX XX X X X X XX XXXXX XXXXX X X X X X X X XXXX XXXXX XXXXX XXXX X X X X X X X XXXX XX XXX XXX XX X X X X X X XX XXX XXX XX XXXX X X X X XXX XXX XXX XXX XXX XXX XXX XXX X X X X XX XX X X X XXXX XXX XX XXXX XXXX XX XXX XXXX X X X XXXX XX XXX XX X X X X X X X X X X X X XX XXX XX XXXX X X X X X XXX XXXX XXXXX XXXXX XXXX XXX X X X X X XXXXX XX X X X X X X X X X X XX XXXXX X X X X XXXX XXXXX XXX XXX XXX XXX XXXXX XXXX X X X X XXX XXX XX X X X X X X X X X X X X XX XXX XXX X X X XXX XXX XXX XXXX XXXX XXX XXX XXX X X X XX X X X X X X XX X X XXXX XXX XXX XXXXX XXX XXX XXXXX XXX XXX XXXX X X XXX XX X X X X X X X X X X X X X X X X X X XX XXX X X XXX XXXX XXXX XXXX XXXX XXXX XXXX XXX X X XX X X X X X X X X X X X X XX X XXXX XXXXX XXXXX XXXXX XXXXX XXXXX XXXXX XXXX X XX X X X X X X X X X X X X X X XX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX ``` [TIO link](https://tio.run/##rVdLksQgCN1zCi7Q9@EAPdW73kzN@XuSUiM@0XTytCrlJwjiA4Tfn@fj9f77bM3MlPhk61Rvf9v@nUsaX@/VZB9oapb5fj3fBrv8oktd/26@75Q0znwv9fn@0lJhqcdhzuaJiVRVmmZw193/vCDHkVpce3rEPsuvayBvOnf2U6/F49vpC7gXpuINosMZe6d73iWeyOlugLcB7mWX5EUFOzCwNwPcc5fw13pN1v6uUgH3sktiWIcNCVD@uc@DfDiezuNBQ2cFf7i0mb8jrUSEE39HarEIprG/I600PtPbgQ5wd/ZfSQI70AHuiv5fN8TxwCnjjVtCE9Ux7nAH4nQHd41x9@HU@7867p0dNLIbapk9EBPcO//XIGhEuAO1QGAM7GDwC/xfHf6NHQDuQC1n7n4SEGj5vP7c/a/An7E/3v45/1vl/3fjDx//uPi7Iv4z7w///nHv7@L3/3L@wec/XP61Iv9j8k8@/@Xy70X5/@36g69/uPprQf1H1Z90/cvV3/8), and a [more square spaced-out version](https://tio.run/##zVlLdsMwCNxzCi7Q@3CA9nXXTV/O3@bTNLICjJEdj5RFLEtGIDSA4Pvj/e3z6/RzbqaXnyrlX27Peu0f/X9Z/c5P8/aQ/vlJ7v1ls47X/cevb8T@x1u9eLP3HP9bU9q3S15f129PXTun51CdXdk63vAhjjaSZuAs4@8XM@R5fzKcrqGOcN7K7s3KZRsf96yNd0YivGK9pvju@ZTIHmD8or6v78VaEtHx9W0Az5bju19LrNN4jn8DtsxyfHe9B97VPUOWfevKmeK7X0sK6BxogAKQfQ8/nsme7xvCv9bw7eodn69B/43oylp6Q/4b0RZbjZ8B/43oiiU4wfjXGr5dO@/RWId/reH7ycdF9jLa3yq@I9/j@3dkW6v4TvUvFmgm858VfEcxp@/fNeAb4z@WOaQtFfthqXYH7hZSjZVi/eOYQ4F/R0j19V/7KvPvGuA9xn@O75S2bPXemyIAsux8vfPO/Bx459g6vp3n@bi5/PuxsQ0/ruPFtHPE85y7DP8ex7vDznx/f3Xugp@34eWs5sjXcXKV/DwtL0c9U37@6NoEvy7Dq0nNUI9j1SLZdVhiDfoX). **How it's made** You start with a initial crystal (cell) at the center. Then, a new crystal is formed simultaneously at each empty space that touches exactly one existing crystal, looking at the 8 cells orthogonally or diagonally adjacent to it. Crystals remain indefinitely. Here is the snowflake after 3 steps, marking the crystals added at each step. ``` 333 333 32 23 3 111 3 101 3 111 3 32 23 333 333 ``` We continue this for 31 steps, making a 63-by-63 snowflake with 1833 crystals. This process is the Life-like (totalistic) cellular automaton B1/S012345678, also known as H-trees or Christmas Life. **Output** Output or print in any 2D array format with two distinct entries for crystal and empty space, or anything that displays as such. The grid must by exactly 63 by 63, that is having no wasted margin. It's fine to have trailing spaces for non-crystals or jagged arrays truncated to the last crystal in each row. A trailing newline is also OK. Bit representations are not valid unless they display with two distinct symbols for the bits by default. --- I also posted this challenge [on Anarchy Golf](http://golf.shinh.org/p.rb?Square%20a%20snowflake). It requires a strict output format of the ASCII art above of `X`'s and spaces. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~21~~ 19 bytes ``` l31:"TTYat3Y6Z+1=Y| ``` [**Try it online!**](https://tio.run/##y00syfn/P8fY0EopJCQyscQ40ixK29A2sub/fwA) ### Explanation ``` l % Push 1 (this is the initial 1×1 array) 31:" % Do 31 times TTYa % Extend with a frame of zeros in 2D t % Duplicate 3Y6 % Push [1 1 1; 1 0 1; 1 1 1] (8-neighbourhood; predefined literal) Z+ % 2D convolution, maintaining size. This gives the number of active % neighbours for each cell 1= % Equal to 1? Element-wise Y| % Logical OR % End (implicit) % Display (implicit) ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~31~~ ~~29~~ 27 [bytes](https://github.com/abrudz/SBCS) ``` (⊢∨1={≢⍸⍵}⌺3 3)⍣≡∘.×⍨32=⍳63 ``` [Try it online!](https://tio.run/##AV4Aof9hcGwtZHlhbG9n//8o4oqi4oioMT174omi4o244o21feKMujMgMynijaPiiaHiiJguw5fijagzMj3ijbM2M/9m4oaQ4o2O4oqDwq8z4oaR4o6VU1JD4o6VVEhJU/9m "APL (Dyalog Unicode) – Try It Online") -4 bytes thanks to @ngn. A full program that prints a boolean matrix. ### How it works ``` (⊢∨1={≢⍸⍵}⌺3 3)⍣≡∘.×⍨32=⍳63 32=⍳63 ⍝ A 63-length vector whose center element is 1 ⍝ and the rest is 0 ∘.×⍨ ⍝ Outer product self by ×, giving initial state of CA ( )⍣≡ ⍝ Run the cellular automaton until it stabilizes... {≢⍸⍵}⌺3 3 ⍝ Count ones in 3-by-3 subgrids 1= ⍝ Test if the 3×3 subgrid has exactly one alive cell ⊢∨ ⍝ or the cell is already alive ``` [Answer] # [Python 2](https://docs.python.org/2/) with scipy, 105 bytes ``` from scipy.signal import* A=[1], K=1,1,1 exec"A=convolve2d(A,[K,(1,9,1),K]);A=(A>8)+(A==1)+0;"*31 print A ``` [Try it online!](https://tio.run/##bZDBasMwDIbvfgrhXeLWlLm7bCse@JzLjoMkjKxxGo1ENo7TJU@fNU1gl0kgIfH9P0J@io2j4/wAvY1AQ@cn8AEpgvMRHUF02/yFFyhDKCeGnXdhg9m9Hm7izzu2qvokNsH2jWsrvQJItYQWyf5gFZu/pZjr4Droz7i44IXKFlb/HTM6U4VkqVbylsyO9syNPju6uvZqj1ViZJbKRMkXqYRMC3EyOjFvz2KfGK2V2D@e@O5JsfV@M6@d56T/jZzeg40Ra7QVuCH6IebEWe0CBEAC88q2V3B@@HZICYcPno3FQowLEcT8Cw) Use convolution to grow the array. The convolution kernel used is: ``` [[1, 1, 1] [1, 9, 1] [1, 1, 1]] ``` and the criteria for living cell is: ``` c >= 9 or c==1 ``` aka when the cell is already living or when there is exactly 1 neighbor. Note that NumPy by default only prints a summary of a large array, like so: ``` [[1 1 1 ... 1 1 1] [1 1 0 ... 0 1 1] [1 0 1 ... 1 0 1] ... [1 0 1 ... 1 0 1] [1 1 0 ... 0 1 1] [1 1 1 ... 1 1 1]] ``` Thus, I have to call `numpy.set_printoptions` to force Numpy to prints the entire array. This part is not included in the byte count, since I dont't think it's relevant to the actual problem. This [114 bytes function](https://tio.run/##Fc1BC4MgGIDhe7/iw5OWxGyXLXHguT8wiA6jbHOUypeL@vWueK8PvGGPH@@qlAYzwkhZrVUrOi4bJfiRNJvpiVa9d6ufVlMNVPO24VTwOxeMNx2TWlH9uLGCaqUEKy6S5Fch0cQfOtDZiH6GpbdhLxf7dq8J7Bw8xjxpUOcyGz0Cgj1wnUFA6yIQUn69dZTAk7Rbd4rtFMjSHw) returns the array instead of printing it out, thus circumventing the print option problem. [Answer] # [J](http://jsoftware.com/), 38 34 bytes ``` 3 3(1 e.+/,4&{)@,;._3^:31*/~0=i:62 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/jRWMNQwVUvW09XVM1Ko1HXSs9eKN46yMDbX06wxsM63MjP5rcvk56SloYFVZY@VQo@ego2YQZ2WhCdKmo2fIlZqcka@gkPYfAA "J – Try It Online") *-3 bytes thanks to ngn* *-1 byte thanks to Bubbler* [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/jRWMNQwVUvW09XVM1Ko1HXSs9eKN46yMDWO19OsMbDOtzIz@a3L5OekpaGBVWmPlUKPnoKNmEGdloQnSp6NnyJWanJGvoJD2HwA "J – Try It Online") Core ideas taken from [Bubbler's elegant APL answer](https://codegolf.stackexchange.com/a/204636/15469) -- be sure to upvote him. This was an experiment to see how close I could get using J, which lack's APL diamond operator and so is at a disadvantage. Instead, J has [SubArrays](https://code.jsoftware.com/wiki/Vocabulary/semidot3), which requires you to manually add the padding of zeros. I opted here to add all the padding at once, up front: a 125 x 125 matix of zeros with a 1 in the center. After each iteration, we'll lose 2 from our dimension, so after 31 iterations we'll be down to 63 x 63, which is what we need. [Answer] # JavaScript (ES6), ~~149 138 136~~ 135 bytes Returns a binary matrix. ``` f=k=>k>31?m:f(-~k,m=(k?m:a=[...Array(63)]).map((r=a,y)=>r.map((v,x)=>k?v|!~(g=d=>d--&&g(d)-~~(m[y+~-(d/3)]||0)[x-1+d%3])(9):x*y==961))) ``` [Try it online!](https://tio.run/##LY3BioMwFEV/xS6mea@aOCIUKryU/kXBcRGMShtNJC2iIPl1x6GzPJzLuU81qVftH@ObW6ebbWvJkDQyz65D0QIPJhkIzA6KSiHEzXu1wDnHCsWgRgBPKlmQpP/glMw7mOu0HgJ0pElqzo/HDjTyEGAolzhw0OkeWNdvLGeexforrxAuWMynhehyzhBxq519ub4Rveughc@Zj0hGXjzdwwJjKHwz9qpuIBVpl0T2z7LozkpbIf6vfizbY78 "JavaScript (Node.js) – Try It Online") ### Commented The same `map()` loops are used to initialize the 63x63 binary matrix `m[]` and to recursively update it. Doing a separate initialization of `m[]` before entering the recursion would cost more bytes. ``` f = k => // f is a recursive function taking a counter k k > 31 ? // if k is greater than 31: m // stop recursion and return m[] : // else: f( // do a recursive call: -~k, // increment k m = ( // update m[] k ? m // if this is not the first iteration, use m[] : a = [...Array(63)] // otherwise, use a vector a[] of 63 entries ).map((r = a, y) => // for each row r[] at position y, using a[] // as a fallback for the first iteration: r.map((v, x) => // for each value v at position x: k ? // if this is not the first iteration: v | !~( // if v is already set, let it set g = d => // or use the result of the recursive // function g taking a direction d d-- && // decrement d; stop if it's zero g(d) - // recursive call ~~( // subtract 1 if the cell at ... m[y + ~-(d / 3)] // ... y + dy ... || 0 // )[x - 1 + d % 3] // ... and x + dx is set )(9) // initial call to g with d = 9 : // else (first iteration): x * y == 961 // set the cell iff x = y = 31 (because 31 // is prime, it's safe to test xy = 31²) ) // end of inner map() ) // end of outer map() ) // end of recursive call ``` [Answer] # T-SQL, ~~330~~ ~~266~~ 232 bytes This takes a long time to execute(reason: must be something wrong with the question). -22 Bytes thanks to @RossPresser ``` SELECT top 3969' 'z,IDENTITY(INT,0,1)i,63x INTO t FROM sys.messages WHILE @@ROWCOUNT>0UPDATE t SET z=1WHERE(SELECT SUM(1*z)FROM t x WHERE(t.i/x-i/x)/2=0and(t.i%x-i%x)/2=0)=1or i=1984and''=z SELECT string_agg(z,'')FROM t GROUP BY i/x ``` This will execute in Microsoft SQL Server 2017 or higher. [Try it online](https://dbfiddle.uk/markdown?rdbms=sqlserver_2019&fiddle=c2952fbb43b83592c96ce03106c5f541) on dbfiddle.uk; link is set to use markdown for output so you can see the whole snowflake. Before execute press ctrl-t for output to text instead of grid. This takes 60 seconds to execute on my computer. [Answer] # [Python 2](https://docs.python.org/2/), 125 bytes ``` s="%64c"%10 exec's*=63;s="".join(s[n][(s[n+3967:][:191]*3)[::64].strip()=="X":n!=2015]or"X"for n in range(4032));'*32 print s ``` [Try it online!](https://tio.run/##FcjdCsIgGIDh812FCWPTYPiXMYf3EYgHMazs4FPUg7p6WycvPG/@tlcC0Xu1eNRqxyNnQ/iEfarUarkdGy/vFGGuDrz79yxXfTXeGb5yTyVxxmjll9pKzDOxFt@wgZMVjF98KoceqSBAEVC5wzPMiklByDZRKYZcIjRUe/8B "Python 2 – Try It Online") This answer is by user "clock" based on hallvabo's solution, on the [Anarchy Golf version of this challenge](http://golf.shinh.org/p.rb?Square%20a%20snowflake) that I submitted. Note that output there is strict and is required to be exactly the picture of X's and spaces to STDOUT via a full program, with only an allowance for a trailing newline. The most interesting part of this answer, in my opinion, is the concise construction `(s[n+3967:][:191]*3)[::64]` after `s*=63` to get the nine neighbors of the cell counting itself in a flat newline-joined string representing the grid. To check if there's exactly one `X` among them, `.strip()` is called to get rid of whitespace on either side, and the result is checked to equal just `"X"`. It's interesting how simulating the steps on the string representation of the output directly (rather than an array of bits) not only saves on doing a conversion to characters later but also allows string-specific methods to be used in a golfy way. Another neat trick, borrowed from hallvabo, is `"%64c"%10` used to initialize `s` to 63 spaces followed by a newline for a line of the initial empty grid. Using the `%c` format, which converts an ASCII value to a character, is shorter than `" "*63+"\n"` or `"%64s"%"\n"`. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/) + my [LifeFind](https://github.com/AlephAlpha/LifeFind) package, 47 bytes ``` <<Life` Last@CA[{{1}},31,Rule->"B1/S01234568"]& ``` There isn't any living cell with 7 living neighbors in the first 31 steps, so I can golf the rule by 1 byte: `B1/S012345678` -> `B1/S01234568`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~38~~ 37 bytes ``` J³¹¦³¹XF³²«UMKAXF⁶³F⁶³«Jκλ›⁼№KMX¹⁼KKX ``` [Try it online!](https://tio.run/##PYwxC8IwEIXn5FccnS4QhxpwcZJSBKHQwcE11IjStFdj4yL97TGxrcPB4973vuauXUPahnDy3XAmVLkElYs9r92jHzG7ZDHfyAGqrYAPZ5UeCuo63V@xNqY9WItCwsyxH7hTAv4hLtiibiXYBLFZfXRGj8Zh@fTavrAgH59JWRE5s0ol5PEWJrVrIZJq4lMIYfO2Xw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` J³¹¦³¹X ``` Output the `X` in the centre of the square. ``` F³²« ``` Grow the snowflake 31 times. (The last loop is just used for its side-effect of replacing the `-`s with `X`s.) ``` UMKAX ``` Change all the `-`s to `X`s. ``` F⁶³F⁶³« ``` Iterate over the square. ``` Jκλ ``` Jump to each position in the square. ``` ›⁼№KMX¹⁼KKX ``` If the cell does not yet have an `X` but it has one neighbouring `X` then print a `-`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 31 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 1¸¸31F0δ.ø¬0*¸.øD2Fε0.øü3O}ø}Θ~ ``` 05AB1E and matrices are not a good combination.. :/ Outputs as a 63x63 matrix of 0s and 1s for spaces and crystals respectively. [Try it online.](https://tio.run/##yy9OTMpM/f/f8NCOQzuMDd0Mzm3RO7zj0BoDrUM7gAwXI7dzWw2AjMN7jP1rD@@oPTej7n@s16HdIY8a5kUoPGpY@P@/rm5evm5OYlUlAA) (The footer is to pretty-print it, feel free to remove it to see the actual result.) **Explanation:** ``` 1¸¸ # Start with a matrix containing 1: [[1]] 31F # Loop 31 times: 0δ.ø # Surround each row with leading and trailing 0 # i.e. [[1,1,1],[1,1,1],[1,1,1]] → [[0,1,1,1,0],[0,1,1,1,0],[0,1,1,1,0]] ¬ # Take the first row (without popping the matrix) # → [0,1,1,1,0] 0* # Multiply each value by 0 # → [0,0,0,0,0] ¸ # Wrap it into a list # → [[0,0,0,0,0]] .ø # And surround the matrix with that row of 0s # i.e. [[0,0,0,0,0],[0,1,1,1,0],[0,1,1,1,0],[0,1,1,1,0],[0,0,0,0,0]] D # Duplicate it 2F # Loop 2 times: ε # Map each row to: 0.ø # Surround the row with leading and trailing 0 # i.e. [0,1,1,1,0] → [0,0,1,1,1,0,0] ü3 # Create overlapping triplets # → [[0,0,1],[0,1,1],[1,1,1],[1,1,0],[1,0,0]] O # Sum each triplet # → [1,2,3,2,1] }ø # After the map: transpose/zip; swapping rows/columns # i.e. [[0,0,0,0,0],[1,2,3,2,1],[1,2,3,2,1],[1,2,3,2,1],[0,0,0,0,0]] # → [[0,1,1,1,0],[0,2,2,2,0],[0,3,3,3,0],[0,2,2,2,0],[0,1,1,1,0]] }Θ # After the inner loop: check for each whether it's 1 (1 if 1; 0 otherwise) # i.e. [[1,2,3,2,1],[2,4,6,4,2],[3,6,9,6,3],[2,4,6,4,2],[1,2,3,2,1]] # → [[1,0,0,0,1],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[1,0,0,0,1]] ~ # Take the bitwise-OR of the values at the same positions in the matrices # → [[1,0,0,0,1],[0,1,1,1,0],[0,1,1,1,0],[0,1,1,1,0],[1,0,0,0,1]] # (after the loop, the resulting matrix is output implicitly) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~41~~ 34 bytes ``` ı*Ɱ5I;$Ṗ+)FċⱮẹ1ịƲ; 32×1ıWÇṛ¡’ÆiḞŒṬ ``` [Try it online!](https://tio.run/##AVEArv9qZWxsef//xLEq4rGuNUk7JOG5lispRsSL4rGu4bq5MeG7i8ayOwozMsOXMcSxV8OH4bmbwqHigJnDhmnhuJ7FkuG5rP/CouG7i@KBvlggWf8 "Jelly – Try It Online") *-7 because to nobody's surprise there's two shorter ways to get \$32+32i\$ than `“ ‘Æị`, the symmetry of the neighborhood lets `+Ɲ` golf to `I`, we can trade two `¤`s and a `€` for `)` and `$`, `ẹ` exists, `œ|` is overkill, and selfing `ċⱮ` is outright superfluous* This is an absolute mess that could probably be outdone easily by someone with any clue as to how to mimic others' convolution-based approach. Outputs a two-dimensional list of ones and zeros, which are conveniently translated to the example's Xs and spaces by the testing footer provided. ``` ı*Ɱ5I;$Ṗ+)FċⱮẹ1ịƲ; Monadic helper link: grow a list of complex numbers ) For each number: ı*Ɱ5 raise the imaginary unit 1j to each power from 1 to 5, I;$ prepend the differences between its adjacent elements, Ṗ remove the extra 1j, + and add each to the number. F Flatten the resulting list of lists, ịƲ take the elements at indices ẹ1 which are indices of 1 in ċⱮ the list of how many times each element occurs, ; and append the original list. 32×1ıWÇṛ¡’ÆiḞŒṬ Niladic main link: generate the snowflake 32 Set the argument to 32, ×1ı then multiply it by 1+1j W and wrap it in a singleton list. Ç ¡ Grow that a number of times equal to ṛ ’ the argument minus 1. ÆiḞ Convert the complex numbers to pairs of integers, ŒṬ and interpret the pairs as coordinates of 1s in a 2D array. ``` [Answer] # [PHP](https://php.net/), 206 bytes ``` for($a[][]=1;++$n<32;){$b=$a;for($i=$n;$i>=-$n;$i--)for($j=$n;$j>=-$n;$j--){$a[$i][$j]=$a[$i][$j]&1;$c=0;for($k=2;--$k>-2;)for($l=2;--$l>-2;)if($k|$l)$c+=$b[$i+$k][$j+$l];1!=$c?:$a[$i][$j]=1;}}var_dump($a); ``` [Try it online!](https://tio.run/##TY9dS8MwFIbv@yuO5TAWSsTOu2XZ8KLCroQpgnRB0o/RpDUtrQpS@9trkg3mTT6e95znJF3VzZtdZ9dT2y9RpiIVPGZRhGZzv2JkxIyjZD5UHA1DteXU75QSj7XH@oK1xaP1oBIpasGvx0XMMOd3Z1fNV4xSrLfUDvGkOZPGE3WyJb/YEMwjjplVRFg7S4SNYPENx3y3/jclZtP0Lfv34uujs78gbC7zqg2P5miSh@d9coCXJ3hNDvvHN1gObf9ZFlCooWvkD1m7qpBBULvAdwf2RaXMK3sBOSwwI2MAcMkzmwM4P@hWGQduQ2cIpvkP "PHP – Try It Online") Well I'm getting used to horrible PHP answers :D don't blame the language, there are libs for matrixes.. displays an unordered array of 1 and 0, but with proper keys. change the first loop value (32) to generate any size snowflake.. 24 bytes could have been saved by removing `$a[$i][$j]=$a[$i][$j]&1;` if we only needed the truthy values. [Answer] # [Python 2](https://docs.python.org/2/), ~~146~~ 130 bytes Prints a 2d-list of booleans. ``` R=range(63) for i in R:m=[[i>0==(x*y-961)*0**m[y][x]*~-sum(sum(k[x+x%~x:x+2])for k in m[y+y%~y:y+2])for x in R]for y in R] print m ``` [Try it online!](https://tio.run/##RY3NCsIwEITveYq9lPyUSq0gGIgP0ZMQcvDgTyxJS62we@mrx6aiHpYZhtlvBprufWxSas14jreL2O8ku/YjePARWh2Mtf5YGyNQUXXYb6WqlQqWnEWn5ur5CiJfZ7HEYkaNZeNkBnQZsBRLKmbS9I1x5bps6WPZMPo4QUirsv@vZrBGnG8evY@Cw4kvq/DDdDK9AQ "Python 2 – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~144~~ ~~122~~ 118 bytes ``` m=matrix(!-2112:2112,65) for(k in 1:31){l=m;for(i in 67:4159)if(sum(l[i+-3:5%/%3+-1:1*65][-5])==1)m[i]=1} m[2:64,2:64] ``` [Try it online!](https://tio.run/##FchLCsMgEADQfU6RLgLaZCij0dIpnkRcZBMY6iRgW@iHnt3i5i1eqVWCLI/CL3UAg2ioMXmnu3Uv6tbz1iNZ1N8c5NqKW/kzzegumld1f4rKkUew5IbTYEdAwqN3KYJLOgTUEjkF/HUSDfl5aqRaK8C2Q14@7z8 "R – Try It Online") My first code golf attempt (except for secret ones that I never dared to post...), so nothing really clever going on, I'm afraid... *Edit 1: -4 bytes to remove useless variable definition* *Edit 2: thanks to Giuseppe: -18 bytes!* *Edit 3: thanks **again** to Giuseppe: -4 more bytes* [Answer] # [Java (JDK)](http://jdk.java.net/), 243 bytes ``` v->{int N=63,K=N*N,g[][]=new int[N][N],w[]=new int[K],i=31,x,c,y;for(g[i][i]=1;i-->0;){for(x=K;x-->0;w[x]=c==1?x+1:0)for(c=0,y=K;y-->0;)if(g[y%N][y/N]>0&(Math.abs(x%N-y%N)|Math.abs(x/N-y/N))<2)c++;for(int z:w)if(z-->0)g[z%N][z/N]=1;}return g;} ``` [Try it online!](https://tio.run/##ZVCxboMwFNzzFW9JZSfGIUHNEGqqLl2islTqghhcAtQpGGRMAqT59tQmqVqpki3r3d2793x7fuDOfvd5EWVdKQ17U9NWi4LO/Mk/LGtlokUlLZkUvGnghQsJpwlA3b4XIoFGc22eQyV2UBoOvWolZB7FwFXe4FEK8HzzeXgzOiKkjuIoDiBjl4MTnEwNIVt7ZMvCWUhySzKZHsEKw9gccvyDbGMimLckHUlI72eVQnkkYnPY0heOE7g@Plm0Y1u/G@tj1MUsYWz52M2XGxdbNmEu6Y2iv3aIzLj0UzOtX4Rx4N6hF64/KH9vUDcNHcPgr19kYZBFiPHDCifz@biD/cSwOVqjwVriPBqs3WDszGJnlepWScj988UfMzlwBR3LKK/rokeyLQp8JaybJQsh0w10PxkCvPaNTktatZrWJmRdSGQzuSaOnpTifUMbrVJeItuMaclrs00wzO7Xc2@Fqa5GFcLEJWsP3waeJ/aeL98 "Java (JDK) – Try It Online") ## Explanations Basically, the algorithm is to fill two grids by consecutive merges to keep the data from being changed at runtime. For each square, we check if there are neighbours set (using a second full loop instead of a smaller 1-square distance to avoid byte-costly constraints). If there's exactly one neighbour, the square is added to the writing (to-be-merged) grid. Then when all the computation is done, the writing-grid is merged to the main grid. When all the 31 loops are done, the resulting grid is returned. ``` v->{ int N=63, K=N*N, g[][]=new int[N][N], // the grid and return-value, we read from it w[]=new int[K], // the temp array to write in i=31, // the main iterator to expand the snowflakes x,c,y; // x the position being tested, c the count of neighbours, y the neighbour candidates for( g[i][i]=1; // Init the snowflake in its center i-->0; // Expand the snowflake 31 times ){ for( x=K; // init x to match all the positions x-->0; // For each position w[x]=c==1?x+1:0 // If the counter is exactly 1, // set x as a position that's not empty. // and store x+1 instead of 1 or x to ease the merge operation // and leave 0 as a default value ) for(c=0,y=K;y-->0;) // Reset the count and loop through all squares again if( g[y%N][y/N]>0 // if y is set &( Math.abs(x%N-y%N) // and if x and y are neighbours |Math.abs(x/N-y/N))<2 ) c++; // Then increase the neighbour-count. for(int z:w) // For each value to be merged if(z-->0) // which is +1'd and non default g[z%N][z/N]=1; // Then place it in the grid. } return g; // Return the grid } ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~207~~ ~~206~~ 192 bytes -1 -14 bytes thanks to ceilingcat! ``` #define F(x)for(x=64;--x; #define z M[r][c] M[65][65]={[32][32]=32},r,c,i=32,x;main(s){for(;--i;)F(r))F(c)z=s-!z?z:i)for(s=0,x=-9;x++;)s+=M[x/3-~r][x%3-~c]>i;F(r)puts(""))F(c))putchar(33-!z);} ``` [Try it online!](https://tio.run/##NY3BCsIwEETv/YpaERKaoDRa0BC99dYvCDmUtdUcrJIohJT66zFRPMzsLsO@AXoBCGF57gc99nmDHB7uBjlRbzmljmf/xOetNEqCylpZ71SSmCSrVJJg1UwMAaLjRhy/dXpEFk8JFTGa4wYZHA2wF5Yu/Mkf9LfIig1xgu65K0uObSla6daMvmOVW8UJ6qh5en68nhYVxQ@SLrh2BjEWYZjPIXwA "C (gcc) – Try It Online") To avoid having to use two tables (one for current iteration and one for the next), each new crystal is written using the current iteration number, instead of just using 1. This allows for ignoring any crystals from the current iteration when counting neighbours. A lot of the counting is done backwards for golfing reasons, including the iteration number, which is why we seed the table with 32 in the middle. The table is made too large so as to have padding, allowing us to count neighbours without having to care about edge-cases. A more elegant solution is bound to exist. This many loops is hardly ever a good sign. ``` #define F(x)for(x=64;--x; To make recurring loops more compact. Goes from 63 down to 1, to skip padding in table. M[65][65]={[32][32]=32}, Make padded table seeded with first crystal. r,c,i=32,x,y;main(s){ Misc variables; i holds iteration. for(;--i;)F(r))F(c) Loop through table for each iteration. s==!M[r][c]?M[r][c]=i:0) Update current cell according to neighbour count found in loop below. We only update if cell is empty (M[r][c] == 0) and if s == 1, combined as shown. for(s=0,x=r-2;x++<=r;) Go through 3x3 grid with current cell in center. for(y=c-2;y++<=c;) s+=M[x][y]>i; If a cell contains a crystal NOT from current gen, increase our neighbour count. F(r)puts(""))F(c)) Output loop putchar(33-!M[r][c]);} Make any non-zero cell a exclamation mark; space otherwise ``` [Answer] # [JavaScript (V8)](https://v8.dev/), 465 bytes ``` [w=1414812756,269488144,357569872,285212944,22304e3,286265616,353718608,69648,1414856704,269553680,357650768,17830160,1426150656,286327056,1364280656,0,w,1343229968,1162876240,83886352,1146377472,1414533392,1078284624,327680,1078219860,1414811664,1145062736,89392384,1141130324,1427395664,1073758277,5].map(e=>(Array(32).fill().map(l=>(c.push(1&e?"X":" "),e>>=1),c=[]),c.slice(1).reverse``.concat(c)),o=e=>console.log(e.join``)||e).map(o).reverse``.slice(1).map(o); ``` [Try it online!](https://tio.run/##TU/vSsNADH8V2Qdp4SyX5C7JKZ34FsIYrJSbbtR1tHND2LvPtAPxy5H8/ub2zbkZ22F3PD2d9batb6tLDQGCAkpkh5yCKoTgKNqeVNChRgRMhiGSD5kMYeTIwKYiAWWvjhMHdXNUZPFhioqRWP0UxdELGy1KHtibDhmi56lSmVC8TUAcUGfQu4utgRBTmnzAqMIYvFNSM0Q0LDCJBLtwao1ElGz0oqjBpM5Sp/YZgaRz6/RRYA6T2@pRiJ0mM5LOGAB5Mq/dJ5TirPRCEhVFXFxXX82xyPWyeBuG5qcgLKvtruuKciY6I9rq@D1@FvCYXxfvi@fFw6J0ebmsoXRtvVrbW43drs0FlNWQz3kY82ZTtf2hbU5FW5aury3f9rHvctX1H0Wu9v3usNmU12u@9/T/rX9pd@bldvsF "JavaScript (V8) – Try It Online") ]
[Question] [ Write a formula using only the digits `0-9`, `+`, `*`, `-`, `/`, `%` and `^` to output a 1000 *distinct* primes when given input (which can be used as a variable `n` in the formula) of numbers 1 to 1000. (Note that `/` will give the quotient as all arithmetic is integer arithmetic.) Solutions can use `(` and `)` freely and they will not be counted in the length. The shortest formula wins! The primes only need to be *some* 1000 primes not necessarily the first 1000. **EDIT** Edited for clarity based on suggestions by [Sisyphus](https://codegolf.stackexchange.com/users/48931/sisyphus) and [an earlier question on primality testing](https://codegolf.stackexchange.com/questions/170398/primality-testing-formula). Symbols are meant to work with integers in the "usual" way as follows. `n` : Represents a number from 1 to 1000 which is the "input" to the formula. It can be used any number of times in the formula and it will represent the same input. `0-9` : Sequences of digits (terminated by non `0-9` symbols or ) return the number represented by this decimal representation. Negation of an expression can be represented as `(-`{expression}`)` `+` : Returns the sum of two numbers `*` : Returns the product of two numbers `/` : Returns the integer quotient of two numbers `%` : Returns the remainder on division of the first number by the second number. This and `/` follow Euclidean division conventions. `-` : Returns the result of subtracting the second number from the first number. `^` : Returns the power of the first number by the second number. Anything to the power 0 is taken as 1 including 0! `()` : Brackets are used in pairs to encapsulate an expression that returns a number using the previous rules. [Answer] # Score ~~1164~~ ~~883~~ ~~835~~ ~~772~~ ~~601~~ ~~574~~ ~~554~~ 506 ``` 541^n*743^(n/2)*(-1)^(n/4)*17^(n/8)%2310+297999352693782350435634574256421873511169209139789986107407037031463672744907435566931682004950168827622126589004268258979810886896053712313147567393521260370898856430728936238509646240927399434529133911694916958518274696252190810912239170743768597920487389824644988723446125401158124982957878348425345764310640796665180984553241724855646631162669954988652785474199384658696484753453854147610893664426900411229033105555630617039087023847065224114331551958/67^(n%250)%67*2310 ``` [Try it online!](https://tio.run/##NZLNjtNAEITvPMVcVrINKP3/g8SbcAkigUgbJ8rmEiGePZRZYVlWz7hV/VXNXB/3X5dVn8fb5TzeHufrY5zO18vtPk5v19vpfPhwHF/H6/78/cd@rF/Gt6cbL8u6pOmyTOtuJ/Myfeb5fWHzwvle1vwiyvRROrtbXaI1S9TJ1EPN08TDhCvVmTlaqFk7q7uCKY2SFC9baKSkWWNT3QNKHCVE1k6oSjJEWMKrsSn4hyq7mKqiOsg1GTTQSo/UDQftm3x1FTCUUqo1RMupw0KMWtDZBlQBmPbGaI2PlzNmWnQIhJowqFkELbkhZpRjvJDBGwaIBeCrUtQsWNyI2YsFm9KelaVWiGNLBSxMAfMdEZhDXeauYpxiBfcWoUARxNC@yYZLllsaI@cypAAw6OWmBz8G1wh0swcOnAMyYuA2KUY5nlAKoCucJCECS4IoRrKhxZ1hebeLfyf7Ik7zC@rtdJ@4I@t9ej2s0@/jtM7jeLmNdZzWcduvPw8TfxpMxPM4Hf9fqGnrm//M8/Mv "Python 3 – Try It Online") (OP hasn’t answered my [question](https://codegolf.stackexchange.com/questions/212254/shortest-arithmetic-formula-to-output-1000-primes/212266#comment499623_212254) about the behavior of `/` and `%` on negative numbers, so this answer works under the floored or Euclidean [conventions](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/divmodnote-letter.pdf) where `(-1) % 2310 = 2309`.) [Answer] # Score ~~424~~ 193 ``` (30*n+(1-(1/(2^(n*30+16)%(n*30+17))))*((1-(1/(2^(n*30+22)%(n*30+23))))*((1-(1/(2^(n*30+28)%(n*30+29))))*((1-(1/(2^(n*30+12)%(n*30+13))))*((1-(1/(2^(n*30+6)%(n*30+7))))*((1-(1/(2^(n*30+40)%(n*30+41))))*((1-(1/(2^(n*30+18)%(n*30+19))))*(882)-22)+34)-6)-16)+6)+6)+17)+(1/(1+(n-475)^2))*10 ``` This code searches the first Fermat pseudoprime of the form `n*30+d`, with offset d from `{17,23,29,13,7,11,19,1}`. The 4 cases where this fails (nothing found or pseudoprime found that is not a prime) are fixed a posteriori. The order in which the offsets are testet was handcrafted as to minimize the number of pseudoprimes. The following building blocks where used to yield boolean values: `1/t` yields the truth value of `t==1` (when we know that `t` is positive), `1/(1+(n-t)^2)` yields the truth value of `n==t`. `b1*t1+(1-b1)*( b2*t2+(1-b2)*( b3*t3+(1-b3)*(...)))` mimics the code ``` if b1: t1 else if b2: t2 else if b3: t3 ... ``` **Edit**: I could't resist to optimize. Key tricks: * the if-else now returns only the offset, the final result is call afterwards. * xnors latest if-else gadget vastly reduced code size * the resulting nested expression had adjacend summands that could be contracted * no Fermat test for the last index, as on failure it must be corrected anyway * grid offsets reduced the number of faulty cases to 1 [Verification program](https://tio.run/##dZHBboMwEETvfMVeqqzt0ngNTWil/EkvpIHWEl4s4xxQlG@nViBcKiwffHgzO7P2Y/ztuZja0DsYRudHsM73IYIdfLCuydpTV7vzpQb@/Jqw0JIVUo6036ORElkWWtFBvCyvo0hH4j/EmCdiii2kWpGPDYRWF9pyWaNsJSn1kyhpa8yahJYkVWVEnjqoohT5QeSpsZpvaqwealLIeXl8F1KaJCGdTaEZrl2EE9xaZAFtH4DBMoSafxqkVyCtSdyztGmO2O5uXcM4i8QdLnaIlr8j8NWdmzC87US2oHXX4fJB6Gdj/zCetWL6Aw) [Generator program](https://tio.run/##nVZbb6NGFH7nV0ynijQD4wRMoiiWeOl20@7Ldl/60jSxsBkSNvZAAO@SWP7t6ZkLMICtbmtFynDmO/c5l@K1fspF@P6ebYu8rFH1WjlpmW/hsC1ekaFmVVFmW86Q4E2tjo6z2uTr5yp74yhCoe/kaVrxuoKPu@CazUM2v2FByK7ZZcCCG3bjB/fOKq4keu44v3785c/fott4U3En4SlK@Gr3SNyGLhwEvyxFCqG/5A@UiloCHIV/5IKXcc2JYXjc5Kt4g9b5TtS8rBSt/Yju/HsXLLRwRcV3Sa4c0VibIF24t9FpnG00TJ2i4W1rSvKlFzeitRxpXiKBMoHKWDxyAoHx/YD2Tsr7r/LeBLO/UTaCYV3QXeF9dQbXEDMZX9clxSygZ0UUBUN@AzK5JAWdXh@x/TwuCi4SgE/QHLJ3XIZOJ/7SR3WB4fEwVMDfWecEPcps56LVTgQr6BTepvju61no33tRMEGsSh4/O6ctNpbeQmKNicI9YZ9KvmWQbwwy74A3a17UWS70E@g/I9shTz8m9YgLVXugh0Dit7tNbDJS8npXCmSI5yUvNvGaE3yBGb64wLSnPADFdbEpivUTXz@3sphgvCn4GhLJaqja6HMuuFGwzhNZh1P9Rn2129Rwz7/FGyKxtC3KVuJPkQb1sdRxTLGyQYWKJygXStUC7eW/A6YTuIj24sA6udG@PQFRq4j2@r/NDZZIl45lUtJ7IG@ymgQmPOmn6i9e5qQZhRmT4IIE3r45UIod52eU5LwSNfqel8@qJJvIbwX8IfhRfskMvI5JgdGEfUyZz8CAET1QdH9Cn5@ghyfo4oR8SQ8kXto5viRiFlIAXB4R2N6FUmh/Kd02RtvKFHlqsyKHx8nasuAYeT41WN319k7Y2qsryWqyfMvLbVyTroiZbqZMNsdR5rQUSOBeXh4eiHD3Hd/B22vOWXCgZ8ev5Ivp42Q0hxAkNlduMhwG0HCRqn1Mp8BQA30AhhIo8hrNZ1bDOMZ01TNd/TCTZdK1bZIJWiYS3a1V12/HquwCGKvjGxzNWLqbBf08S9Q849@gC/OEtIgFQKz5sgLmaWISnZMOJbXJaprtVwfqkn0NcX6bJbKyWoi0IhlVX@jDMNRggPbN0ZtBd5zZ7ZJ4QCGd0x@7Ft36q4LySSS8AT3@sBuaOKgZzhrpdd/irT0lmnfn70/QBUkhoaOhSqeTvdus7EkLja6JIn@INhZ5YJKHvbZ0U1kM0EzpAxSkl2J3Xxyw898G@3Q8vkS9Xc1wHGrvXv7dOyVn4OEL/V8Ovcway6WjQTOvQkucpPn3WCQfyjgFS8mwFWBPDwFQeXl9BSopdQMfDyBIQsQZ3HuBbPZS@DbORLeDdjupY20Wo9jIJWNEultc@fcM4fPzczxgtd4XZtZrG4DaFQgg7ZG2D1XOdFV54@r2TgXF6XdtbAQsELbJg1VBa0w@PMWlXJsnGwuBerMLkKpvW8nfYsPFY/0E5sOB2ALpCKjXlRDJVgOGL1pBr7edpyc2Gi2iA2oiiMnSV5uqMjohL35odS/afWmkxVSxbNGnFm9tHcK8LPMS4iBX3QHAAQHLpYi3fLmMIrxcyle3XGItRj9B5/39Hw) [Answer] # Score ~~163~~,162 ``` 1%(4^(n*15+701)%(n*30+1403))*(1%(2^(n*30+28)%(n*30+29))*(1%(4^(n*15+6)%(n*30+13))*(1%(4^(n*15+9)%(n*30+19))*(1%(4^(n*15+5)%(n*30+11))*(1%(2^(n*30+6)%(n*30+7))*(1%(2^(n*30)%(n*30+1))*(16)-6)-4)-8)+6)-16)-1374)+n*30+1403 ``` [Verification](https://tio.run/##XZHdisIwEIXv@xRDQDrTqjS2/oJvsM8gVDfVQJqGNC4r4rN301azKOQiM2fON5OJublLo/Ousk0N7a02N5C1aawD2RoraxGJX2P3jLGOT7A4oE74Ml1nnCb@mmcpL7KcKEGvLg5jarF5iYvtU3oZV8GWfyjboHx6lkHhH40Cbf0uBMOQXtHMn4JmG/KOWR/zfF1QGubv/PPmrbPSIEVRtRc/pUKmyvr4XYLesbTfwdwKo8qTwPgQT@MkicnXWtFelYM93CvUBFVjQYPUYEt9FsinwDO/qkfkV6kdVvFdCY2jiR7wLVsn9cmBvtZHYdt57JFjaakUPn8AzQg2A3j0@jpPOruLb90j3wZkyKaM0X9MQxzYfTG9RmJfA2cH9xH4YNT9AQ "Python 3 – Try It Online"), [generation code (takes around 20 seconds to run)](https://tio.run/##tRldj@I48p1fEYFaScB0J9DTNK1lH@5u57Q67d5IdyetxLAoIYZ2d4izsemBRfz2uSrbSZwA83HS8UAc16fL5apyJT/IZ56NP39eF3zrrHfZSnKeCodtc15Ip6DJbkU7CshzWkSSFyVsu0s1gElaNKhWfBuzLJKMZ4I4ecGBiewYoGRbw1ActvmhpGEiLwDiRMBFLNX4AtZmlRAnYW9M8EKUHMVBdDoJXTtrWmwj6eUk8p86DvwKKndF5uT8kxeRfBiS3J/NQoN8hs0ucMBfJARVGmq1vNyvQEbAv4sdtQW@j1JBO51ffnNmzsNDRxYHzU3Ri5l@qJnojbNEzPSjQ/crmksbFxgcTxZm/b6GneAOy5x5SCYkDEk4JiEMpmQ0JqPpotZfc5rzBRIzRciQsIiyDfXCIAgHv/zm4/KrJY6DPhtw/1TxQKK4JhqRUWBZqNZvzkn8dTnGzFoKiX0nyhLAzbhE/Erfk96pDZVaLeFxwma/8ozWOwYShINTTw4AQTK/GQeE392NA3tHji9KnxdLH4IaKXW8lwHzr0nW6/Ji8n@WbdnPSF9F2XLF32gBwoWR2nNitlHmEtsoTRtizkxurA143suQOT84oYN6wPBHBxQI8A0hSn5cKyl8owFLaJR6RjRfrwWV6IFXPM4os41YxrIN4AG611iwPjifnllKS3a1E8VUSCCqGFQAjqZFMze8Ufn@GZMSalkBjj0YoomCv4YwZ9hyM/8MHyyZ0syTPhgSB6jvBbbWUuRFoFoOSLCCSG0ypKwXrld3CwjgBh5n82Dh28c6kzBJKmV84zc8TelKen32XTvXi9PoGXFsQ2jK@cuCMPjz24786C@@2dOj7OCht89fF43DZkS8LhaK@NXmXjqiWdLou9dkob3A4azV48JgMAXDM3sONMvCA/Q/aX9mDTh0JCDDsNqqZ7p69Xh5uoU5NH4zwnPLwcGQGCatyDQi3L9lQuxiJBUtl2xkpHJS3O7yJJLUs7fanE5DgE4lMFuCylrXlEcJxKKIxCoMkj5Zg9eK55niTZ4pgmeuaxSAuBVzQXFFB3ErZMJ3EtSMpDyY9cFSNNGTeQKu67kD/TJwfcct8eIq0tZZmcSAH5CoxDECn8zBcJ2a04eCbwoqxJMT3AY3LqFZMnM/Fq7W4w35aC4w0vzU8QW73OKfZ8ctjKNxrcZbAJhopL7HhpF/d@fF8LC3CzB@dN6auyKDC/wtGhkMJVAFt@HluCWDs2lcxVtwKWq1DLN2P@7DeD76h3PU9jnV5rm5Ddc3N@4NeqpZkFqP3zKZNtYAVl69HhhNIYlf2w0j09jerTxA@1DDv9uk7xUKTVxzaKAO3e4kXXJwWkHetP8Zr0vBCsZR74PxKLjso8AxwXirOelCFdwN06t8Bk8TcrdeO5948Srw/G0PDpS4WyhpUyeScDQiE6RzjB06VFyuhG0BzTNtQ@oAgL/lLKN76aUNJzKBonW489soz8GgAGh70NuTyQ/EJW4dT1ReTMG0UNQ2SuROp2fZdT4cTYkzhEjqhA8hjCCyOuEY/6YACO8REE4hG3V6lsm9x37/we97k35/hCGuhyL3QSMXT2ANvVKdfXgZVsFH1@EVzvjLOBXe/dfxKtx334Zb4T808B@@hF/RTL6PpvSEMhXuA7IPyX5E9mOyvyf7d2T/QPaTb2FTlw9yl6eq3N8PuNaKKPf8k@Xe/IqEBbmScn3Y82@S3dPCr63g60zqM1JfriAtLjdcSpqBQ9YvLdiyoBBfVF46n2xcwBr8zKXrIp@jdVsABCyaCEAbcQk2DqYaYQ7Q0NLnLC8m8HM0rD0WbYazGT6g0mkyuUJ9@aJWl2zqQmbdCdUlDu4LAyC2LoffqOalNT91rjKoCVtz36s1s9S9IkXt305QU86pupds96r6afYSVF1EoZLJJK5uhQHc63vl3ve537yd@GWpR/d5yguKKQty0gxbBmc1E9eF6vBSLcpWABsFOsNv9@rygs0Zb7tLiRcOPLaCnanqWKZpfRJCPB71@6g3vPrtLLndlykSHqVC@qFxY1Pf6BcOb57vtHKZ7vCAGcqR3hNG2IqMA5@YpoEpiEvVvpjz8DJkbwiJG/lw06zCSkU3zRnUls@fFl9NfzGJOaQrvlYNlovR7dTpIfBdp/cHWg/MmTIhPbvXBW4jiNrx3quqKTu9rLReL9a1gs6JK9TjAqmJ3a@6tFLjLCAxVoul/6yIrmXW7vH1dHf84@SaeImeHzg/QFyzMoCKhUH9jlrE1rsOxBmBahktDIBwCtNzTPoq3avkP8Y/NVoABiI48zG8PwDGPTyxHLiH8QSLhgniTJw2F82kyUlj1bXGMJyaWkNjTr4FMbQR3znXtdeENZbNbtJQbnIJsaXbZcTx1xDDybWVTCaqsKqRwsewrMGmoYEHgI2X2959CCiehyuFA@Z404kZTMqZybgcICE65XiqaKYlhuaNo3ubSM08jptElaCJQVCKq5mwpMFFaZpHRWORVKppceXMY4tC2aXWTY/CSTUq58KKbnJRUkUymZbrqSgemhSl8tdJOjosXOsz1BVIKyU9WgEOQVmz3ntoFfMqWK1FGa6q6TlbYDiARJa1i3wrQHovJLD6DZCGoBQIzm@Pei38bL6IGBQz/5I8/1linx@CEtyGUp6amqgJMi1qjKKd8pbGd9iVpBJEVH05l4A8sGCc8tWrYH9iuTSG8KOsPayOb6i8Gqw9gqkHFSzGvjOEu8cIcUc482hiTTgd67NwDwTvYPw49Tt53eexb4co21bPVb2yEtknLl7xzi@CnThShd2o0/nbT3/5z991JaeyeELj3cbr7@uyTmE8tbpygKCzPpRAbH3w1gbffEpALY5rj/lfqGKqCgbx/FOjFZOrrzZgTg/oIf@3vneYyduC5mkEFUL3rku6d3ddv575HWb6/a6K@AmnIpPququvALNAfyH5WfzK5T8z6u1b/LvhzXF/6poPKYD0Xjf0q20m2sQEDWndzDer5AxnGDb6TnDL9ua15HXXOyKTfp@dfvey/rEiv7tjp8HRq5jgu3/TQAG4Bp98v2vZuvyABPXGgrzSwwz2w@zXGlsDHwTdJfwDWn9ctkArC4hdih2Y7nLZNd9p6NsysTvUVSxILraoYW8NzVlPC38JwzIebNxaSXLqVng0FdeojslQc7fQ6xb7Mo6wy3ZxyxK9Wx1b0cRcKFSPExJY61ZBPy2FLHTnGkWDEl/Usk2g9Dn1veXSH7SpG4pXZteD2o9hF4jF1u6Om21JOrZ7aXq919tow1at/TVHB9W76gm19EEAx8g@VoMhTAxhBtXJTV@vlx/eV2zPju7yE4OZnVzqOIsRSJOtIGJJmvz1OSowrp0daq8l21fv7buKzcUnhgkE5LIuxQ8HeLNwXTXkpkqta/uG/0ZkNTNmqzp4UbMUj6seavklhDcSTilwVWWOj5nJHTzdqbzD1ZeWjXyGmpS4O9GK0DCLXMvQrhiC237@/F8 "Python 3 – Try It Online") I would have posted this as a comment, except I only have 1 reputation This answer is based on [Max Kubierschky's solution](https://codegolf.stackexchange.com/a/212389/95116), with many of [xnor's improvements](https://codegolf.stackexchange.com/a/213440/95116) (specifically everything in his generation program with the addition of his trick to shorten expressions within powers). The main optimization is based on [Max Kubierschky's comment](https://codegolf.stackexchange.com/questions/212254/shortest-arithmetic-formula-to-output-1000-primes#comment499937_212389), and I found offsets `(1403, 29, 13, 19, 11, 7, 1, 17)` which are mostly small (with the exception of 1403) and have no faulty cases (these are just the previous offsets + 30). ## Explanation This method works by generating primes of the form `30*n+(30*k+o)` where `30*k+o` is the offset composed of o, the base offset from the set `{1,7,11,13,17,19,23,29}` and k, the grid offset in the range -1 to infinity. The grids are the sets of integers n from 1 to 1000 for which `30*(k+n)+o` satisfies the Fermat test for base 2. The prime grids are the sets of integers n from 1 to 1000 for which `30*n+(30*k+o)` is prime. The grid offsets were generated by first considering only prime grids (ignoring possible faulty cases) in order to find a set of grid offsets to cover the numbers from 1 to 1000, (in this case they were found by setting all except one of the grid offsets to 0, and varying the remaining grid offsets in the range from -1 to 66) After finding grid offsets that cover the set, the code runs through all the permutations of offsets to find an order of offsets that covers up all the faulty cases (for the offsets used in the current formula, there are 81 that work), and then generating the formula using each to find which one turns out smallest [Answer] # Score 2341 This outputs all primes between \$31\$ and \$8017\$ (included). ``` (113467395935668970410160492737179506361846013862444084170197806945186405092696909126164158205176795679626257477170011681151081828693721528545308301463032313852735898720278373462178435545407324698821351304548663895918208828677426209417450978147368548225197577994423342074325769235860896833550745001703798952436205556087566508085462913775782980107289038262897153290911775461849717826677653709482106939563942394004153958440037041024098156603769869491411749714891362691603370984320936124882165280605174558859749487518953604842331779664328074931195219441658740089199947350409773050270253672458490842517716227535564556430387611590820439097600165832489226127768727315594781312368235772273799332206758908020271761747844563774441691210056862686595288936465304647859214996600265632129456351742413141396515373657806301978324762068082957610010981667490015017872109960968210719664738068557705903476757448731528153247317383397296951323720188125875523771873472067739298722926939700395850510069970848932566438053043914675253394668929358649440219868955587507427792258737478621439222869420782804120723724037942099140240986671113771843292946536125599661698395893047644516938416344212452574005345276922734768543821803294119263624051859444984143612848763146503016281898460776934493046854691490177334701465551154370051389269555217280444180285443508781807182786653180547028418689044382239111057385640034581765695611964566960423155654254631533264137376719604736646235721281638954806708051896372829794828522441565514326091912749474754904829505420000828614379978905433227551134966163328596138390836978449350464146519410700211096728982452219157828903470370081269726761212190236152174162025868830122533316205222356743692764196532590297434905214324476315471045728469350713970766245611550719074621408922145054478879292926089731205325210583591485438579344315785755440427094785080423582680705622279978441230497635622038519006130677863238128994042483893669828145180491933002965357145427263569009059259792273674006429955369804616413369843446578638589803530417606529429534136839003463278401805099943786536199970623822629008628461486362852575470843011844101058219237624888472496428195993935156341808156330726437453034634118080653972710684434727685175583816599255076497400463324245086662776394809313991656593421958024921754700582702681454016857120679602782/(208^(n-1))%208)*2-389+n*8 ``` [Try it online!](https://tio.run/##JZbZjlNHEIbveQpfEMkzI5LauhYR8iwgAlEi5Ikgyg3i2SdfOSBLPme6q6v@rf3Xh38/fPv49c@//3lze/7908vny7vL7fLut5erqkeWzxk/mT0loaIpMVZeWnMkPbUjRb3TIkI6tESnWnLiaGfIkbGcHBm11Aw9bXK0kgJ80tJORVFQRDVb9ai0tnWOl@mxPnFc2kUjXdyc4w49nJ4uE6v2olXT6vDD4pByi5xuUz/qwqvO9GYWCktv8argaBk6Dnqs1ihPzmqzwwinaibC3MOkwukyxzg0pSfbOUl2p9C411Dbwil4zmFFAdmRFuqljXpRr21aVMp6xJvDwVSP20KjLIgFk1csTNrL40V7zACY0JA@dDMh8HB4bvDm5GXFQqaVI3lmbLAfDWputWiOB@WBOt@KgMTYMGexACUASy4jcU73GXYF/SsTOWz3QkB7k8nGZuZxVaZV0GF3F21wxoAWnAitVDm0W4lRoSxodZAGsEJzmtUBvIz9wGdXwjkLTMLBohJMqQuFPYZmDCwgulzP4YxWV4MpuKiy1eKMu5lkoQgwX0mgLwZCEAFuUL2tIkAVOYlW@RxG6AaHAGiJZPEZ0xgGFbFkn6nN7l9sLDiWz@QBfZRyVuR@FzudFswndNsgE07RJQQWGVz0oBEG4N2koB2@lS6e5dTowxwCAE4VZBKg7yv71QZLlFXuU4aJELNhCtFuNaA/h8dSNkQtANjV1hS2nmMPAkEoB3YFEfHcYIqUl8uWndtRCqfCFNJam9usxtFACBQ3b1A0J0E8REAID77QYjh2m61R1yKYCi3yZTuM9QRvh/L/yxMwVPXeLTrimMUdcuEUKGCnt9WhpUpY44WTJulYEKWeDQnIc76tD20nXrdiJG1CAR8rQ6N0IkehEsqROi1yBlNXQh@WhDGMh7g3txDWcMAeurVQCHwhUjxfmzZMjjQD11CT@ABUXhE0OyqSQmtsI3QwPDVhtUkjnO88HGpwsi6ErKZR3AsEciAU6cMNzkCoh6pYYHBEkpSC4VB6HgxD4KECN2ITzSEP3b@jPlS7@gcaZLbBFigJenf2QfGGEmvDg6QkmckGRgF39Kf4YD0Oh4dxYzVLsyb822BkGY4qmmZyX7eevQruJPEMtAkWOLU9Zx0263o6BC8yAW1jH8ac3KTr5Q4h6eZf30W@oUXCA2ZZ4haG0BEsrQstnGNgJNib@LbC9H1FFSbGUZyKBAIk8Ae2YdCgPRbsgBHLNNgrqU8DkEp7pWuGStSxUG90c2TtpcGlhZw0FgNU3Uh8/2/K4z3O5RAMSx5xecRdcadWNb4jHdDBKVhDNpo28mMvCRIGHA5hZ3cwocBQGeHm@5LUAys8yeWEa5uscRBpMpT90b7BhCVgd69RNioZB6479CHU4QvwqEURRh@AqLsrcm2SYYNSQYqt90vX9zswxeYWgtm7U3wDAAEKdwBmJe9ZmEstNNESbcsKWTbbnX1r2NkYQXzImZsNInNBBpn1Xq9PV/icxW2@Y8tiB8GkQu6N0yQVYgpG4zompIhXMnbNtFcYUzIYp@2dv13ga/5CixuBsJoU3bRb9yvogxW3xYAApJJbO3@sUMEROhLOsTnh1lx6yIB7EDNAID0dDMzPGb23vG3i2FzImZvypZupOA4k7PbLlV8Ot8fH6@2N3h4eftqnh0e7vYGs29PtsW8vn5@/XvnxdNHbW35E/coXPLXfn54eLt9fXS4fn2/fnr98@vnL8x/X9x@ur7/ffjyw/vX3z9fbw4/3D29f/Xj5Dw "JavaScript (Node.js) – Try It Online") (Node.js) ### How? We compute: $$a(n)=d(n)\times 2-389+8n$$ with \$0\le d(n)<208\$. The values of \$d(n)\$ are extracted from a large integer, using base \$208\$. Below is a graphical representation of \$d(n)\$. The minimum is reached at \$n=399\$, for which we directly have \$a(399)=8\times 399-389=2803\$. [![d(n)](https://i.stack.imgur.com/caHuo.png)](https://i.stack.imgur.com/caHuo.png) [Answer] # Score ~~1778~~ ~~1319~~ 1164 -459 inspired by [Neil](https://codegolf.stackexchange.com/users/17602/neil)'s suggestions! ``` (28389416454731914904646197269110195258968918334324648337536406183122452341375087148095278619811035121264892162819521481008101705277372014120459537607320900170581458493476732106029764703970199356551116634482447603151892501883985471668745077729919867085592433543835805593713705073935219732297479335704578859520285745463599513991638068362975801056573234819165907183812641577379596655404026370719245188577913240916435487946831490476753322022399310328082542064590520714793222945825868990061383486920959013849054510725156607978917228480666383141633344797723352686825873369593489365635288158535711600587674466307031798274562517630853907709405080966507256977400682764885616947585079339593770144096628672186322100621135207302538190833576961188067354198288862669754543325834368496102584439249310678425485967421525911011440604945657742285226023738594503000443799738987162853276495354222398842865644351430245057910519732921873667017428523263018326208740011108682459267993023371456176948637898475810086660149605871207027333515638814123020249096374464098648830557815605475878366999652657721355174060931879798441836550660645385542381428064142926776728816247052/(14^(n-1))%14+17*n)*6-1 ``` [Verification program](https://tio.run/##LZTNbhtHEITveoq9BCaVOO6/6ekO4DfJRY6lhIC4Iij5IBh@duUb2QeC3J3u6uqqGl5eX/572v3t4fp03p5fz5fX7XS@PF1fttPz5Xo63988fH68O3/5erftf/39drDy6tCMEdO1NVoiI7WnZauK9rBRndVa7uHGKT/m8AxJ3qlZDPNQ3klNjRJaZgFR9PtQU6OnTdNqwVGiInx0CpXTp4mGmsTo4TNluknL@3FpjIr2mMlblRTrmTHFe8KtfeQYqprpEWVBnbgOZdwQrfIuFuO4ZgyZc1o3xHJKjdEW7iO8fJTw6JMlhDIH15DAjWkxm6oJu1kFQxOrAVqkj@6hDmJ6SZYn5UCpwIpmZ1HORstEqFoy6Fj79uiEd0iIJSOnQgXS4M5WNBbaAmo1O8B9dwUFhsNIzBjpSGslZSNMcK@REpxF1mCNatiGa@iYyoZR2ahKHU/ADebJtKEjEbwn/k6zwr1EyzWSpTAcQERDAEvgwJzuCQyA7TnQwKp01EAibBAsg2gEIIJLOrsMsZJJk1fUocaUDnQmKciwWCRDAqbUEpUaqdmBlBwi/hpHj0asBsM900r2JEZpqr5Wd7GBxi213MpORU8hNSMwHJKVlsxhcVxnEcKcKJFKY0U4FixVc1YgKk6zhinpf78Ga3hKICzWckAGzEijT6eUbLmIgDKb2FRzESA6fO1DqDFpuVZAF6JRNzRgTN/AcRnvYeOKIG8STmUCA5x0kGK@jKuFQCRdlg34bckoILiL3JFE3cZjx8hayq0bhpOI1rk84XpNMczzZbnjGTeOdjg0qvqyDHlrye9chompNC6oSbCzu5MMsLuhN2YuOdCLhGJxBCxJNOFZYUQSNsYNtuCZr0WXXKyspMW6958@HTRubw/7Rz0ef9P4XeftfrzNj/p2vX/@9viyfd6@Pxz24/bwdN327bRv17v93/uD/rGxnB5/3PB/tr8cHj58f7zfDz@bjj@2r6fnl9P@z8u2fzt/ub8@//nhePOr9O7x8fDrb/Bw@Ql8eQf@2Xt8@x8), [Generator program](https://tio.run/##VY7BTsQwDETv@Qofm3bRNiD1gLQnPgPtIdu6EKlxgp1I9OtLmt0iuNmemTeOa/oM9LJtMwcPY1gWHJMLJOB8DJzgLWRKyKrqsvq4HoqTyM6jUvKVLaPABd5N/9zSk4E5MBA4Arb0gY05gel7o69qwhkoNqJfFYCbD8jjAMCYMhP0ZcFF8N9x6PZkN2ilJifJ0ngvrbzzeaitsrc@PrqqmxUsFm@/m9@I7oyi7G/IRZHsm93Utg5amCrCncpQKFhcyDbhn6xW5V9KNXPMd5jeth8) This only considers primes of the form \$6k-1\$, and yields the lowest such prime larger or equal then \$102n-1\$. --- # Score ~~1635~~ ~~1604~~ 1572 The rules don't explicitly forbid this, but it I'm not sure if this is intended. Similar to the above, but finds the next prime after \$\lfloor n^{1007 \over 621} \rfloor\$. ``` 16921707110807543794883034080662369959145330548686331531608873466161289588508225504395036067059456808254955842748011935275567235182962066696532824341658478313282515740212407513889626921371569995949618530076057857935444678903541507451833650971208966857022879588416744784446458319742198436165114149099979782639487537376816458053319371322652945071076875723112404278546530735706274859341438493065587724231536852995916148117098900150719957460662049351379626720184420298531075385276847667099516667910747707987556366430526973567431116704034575028503641091403375164564764095445312182120994347975065105984011801750777939791614004132127064169527985645152866679765959804131578103751126570294714529430395223496169502308685883689716858687150949295161789378929626842080159238203320971831181073359220269422355146095712138282898528757872049694061460608989183240128781928642651093781146703726149529559745625017336481225823115996890606949461379145867395915059579445847541041812545106491388887871854979774599921555206338249335536406513747513391059876604297546812682955845160908578873034957552441194311592692169821206761814295401029352512438888121121058993809853128792382425425507315758921975340564810424303160455069096558687026616771028629060280318800048984850429104924036193703515227460262324051154267318767728375732829596082819890956884172016068499243733410402170378286724312471419805200183238726658173781500929626384453831442841099333236763065428542599128063204447946777048377374390957947246087390567878387147899066382490069914521762754275957918350785590249135/35^(n-1)%35+n^(1007*(621^-1))/1+1 ``` [Verification program](https://tio.run/##LZXZTlxHEIbveYpzE3kGJ6HWru5IfpPc4BiSkWBAA75Alp@dfHWw2M5pqmv5l5rnt9f/ns7@fn95etxe3h6f37bT4/PT5XU7vTxfTo93V/dfHm4fv3673c5//f2uY5mWlKpMqQyvFXO6ePA@hvlYK5dGukvGHHO4a7oOmbM8xtChNlfOmTLNMiV8pfiQUZIrckzOM1bmDKuYoro8rTJHmadOW8OoNNZIt2nhoYPYmq79npoVYmpBe@pzEt49e2nSG83FGjrTRWpI1swif0SMmkt40pQK6riPlFVqQopBmJjN6s4pWEHBvhRJ3VVhumY406VqaCyhVK2aNhyAKr28xtSOF7BhpqJdG2nMDJw0QxQTanfO5DODAaWcwqOByMWk4TOWywCdKgtrbOnNdtCHxlTIWQwiPYZyXDGaF@EacFSjUSZK8ya2wIHS6aSggagBC1xS8K3Ff6Lges1G38cIOAVMegIAOgUHCajPSrHZLIYK5Is72DPrIGPIAl7qGNyB5lpQBjTJFArlM6AYmjmoggtg60lEAoDUmB68F/3RLCk1be7d1UiGnh0G5VOlayqIQtSKQoL8QZhcNW/OSSLmgibhENTgth/BHaxQhfXcigqcn1YZgEA@SC7zaQxlrQf4VqqVO@dgOFZQIFMBGrgZk2C@aNea0lkNPlEyOgQjwA9ZoBkn0PhioLAGoysjH1D1MqJpHR@grhyWIIQkYRjXzNZJrsUQJCT3itHkMvQc5S2GBFqkDfLQiqrBiasJgAC62hgYktHRWQuVGijWNDNxlzMCgmEqKjZPjhL47WtnDJkgUSgMJA1MtrsV9GQJRmmnowrKkywCA8fe7u7DsXYVjMKESpIEBgjD4ony97aAkG/JuZZP2TXazmsSggl6aVRzTgC2Q70h2cDQUxNOG0HIwIPtE/iFJOgvXAbU1pDZJG5OQWXQgbl6HhIsWMHFEMEqQGrW9jHWGueoi@LAqwCA@yaCq145wA2rBpPQsdhgbIj2GMzgVlJifm8GpFcnHNMF5mWqlim3cBWGRRKOWAbbDKpRQop86BDTYyCEh2lnWwxqCAbDXgWcNShrgRLUoTaWE4LATUznRS52rOxqoCytohAQg/1JQWWTLTAZO@cCbi0jOmXrkLd2GdEcoE/EKNbqyZsbz@vrw/kPPf7m@fnMs7JRrw/D9Pqa0@PNjX7W98vdy/eH1@3L9uP@cD5u90@X7bydztvl9vzv3UF/37ilx59XfNScXw/3n3483J0PH5eOP7dvp5fX0/mf1@38/fHr3eXlz0/Hq1@htw8Ph1@fUId@fz5@ZH/es38kOL7/Dw "Python 3 – Try It Online"), [Search program](https://tio.run/##ZVJBbtswELzzFVvkEDJRZQvJoTCSvqDIB4oeVhIVEbWWApdGLBh@u7ukFNlFeBCE5czuzCzHKfaeni4XN4w@RKDDME6ADDSqLvgBeEqF5XYMbrAB6d2qpTJg7JXKdYZXYZUYAk567zjqK1xvC6i2cqqtMQW0cRrtq4AdxcYo1doOyB5jJmgyOwVy7qBz1DLE3gIPuN9bXiTATyD4cLGH2hGGCdhiaPrMcu1xFjLXWFTadpbCBdBjZTIs2HgINLfj30L6o1Qiikr19ukkS6@y9Oqr6s4HQHAEV5wAV/G/vP8LGEGEQxewic4Tz6qr8odYwE0t36p8zoTUrb52G/CYOsoorVFEb4STorstPJtlWPbd5WWU702rsYDapN47aDxFRwe74kb/sWyq23sf9Bs8PIAWLcaUyMmiXi2unJRSk1jrklIbyeATcZfms5fVzAvCcZT4GQYfrCwQCTw1tpBfx9AgRagtHNi2t/r3ljTb5d00xsC3vI/t7ouJVp4XSsPkZBH3PTtbETWylcsU4wo2t8My4AWO1wTTSU8g3fxXlAmS@v3pvDmdd3A635eyLAk751xkvDGXyz8) [Answer] # Score 194 ``` 1%(2^(n*30+16)%(n*30+17))*(1%(2^(n*30+22)%(n*30+23))*(1%(2^(n*30+28)%(n*30+29))*(1%(2^(n*30+12)%(n*30+13))*(1%(2^(n*30+6)%(n*30+7))*(1%(2^(n*30+10)%(n*30+11))*(1%(2^(n*30+18)%(n*30+19))*(-18)+8)+4)-6)-16)+6)+6)+n*30+17+702*0^(((n-360)*(n-523)*(n-654)*(n-941))^2) ``` [Verification](https://tio.run/##ZZHRboMwDEXf@Qq/VLXDmJJA6Tqpf7IXusIWiZgopA@o6rezFBiahmTJkW@Or27ihvDdcT42vrPQD9YNYKzrfADTO29snTTntrKXawX8/jGqHWohkEUuU1XSbjkdiQT@1bT@1XS@0d5W7fRfUyunNtxqt3FTcqXURlvd1OSWxUEaq6CspCxmSOdagqRHqYWMMCJneSkjwdkhhnj28lBM/VQ8bYSm0df9rQ1whnuDTNB0HhgMg6/4q0b1AkpKRY8kPiUHbPb3tmacIXrA1fTB8GcAvtlL7fvXPSXL1aptcfkBdPNiNy2eWRp/AA "Python 3 – Try It Online"), [generation code](https://tio.run/##pVffb6NGEH42f8V2q5MWAxd@xBedJV7aXqp7ud7LvVyaIGyWBMVeEOCEFPlvT2d2F3AMtlL1CTwz38zsN8PsuHipH3IRvL6mZb4l1cu2eCHZtsjLmmRVUWZbbhPBm1q@GsZqk68fq@wfTkISuEaephWvK/hx413ZfmD7n20vsK9sz7M9eL01VnGFtr5h/PHltx9/htfxpuJGwlOS8NXuns0bc2nMspRINbzOIJKoUW5Is0ImCBFZmpfb3SZG@5LXu1IQLflY8mITrzmjF9SmFxfUHCR3IJnPqXa2fuDrx86RLWzeFHxd88Su4Yjht1xw9L7OE8x5HBkDV7tNDUr@FG8YGpoy@87RL6GywIOoA6ZUBiVpnG14QnJBELUkLT72kNhgKMJW7O3eV9h2byBUbsNWPRUO4mLeGEv7wJ@o4U1WM08fOv1a/eRlzppD5ijzLphntc3eNKlh/EqSnFeiJs95@Yi8kiZ0O/Rfgo/BiKTG7DzyW16Pwd4HwEJMQ1dDp0ddatquDVkfyT0pd0dy/4Q8OCEXJ/yj3EP72bGGCScwQXs54a3TBehxUOJxdcaHkaR4nLAUB9NilZY3JfaPspWKIdkRplMtEKeb4pqX27hm/Qdtq2/Zxg/2sFzKBZS8Rc3@jol524P2Vqtgjrc3P0yrsMG6ToR@eH9c3Tz/O3RPlA4dQGlsX5Jr08CDOUfkdKPm2DBQhi4YBmgo8pr4TlHxXZKfBC0G0OLdoIOUrg5T6sqVieS79PAdFUxRpYcRhQ8Rv7yEZILomYxTAXXjQieKa9BrBxZY0bbez49ZTOQnjnMGBpv2e@N4t3LiHIIt5jngwJyziUxulhoyICj61ZVWUqjS1Dn9o4NG0amjenhWOjoAzBl1ABKG5MQRQp3DcGtAGFty4qlJy@HSQgSCVtEqLjHYVDMP3EpbwZ@jqoYL7V5m10os8BxFDkPnpmnJGJ39@YQGb9AWR/RNshdMsVeU/CkCOghed0D7JJ3AmLaDVkRDdclkaXqK5oGkwaxNHOVF6o13cnemYMd8YqS3sU8zDlT35jPjv3A9GzhLxsTr5SB6zmBd2NURb9a8qLNcVPLrG1VkCGS5sJwcLiuWAwIHOq54ic66Ha0mE2ZA5BvMza3MlQgsdRmLe85g3Liuhz3SdCvN2chq18FxpndDdbPr5YP2hksKu1WjFpEO@zEuCi4SxlDT3QdferXsVOnzq0g4puNODDjAYvaDV7kwhv2Cypq3Y41a1Opu7BSvQViwzDu4h62UztvCwT3kuJ5Y@TfEUevK9efuHWN4j35yYcoJZ@EH8vlpcSmfny89EzzjLqX5w@qfrqFF3sYx1NpLNWRJsAukqF8@1/lOwDL4@0NcVoPzoXvYUTeZ8nfn@G@x4eK@foDawAs7dGYeGKnOCsgTLytZSWzG6/5EEzuxgvZG5pkuK4Yu662PO6owhz8BhPKyzEvZToX5@vov "Python 3 – Try It Online") This is golfing down the [excellent solution of Max Kubierschky](https://codegolf.stackexchange.com/a/212389/20260), who said they will no longer spend time updating their answer. See their answer for an explanation of the strategy. The formula here is largely the same, but was shortened by removing repetition and introducing cancellations. **Branching** The main improvement is the arithmetic formula used to branch on a condition: ``` if b1: t1 else: t2 ``` Previously, this was done as `b1*t1+(1-b1)*t2`. This meant the condition `b1` needed to be repeated twice, which was costly because the condition of Fermat-primality used a relatively long formula. We instead regroup `b1*t1+(1-b1)*t2` into `b1*(t1-t2)+t2`. Instead of repeating the condition `b1`, we repeat the output `t2`. So, we arrange to make `t2 be short. As used, one of the branches just gives a number (the successfully found prime), which the other branches into further conditions to continue the search. ``` if b1: t1 else: if b2: t2 else: if b3: t3 else: ... ``` Our method has the no-result `t2` repeated twice rather than `t1`, but we can fix this by negating the condition `b2` so that we can interchange `t1` and `t2` We make it so that the twice-repeated `t1` is just a number, while the once-repeated `t2` is the long branch. We do this by negative the condition `b` to checking non-primality rather than primality. This is done by replacing the `1/stuff` check for `stuff==1` to instead be `1%stuff` for `stuff!=1` (in both cases, we know `stuff!=0`). Doing this recursive expansion, we further find that it has terms like `t1-t2` that subtract two potential outputs. These can be simplified. Because each possible output has form `30*n+d`, we can cancel like `(30*n+17)-(30*n+23)==-6`, saving many instances of writing `30*n+`. **Error fixing** We use a variation of [an idea suggested by Arnauld](https://codegolf.stackexchange.com/questions/212254/shortest-arithmetic-formula-to-output-1000-primes#comment499884_212389) to fix the faulty cases in a shorter way, using 32 characters not counting parens. ``` +702*0^(((n-360)*(n-523)*(n-654)*(n-941))^2) ``` There are four non-prime outputs, and a brute-force search finds that adding `702` to each one makes them prime and distinct from all other outputs. We use an indicator function of being in those four cases, and adding `702` times that indicator. The indication function uses `0^` to check `==0` for a product of `n-k` for each failed input `k`. (If we can't rely on `0^0==1`, we can use `1/(1+_)` as a slightly longer alternative for ``0^\_`.) ## Potential improvements Other potential approaches might hide errors in a more efficient way by adaptively adjusting the numbers checked and the base of the pseudoprime, as suggested by [in comments by Max Kubierschky](https://codegolf.stackexchange.com/questions/212254/shortest-arithmetic-formula-to-output-1000-primes#comment499937_212389). --- ## Score: 181 ``` 1%(4^(n*15+8)%(n*30+17))*(1%(4^(n*15+11)%(n*30+23))*(1%(4^(n*15+14)%(n*30+29))*(1%(4^(n*15+6)%(n*30+13))*(1%(8^(n*10+2)%(n*30+7))*(1%(4^(n*15+5)%(n*30+11))*(4-1%(4^(n*15+9)%(n*30+19))*9)+2)-3)-8)+3)+3)*2+n*30+17+702*0^(n%941%654%523%360) ``` [Verification](https://tio.run/##ZZHrjoIwEIX/8xRNE2KneKEUVEx8g32G3aAWJYHSlLpZY3x2tgXBW9KE0m/OmTOtuphTLXmb67pCzaVSF1RUqtYGFY3SRSU88af0FmPcMp/ElBJJWRKswbcbHgZsBUDJM2JsYBH/YPHI0ne2HC0H2bpHtnhAH82SUcQcimfPMB2ha5aC9ZlxmK0h4G7RKLiPEKzCiIZO5qcx85dJ7CcR9/kyhNZOPm@MLhQBz8u34jcrCS6zanfIkNzgwF2PJVo059KgLbrmRALKa40kKiTSmTwKwqaIhSGDm2fvVBqST66lkKQXwQ0disYUcm@QPFc7oZv5xFr2pVlZkvtTENUbq86419q6g1DdI/64KDaB@8y1UGW2FwRTiqf4G8PjZLGwJwtslTbD0ZysxIV5sXlUE1v8rIbuf4z3ooJhPPzVOW/QtW9xw9D@Aw "Python 3 – Try It Online") This includes some hand-found optimizations. First, the faulty cases are checked in a shorter way found by Sisyphus, as `0^(n%941%654%523%360)`. This evaluates to `1` exactly for the exceptional inputs `n` of `360, 523, 654, 941` and zero otherwise. This mod chain works because each value happens to be less than double the previous one, including if we append `1000` to the end. Other misc fixes uses that some values could be written shorter in base 10. Some of the expressions within the primality checks like `2^(n*30+16)` could be shortened like `4^(n*15+8)`. The various difference values were all even and could be written halved with a `*2` later. A `+stuff*(-18)` was changed to `-18*stuff`. [Answer] # Score ~~3627~~ 3611 -16 thanks to ovs ``` 3+2*((673353961358307057272173964285854305022400426862712283607156657501677042657259951223221803215027383567602764647222388720899640048400919228204711994106584574819864931142671077276501015670240042908527525811814749482980228611256604904077801987663433451736668942035070032934698860829734874720469210161714878816011028172504741493933579809209910574296450420677024369299112300880495910602256708103075450576078270852444355116728596095883942463207003664230806032583002863238578022990852754983925220712751300313297384933847995017349232355819646993088732601141789442882215894245107446410040144336314519163731984860252867369601943162930927332772671777942282743699929467221065940282853778104585857297151693682829776011636408160070741255197392398379178628552688459418297270015040378809673826532754044991491047949801618973677882844224163396790251399862833397713210556181592058088280808086833457843140471319676974659849432132663508730287070561924395375776930976500890901210246692236611967263433823329001222292758613681022886491412907860270659758688163330174276013329990329027854152360352827518702283024606693537791396445418370900593234237528394888627532943238538996362251812152746408784587329522604812362612961371495908130917050336369858923800623610558102111936921275925428797115215197211803311011792800756612190446912977181671053858030216650244322510913097098308798280996846215666363104582951499187555401911800510241478422010155586326948174226637924523831893487438486345918123442987712606546163773523778000231233612013623430096825956978942500937017215764165647469497368906623052990700252559013399879211291330909786175176769030687149835775829911173638805247625058275472816919156779291864013317155789882424054286324759552057921576616305056718594449895582860551963359519586408623708864584561224246719261364576172798288646507616917260121960060868716498458065082069151627356119717481764663140004551411443836333454961570935788652411333156384108866105400945838983456882978708424835088504807894682236883745784973974040648206299840824904279658635709233240664508551436734587146655032803436637243796714343511860088974399527943200654250140528821734417790449393945285632254377776046148129706540302453728840180914936819379438129581929627122804300127402709137830767613859849789109693350209773812357814726116008525681439255652001075856620439770299106395170302718499156517954285958747428744867003478259930463719139124320607133501439062288308905310881240867020273433661589445461066595657102669091317184108354554780017050349715850637537754106644755877075976187792445454821491839099929811225904639357052860836725499598183388404838427261429247485564633277253719915506486176500112852688184110139443587654583288837334797167835735314125201482147157537170750071301166473892100288867902409680472473344928486818014572141062729317739432887663007563551474290116952695377398184560337726343710669752174924005456400102600864172580302332762119194992885413026313261935677976382585514252800149731204021813826627080668911910552674815596682803932260276187920122242385797617877679445263885318204673888387270960551456287016730721644217841772314017713996319546205478449021962852317888766140480391183821928016315770425629570172282014425326824523667359350036132550758310731296339346026078740156028410312853179295874487323332796505227759163992369277010277291451843685489537975456773437258824811891298037075841518405314798557707912615382278504559764233167102285790740913352590724521945879074542935442272119863497621828348597890290006456761410388942801963190048896271350965485295433493478609534842891151210843278069634083290205578635819949175811191179//(3963**(n-1)))%3963) ``` (Brackets added for clarity, but not counted in score). This unpacks primes from a large number. There are 13 bits in the largest prime, but we can omit the last bit if we ignore the prime 2, since then the last bit is always 1. You can also check the [verification program](https://tio.run/##RZdLbibVEoTHeBWeXMluuJB5Tr7OnbIBJiwAhBss0XbrbzNg9X2/KCOhlqz@q84jMzIiMuvz329/vL7sr18/3l4/3f94@/vz2@v3P789//n9y1@ffn263T9/@vx6e7t//vLT7fnT093db08f7z8@vDz@7@6b29PbX7eX@/3t@vDwUL137lO@c7a1Za9e3jyJNTkZ29LWCrNYNbXa15pd1p5V2Wle3XrHxjwneb3X8rG9nI29Z2d18b@Kil68nullc7iBQ4c/xw@HLot2PyfcKieyY/xMxdnunN9uTWzFjcbdbe8xHZtcnSvHfTw6Tsw6Q8hT7osgLY4Fe8c4rqt27B1JilU1J5btJG/iPTvqzJRxQO@YJlzj0eLC8naezHiZu61x0iXgcOI7QNjceZad40BIWBW8XiZwVmwO4Y2vbTZDQMkyMFnKY9wAPlmf4NSzWilFxM500KUMp@zkzCbaqL2ucIsCbRuO2UulIyZe7clW8ucfXOKwa@Vij/PTWbd9K78hcP40NTPAiEPduBHMKdQ5HD29l7INb3CCDkNhU5ABn3VQT6cE5oS6aztPj9fuDc4BjFw70KuI3k9sLxAGIwi3qCQF7W4Oo/IthA4YBeku1f8E@ZD5pm5ukaJiE7an19nFK360oqsNj1QWUKEcC9DIjmzIvA@hF8ck3IVScEv7QBgKEfmmoHaIceDvFlwWQaGC8oAM4Knyw3nUkfQHFFZwJfLoQ4K@z9EFmyfdAEv1kx2ecCHHtMeufzViXQ84hIgOSMjidJArpQi2gnbBRWAn95YWC2HEPqCQJCv0xH@0Y8ecu2ADzFpwwXXcurg9C4APGaK1BdyJEEDMJQnJiXryulWgFtJaIF6TA0SIJVR1AhTSOasxAU8uQSiqVTrByQR0vRHAVpWOyzKCpcBOeJYHPkFRtCnizsg8AFmpwtItA9iFBEALWsEB1RGAUrw7UBbl8oo1RcDkgAIRDrUGBwcdE@tQLJTkRLNirfBXqg4gUp1ID/8hb0MernHRg9cYFL4Cf/pQIvQHhstxCsjv4hZhyXMIlDqSq2N3ZEz0hEwAKobBMWI@qjLpTNSSLZbUINKShotP05lwC3lwr6UKh1UNZLrMjJCRbgGS8BcLCCqAfDbku5xoS1EQ6AitDQ2xMhQN/hkl0TXFkVgMI9gsAQoOBzwogcOimDwJ3yRfKHQoEhbmWA58TpyZvENEh1zFLkt5CEJBxQnqUAKqExcuRvJkT/4wCzq0iAxENaoQft@t1ElWJovdc1Z0cW2KPrgq0OL5cnEOJCUqz5FYbKIQLHhhMaaiAUtQQPSLOZ4rXGVL7dnrGCM2eYb3VKBM0ofGrHfsUnQiEdyU/6qhgIgOZuNZkgRyJP51lY8llJffBNZyPbiApZSE245qxEvApjcYS3AhfCwlO2xMdWO/LBD4gzDCZYr0yS3VB@xNyAIyXAQYTrab9KmqKzzRVn2QO9DFsAVFQkKEBkli5AqDYY2pftQSptMO@jIUuV3jKVah4ACengqEcJncStzS5XIF1qgvjSLE0ra05gSeaAkKQxVxD8thHy/4TQcCWG7nCgiATKVfE@2oJ/mm2oL6B12iJR@1QxLBdEtS4ayWUcNSqfnIckJ6ClyDvVQe7aiLYlGwkuO1TH0I0b@PGyYKo@SQY0G@1qQC6RxtyjwBBUWW2rDRgtGCRAI2iIxKqzfQDMGUlDCDpASch@aJsWjx8m4TYa0wW6yF8GCXlMtaHEJUhFWaCOQkgRbVgpGwZp5NcpiTHNCX0NF0pFh0HQUhyy3Pzq1is8S0fWk4UuOsq6eGdEx5pNLEd3CBo1xdgbBvMyAgHfT9bn2hXggnuFn2m5qa8F@MBmMgNToFtiMf4eSEGWpqGLFdfZZhidocBS5WqopQHUpQMKrMe9qVigP3YKBQxHLQYsAdqP7ewlNZg1GKekhJvYmD5@q2ChtzgwuwiLkrRW6ggLZoQm5cLa@ge6gjURK/oiQtZeRKwgSkejz@hDDoeKYTrt4bMjU6KUFxHuOLHJJbOYZJwYUHcTM8Qgdxdq7Z73J6DVaq5NHRcLrUYVmlmJM2t/u9lbYwpT/Cb85HoOSgoVXVgVI4JxhczUF44P1wABMlFLVMHpdmLZr4vpyu0TvrdblGI86RdrFpeI2tawgpDX@muVRnmeYWuQsGXJp5jGqpL66ruIwY6vFxDX2qN36BLMSlJdsFWA3VGm9AfTT2nMskyUIDBgVARzQ22gl7JeAlC3NNMurOuCgdzUQ7ADZZoooLpHOhqUlGMeERBO9qpJgz9dMHAXecvJqMRnvsELrAi6uvFTczH6TGWBCCQGgRdQgNObgmcWFMQqFhn6pTzy1qbTXsS4qhOWELeUwOBsPI1PwJ/ur8BEGdSOloMGXuKooyqvTRsE1BVGHqQUj6dlDXJxnRjsu0Q4KFqBRMiuI9SiVPDUQyeRAH@n1NCeRICZg/JVk6MdJqZeqy9OsFFkLCmh81fRw18yPKUFUafMrDTFMbUtL3kvhL2WjW@mxRKfStNJcjghsZswkc9C1zZET6QuAg1lOO1HBIyoRKt@IqtK1RztRfof/oM4tGp48mDSV9fvjhgfltf/jw8PJff3x8/I9@Pd7dfXy93b/cP7/c3355@f3pAQHad/YdS/iO/OXLl6d/PzEf9HX5@PXr/wE). I do not consider this anywhere close to optimal, but it's a good starting point. ]
[Question] [ ## Games are fun This Code Golf here was so fun I had to make a version for other classic games similar in complexity: [Shortest Way of creating a basic Space Invaders Game in Python](https://codegolf.stackexchange.com/questions/4410/shortest-way-of-creating-a-basic-space-invaders-game-in-python) This time, however, try to recreate the classic 'Snake' game, in which you start out as a small shape, constantly moving to collecting pieces to increase your score. When you collect a piece, your 'tail' grows, which follows the path you have made. The objective is to last the longest without crashing into your own tail, or into the walls Qualifications: * You, the characters that make up the tail, the walls, and the pieces you collect should all be different characters * Show a HUD with the score. The score increases by 1 point for each piece you collect * The player loses when they collide with their own tail or the wall * A piece spawns in a random area immediately after a piece is collected, not to mention at the start of the game * Speed of the game doesn't matter, as long as it is consistent * ~~The 'cells' should be 2x1 characters, since the height of block characters is ~twice the width~~ Can be 1x1, because 2x1 is just ugly and I didn't really think of that * The keys for changing the direction should be `awsd`, left, up, down, right respectively * The starting direction should always be up * You must show the edges of the wall. The score may overlap the wall Shortest code that meets the above criteria wins. Imaginary Bonus Points for creativity. [Answer] ## JavaScript (~~553~~ 512 bytes) [Link to playable version](http://copy.sh/snake/) ``` c=0;a=b=d=-1;e=[f=[20,7],[20,8]];i=Math.random;~function n(){if(c&&(87==a||83==a ))c=0,d=87==a?-1:1;if(d&&(65==a||68==a))d=0,c=65==a?-1:1;p([j=e[0][0]+c,k=e[0][1 ]+d])||!j||39==j||!k||10==k?b+=" | GAME OVER":(e.unshift([j,k]),p(f)?(f=[1+38*i( )|0,1+9*i()|0],b++):e.pop());for(m=h="";11>h;h++){for(g=0;40>g;g++)l=g+","+h,m+= !g||39==g||!h||10==h?"X":e[0]==l?"O":p(l)?"*":f==l?"%":" ";m+="\n"}x.innerHTML=m +b;!b.sup&&setTimeout(n,99)}();onkeydown=function(o){a=o.keyCode};function p(o){ return e.join(p).indexOf(p+o)+1} ``` I tried to make it output to the real console at first (with `console.log` and `console.clear`), but it was flickering too much, so I put it into console-like HTML. It will work with this: ``` <pre id=x> ``` Also I implemented it with 2x1 cells first, but it just looked worse than 1x1. That would be a minor change though. Uses `awsd` keys on keyboard. **Update:** I was able to cut it down to 512 (exactly 0x200) bytes by improving the tail search and doing some more magic. You now get 2 points when a piece spawns in your tail (it's a feature). I also fixed the overlapping when the snake bites itself. [Answer] **16 bit 8086** 526 bytes / 390 bytes Decode this using [a Base64 decoder](http://www.opinionatedgeek.com/DotNet/Tools/Base64Decode/default.aspx) and call it "snake.com" then execute from Windows command prompt. Tested on WinXP, you may need to use DosBox to get the right video mode. Control keys are 'wasd' and space to exit. Press 'w' to start. ``` uBMAzRC5AD+2AOipAb1AAbgAoI7Auf//v4sMsAHzqrgAtLksAfOqg8cU/sx19OgsAYs+8gKwAuj4 ALQAzRpCiRYOA4kWEAPouAC0C80hCsB0IbQIzSG+ygKDxgOAPAB0EjgEdfSLRAGzAP/Qo1cBiB7w AulqAIEGdAGu/7P+uNECgMMEw7MCuNsCgMMGw4s+8gKLHvACisPolwADv+YCJoo16I0AiT7yAoD+ A775AnREiz70AiaKHbAA6HUAA7/mAok+9AKA/gB0FscGVwHNAoEudAGu/zPJtj/o2QDofQC0AM0a OxYOA3X2/wYOA+lZ/8YEAE7+BIA8CnT16F4AaOAB6EQAM9K5LQD38YvCweACBQoA9+WL+OguALlL ADPS9/HB4gKDwgsD+iaAPQB10rADiMRXq4HHPQGrq4HHPAGrq4HHPQGrX8OhEAO62wD34rntf/fx iRYQA4vCw772Ar8K9bUEshCstACL2AHDi4f6ArMDtwXR+LEAwNEC/smA4Q8miA0p7/7PdevoIQA6 xHQE/st13ugKAP7NdcroAwB1+8O3BSbGBQEp7/7PdfaBx0EG/srDuBAQM9uAwwLNEID7CnX2w7gD AM0QzSB3dgEgxgIAYYcBZIUBIMYCAHd8AXN+ASDGAgAA+wAF/P8EAAIAH4ofigAAAADRxeD/TJlO gQPvQrVA4++BVdVjgQ== ``` Here's a character mode version that's 390 bytes long: ``` uAMAzRC4ALiOwLlQADP/uCCf86uzF6u4AA+xTvOruCCfq7LdfCxUPOr6BgBiz5+AqF8Aqu0AM0aQ okWhgKJFogC6MUAtAvNIQrAdCG0CM0hvlYCg8YDgDwAdBI4BHX0i0QBswD/0KNSAYgefALpdgCBB m8Bov+z/rhdAoDDBMOzArhnAoDDBsOLPn4Cix58AiaJHQOclgmijUmiR2JPn4CgP4DvoUCdFOLPo ACJoodJscFAAADv3JYiT6AAoD+AHQkxwZSAVkCgS5vAaL/vwEAudAHJoA9qnUEJsYFzIPHAuLx6F 4AtADNGjsWhgJ19oMGhgIC6Uz/xgQATv4EgDwKdPXoPgBo5wHoIgC5FwD38Wn6oADoFgC5TgD38U ID0gP6JoA9AHXhJscFA93DoYgCutsA9+K57X/38YkWiAKLwjPSw76CAr8CALkEALSfrAQwq+L6w8 0gd3EBIFcCAGGCAWSAASBXAgB3dwFzeQEgVwIAYP+gAP7/AgACqtAH0AcAAAAA ``` This character mode one's three bytes longer (but the snake's better): ``` uAMAzRC4ALiOwLlQADP/uCCf86uzF6u4AA+xTvOruCCfq/7LdfCxUPOr6BsBiz6BAibHBQEKtADN GkKJFokCiRaLAujHALQLzSEKwHQhtAjNIb5ZAoPGA4A8AHQSOAR19ItEAbMA/9CjUwGIHn8C6XgA gQZwAaD/s/64YAKAwwTDswK4agKAwwbDiz6BAosefwImiR0Dv3VYJoo1JscFAQqJPoECgP4DvogC dFOLPoMCJoodJscFAAADv3VYiT6DAoD+AHQkxwZTAVwCgS5wAaD/vwEAudAHJoA9qnUEJsYFzIPH AuLx6F4AtADNGjsWiQJ19oMGiQIE6Ur/xgQATv4EgDwKdPXoPgBo6gHoIgC5FwD38Wn6oADoFgC5 TgD38UID0gP6JoA9AHXhJscFA93DoYsCutsA9+K57X/38YkWiwKLwjPSw76FAr8CALkEALSfrAQw q+L6w80gd3IBIFoCAGGDAWSBASBaAgB3eAFzegEgWgIAYP+gAP7/AgACqtAH0AcAAAAA ``` [Answer] ## shell/sh, 578 chars I tried to be POSIX compliant (being as much portable as possible and avoid bashisms, even the random-number-generator does not need /proc). You can e.g. play it in your native terminal or via a SSH-session: run with 'dash -c ./snake' There is also an unuglyfied/readable variant in ~2800 bytes, which can be seen [here](https://github.com/bittorf/shell_snake). Some notes: shell-scripting is not suited for coding games 8-) * to be fair, we only used so called 'builtins', which means: + no external calls of programs like 'clear', 'stty' or 'tput' + because of that, we redraw the whole screen on every move + the only used builtins (aka native commands) are: - echo, eval, while-loop, let, break, read, case, test, set, shift, alias, source * there is no random number generator (PRNG), so we have to built our own * getting a keystroke blocks, so we have to spawn another thread + for getting the event in parent-task we use a tempfile (ugly!) * the snake itself is a list, which is cheap: + each element is a (x,y)-tuple + loosing the tail means: shift the list by 1 + adding a (new) head means: append a string * the grid is internally an array, but shell/sh does not know this: + we "emulated" array(x,y) via an ugly eval-call with global vars * and finally: we had a lot of fun! ``` #!/bin/sh alias J=do T=let E=echo D=done W=while\ let p(){ eval A$1x$2=${3:-#};} g(){ eval F="\${A$1x$2:- }";} r(){ E $((1+(99*I)%$1)) } X=9 Y=8 L="8 8 $X $Y" I=41 W I-=1 J p $I 1 p $I 21 p 1 $I p 41 $I D p 3 3 : >L W I+=1 J E -ne \\033[H y=22 W y-=1 J Z= x=42 W x-=1 J g $x $y Z=$Z$F D E "$Z" D E $B . ./L case $D in a)T X+=1;;d)T X-=1;;s)T Y-=1;;*)T Y+=1;;esac g $X $Y case $F in \ |:)p $X $Y O L="$L $X $Y" case $F in :)W I+=1 J x=`r 39` y=`r 19` g $x $y [ "$F" = \ ]&&{ p $x $y : break } D T B+=1;;*)set $L p $1 $2 \ shift 2 L=$@;;esac;;*).;; esac D& while read -sn1 K J E D=$K>L D ``` ![enter image description here](https://i.stack.imgur.com/0AEY1.png) [Answer] ### C# .NET Framework 4.7.2 Console (~~2,456~~ ~~2,440~~ ~~2,424~~ ~~2,408~~ ~~2,052~~ ~~1,973~~ ~~1,747~~ 1,686 bytes) This was fun, but I really had to think what variables were what, because they are only one letter. ``` using m=System.Console;using System;using System.Collections.Generic;using System.Threading;class s{static void Main(){m.CursorVisible=0>1;new s()._();}int l;Action<string> w=(x)=>m.Write(x);Action<int,int>n=(x,y)=>m.SetCursorPosition(x,y);(int x,int y)d,c,a;int h,u;List<(int x,int y)>p;void _(){while(1>0){f();h=25;u=25;p=new List<(int x,int y)>();l=0;d=(0,-1);c=(u/2,h/2);e();m.SetWindowSize(u+4,h+4);m.SetBufferSize(u+4,h+4);while(1>0){k();if(t())break;g();r();}f();m.SetWindowSize(u+4,h+6);m.SetBufferSize(u+4,h+6);n(1,h+3);w(" Game over,\n press any key to retry.");f();m.ReadKey(1>0);m.Clear();}}private bool t(){if(c.x<0||c.y<0||c.x>=u||c.y>=h){r();n(c.x+2,c.y+2);w("X");return 1>0;}for(i=0;i<p.Count;i++){for(int j=0;j<i;j++){if(p[i].x==p[j].x&&p[i].y==p[j].y){r();n(c.x+2,c.y+2);w("X");return 1>0;}}}return 0>1;}private void e(){a=(z.Next(u),z.Next(h));l++;}void f(){while(m.KeyAvailable)m.ReadKey(1>0);}int i;void k(){var b=DateTime.Now;while((DateTime.Now-b).TotalMilliseconds<230)Thread.Sleep(10);if(!m.KeyAvailable)return;var a=m.ReadKey(1>0).Key;switch(a){case ConsoleKey.A:if(d.x==0)d=(-1,0);break;case ConsoleKey.W:if(d.y==0)d=(0,-1);break;case ConsoleKey.S:if(d.y==0)d=(0,1);break;case ConsoleKey.D:if(d.x==0)d=(1,0);break;}f();}void g(){c.x+=d.x;c.y+=d.y;p.Add((c.x,c.y));while(p.Count>l)p.RemoveAt(0);if(c.x==a.x&&c.y==a.y)e();}void r(){n(1,1);w("/");w(new string('-',u));w("\\");n(1,h+2);w("\\");w(new string('-',u));w("/");for(i=0;i<h;i++){n(1,i+2);w("|");n(u+2,i+2);w("|");}for(i=0;i<h;i++){for(int j=0;j<u;j++){n(i+2,j+2);w(" ");}}n(a.x+2,a.y+2);w("@");for(i=0;i<p.Count;i++){n(p[i].x+2,p[i].y+2);w("#");}n(2,0);w("Score:"+l);}Random z=new Random();} ``` Some screenshots: [![Snake with score of 10](https://i.stack.imgur.com/X25F7.png)](https://i.stack.imgur.com/X25F7.png) [![Snake crashed with score of 4](https://i.stack.imgur.com/Q09XC.png)](https://i.stack.imgur.com/Q09XC.png) <no longer have binaries, you can compile yourself> [Answer] # Applesoft Basic - 478 (462) This was my first ever code golf, but it was written back in 1989, and it mostly implements the snake game as requested (but without food, the snakes just continuously grow, and it's actually two players, not one) using only two lines of Applesoft Basic. There were a number of two-line program contests at the time, such as in Dr. Dobbs journal. I spent 6 months figuring out how to fit this into two lines which have a limit of 255 characters (and only one branch) More info at: <http://davesource.com/Projects/SpeedWaller/> The program typed in is exactly two lines: ``` 1ONSCRN(X,Y)<>7ANDB<>0ANDSCRN(U,V)<>7GOTO2:HOME:GR:X=10:Y=20:U=30:V=Y:I=201:J=202:K=203:M=205:W=215:A=193:S=211:Z=218:O=1:Q=-1:P=49152:COLOR=7:HLIN0,39AT0:HLIN0,39AT39:VLIN0,39AT0:VLIN0,39AT39:VTAB22: ?"WASZ IJKM "C:ONB=0GOTO2:CALL-678:RUN 2PLOTX,Y:PLOTU,V:B=PEEK(P):G=B<>ZANDB<>W:H=B<>AANDB<>S:O=G*(O*H+(B=S)-(B=A)):L=H*(L*G+(B=Z)-(B=W)):G=B<>IANDB<>M:H=B<>JANDB<>K:Q=G*(Q*H+(B=K)-(B=J)):R=H*(R*G+(B=M)-(B=I)):X=X+O:Y=Y+L:U=U+Q:V=V+R:FORN=1TO99:NEXT:C=C+1:VTAB22:HTAB12:?C:GOTO1 ``` The listing when formatted looks like this: ``` 1 ONSCRN(X,Y)<>7 AND B<>0 AND SCRN(U,V) <> 7 GOTO 2: HOME : GR : X=10 : Y=20 : U=30 : V=Y : I=201 : J=202 : K=203 : M=205 : W=215 : A=193 : S=211 : Z=218 : O=1 : Q=-1 : P=49152 : COLOR=7 : HLIN 0,39 AT 0 : HLIN 0,39 AT 39 : VLIN 0,39 AT 0 : VLIN 0,39 AT 39 : VTAB 22 : ? "WASZ IJKM "C : ON B=0 GOTO 2 : CALL -678 : RUN 2 PLOT X,Y : PLOT U,V : B=PEEK(P) : G= B<>Z AND B<>W: H=B<>A AND B<>S : O=G*(O*H+(B=S)-(B=A)) : L=H*(L*G+(B=Z)-(B=W)) : G=B<>I AND B<>M : H=B<>J AND B<>K : Q=G*(Q*H+(B=K)-(B=J)) : R=H*(R*G+(B=M)-(B=I)) : X=X+O : Y=Y+L : U=U+Q : V=V+R : FOR N=1 TO 99 : NEXT : C=C+1 : VTAB 22 : HTAB 12 : ? C : GOTO 1 ``` The game is actually *two players* and includes "instructions" at the bottom of the page showing the keys as well as a counter so you can see how many steps you survived. It's 478 characters, 16 of those are the instructions and counter output, so 462 if you want to shave those off. [Answer] # TI-Basic, 307 [bytes](https://codegolf.meta.stackexchange.com/a/4764/98541) This one is very special to me, since I learned to program with a similar snake game on my TI-83+ (in high school, during boring classes). Also, on these calculators, golfing the programs was a real concern because of the limited space and performance The controls are the direction keys, but they could easily be changed for `awsd` (although noone would want that since it's an `abc` layout) codes for the keys would be: `A`: 41, `W`: 85, `S`: 81, `D`: 51 ``` ClrHome 99→dim(ʟX ʟX→Y {8,16→dim([A] For(X,1,16 For(Y,1,8 If X=1 or X=16 or Y=1 or Y=16 Then Output(Y,X,": 1→[A](Y,X End:End:End 8→X:7→Y:-1→V Repeat [A](Y,X 1+I(I<99→I Y→ʟY(I X→ʟX(I Output(Y,X,0 1→[A](Y,X If X=N and Y=O or not(N Then Repeat not([A](O,N randInt(2,7→O randInt(2,15→N End Output(O,N,1 Output(1,1,S S+1→S Else 1+J(J<99→J ʟY(J Output(Ans,ʟX(J)," 0→[A](Ans,ʟX(J End getKey→G not(G)U+(G=26)-(G=24→U not(G)V+(G=34)-(G=25→V X+U→X:Y+V→Y End ``` [![demo as gif](https://i.stack.imgur.com/lizob.gif)](https://i.stack.imgur.com/lizob.gif) [Answer] **Ruby 1.9 */Windows only/* (354 337 355 346 bytes)** ``` require'Win32API';G=(W=Win32API).new g="crtdll","_getch",t=[],?I B=(c=?#*39+h="# #")+((S=' ')*38+h)*20+c;n=proc{c while B[c=rand(800)]!=S;B[c]=?*;S} n[h=760];k={97=>-1,100=>1,119=>d=-41,115=>41} (B[h]=?O;system'cls';$><<B<<$.;sleep 0.1 d=k[G.call]if W.new(g,"_kbhit",[],?I).call>0 t<<h;B[h]=?o;B[h+=d]==?*?B[h]=n[$.+=1]:B[t.shift]=S)while B[h]==S ``` Plays in a 20x40 board in the windows console. The score is shown under the board. Use `WASD` to control the snake, any other key to exit (forcefully!). Edit the sleep time at the end of line 5 to control the speed. *(Or save 10 characters and make it nearly unplayable by removing the sleep entirely!)* Bonus feature: randomly fails to start (when initial piece is generated in snake's location). I needed ~100 chars to work around the lack of a non-blocking getchar. Apparently Ruby 1.9.3 includes a "io/console" library which would have saved roughly half of those. And this solution is Windows specific. There are published solutions to do the same type of thing in \*nix systems, but I haven't tested them to compare the character count. Edit: Had to add 18 bytes after I realized that the tail only grows after eating, not after each step. Edit 2: (Possibly) fixed crash issue, saved the 9 bytes by restricting to one food item. [Answer] # Python 3 - 644 ``` from curses import * import time from collections import deque from random import randrange as R N,W,S,E=z=119,97,115,100 t=tuple u=0,0 def m(s): a=lambda o,y,x:y.addch(o[0],o[1],x);q=lambda:(R(L-2),R(C-2));L,C=s.getmaxyx();curs_set(0);s.nodelay(1);s.border();s.refresh();r=newwin(L-2,C-2,1,1);n=deque();y,x=[L-2,0];d=N;n.append(u);c=N;p=q();a(p,r,N);a(u,s,48) while 1: if c in z:d=c if d==N:y-=1 if d==S:y+=1 if d==W:x-=1 if d==E:x+=1 l=n.pop() if (y,x) in n:return if (y,x)==p:p=q();a(p,r,N);n.append(l);s.addstr(0,0,str(len(n))) n.appendleft((y,x));a((y,x),r,S);a(l,r,32);r.refresh();time.sleep(.2);c=s.getch() wrapper(m) ``` Does not quit cleanly. Piece might disappear if it spawns on top of the snake. [Answer] ## Bash (too many characters: ca. 1522) ``` t=tput tc="$t cup" tr="$t rev" ts="$t sgr0" ox=5 oy=5 ((w=$($t cols)-2-2*ox)) ((h=$($t lines)-2-2*oy)) trap "$t rmcup stty echo echo 'Thanks for playing snake!' " EXIT $t smcup $t civis stty -echo clear printf -v hs %$((w+2))s printf -v v "|%${w}s|" $tc $oy $ox printf %s ${hs// /_} for((i=1;i<=h+1;++i)); do $tc $((oy+i)) $ox printf %s "$v" done $tc $((oy+h+2)) $ox printf %s ${hs// /¯} dx=0 dy=-1 hx=$((w/2)) hy=$((h-2)) l=2 xa=($hx $hx) ya=($hy $((hy+1))) $tr for((i=0;i<${#xa[@]};++i)); do $tc $((ya[i]+1+oy)) $((xa[i]+1+ox)) printf \ done $ts print_food() { $tc $((fy+1+oy)) $((fx+1+ox)) printf "*" } nf() { rf=1 while((rf)) do rf=0 ((fx=RANDOM%w)) ((fy=RANDOM%h)) for ((i=0;i<${#ya[@]};++i)) do if((ya[i]==fy&&xa[i]==fx)) then rf=1 break fi done done print_food } nf ps() { s="SCORE: $l" $tc $((oy-1)) $((ox+(w-${#s})/2)) printf "$s" } ps while : do read -t 0.2 -s -n1 k if (($?==0)) then case $k in w|W)((dy==0))&&{ dx=0;dy=-1;};; a|A)((dx==0))&&{ dx=-1;dy=0;};; s|S)((dy==0))&&{ dx=0;dy=1;};; d|D)((dx==0))&&{ dx=1; dy=0;};; q|Q)break;; esac fi ((hx=${xa[0]}+dx)) ((hy=${ya[0]}+dy)) if((hx<0||hy<0||hx>w||hy>h)) then go=1 break fi for((i=1;i<${#ya[@]}-1;++i)) do if((hx==xa[i]&&hy==ya[i])) then go=1 break 2 fi done $tc $((ya[-1]+1+oy)) $((xa[-1]+1+ox)) printf \ $tr $tc $((hy+1+oy)) $((hx+1+ox)) printf \ $ts if((hx==fx&&hy==fy)) then ((++l)) ps nf else ya=(${ya[@]::${#ya[@]}-1}) xa=(${xa[@]::${#xa[@]}-1}) fi ya=($hy ${ya[@]}) xa=($hx ${xa[@]}) done if((go)) then $tc 3 3 echo GAME OVER read -t 3 -s -n1 fi ``` ![Screenshot](https://i.stack.imgur.com/eBtVd.png) [Answer] # Binary - ~~617~~ 274 Bytes Base 64: ``` jtiO0LgAuI7AMf+50Ae4IAJg86u4//+5JgC/qALzq7kRAKtguSkAMcDzq7j//6thgceeAOLsuSYAv0oN86 thic+9BgDojADkYCR/PEh0HDxLdBM8TXQKPFB17IHHoADrDoPHBOsJg+8E6wSB76AAsAkmgD0HD5TEdAYm gD0gdYCqT2AGHgeJ6UG+GH0B7on3R0f986T8B2FXiT4YfYD8AXQJi74YfbAgquskRUW/MAKDBhR9AaEUfb MK9vOGxAQwqoPvA4jgMOQIwHXu6AQAX+l0/2Bmuf//AABm9/G5///38YnXgef/D4H/gAJ95on6g8Iog+oo g/ooffiD+hJ91IHH0wDB5wImgD0JdMewB6phww== ``` Hex: ``` d88ed08e00b88eb831c0b9ff07d020b86002abf3ffb8b9ff0026a8bff302b9ab001160ab29b93100f3 c0b8abffff61abc781009eece226b9bf000d4aabf38961bdcf00068ce8e40024603c7f74483c1c744b 3c13744d3c0a755081eca0c7eb00830e04c709ebef83eb048104a0efb00026093d800f07c494067480 26203d80754faa0660071ee989be417d18ee01f7894747f3fdfca461078957183e807d01fc0974be8b 7d1820b0ebaa4524bf45023006837d14a1017d140ab3f3f6c486300483aa03efe088e430c008ee7504 e85f0074e960ffb966ffff0000f766b9f1fffff1f7d789e7810fffff810280e67dfa89c283832828ea fa837d2883f812fad47dc78100d3e7c126023d807409b0c7aa07c361 ``` Create a .com file from the above hex and run it in DOSBox. Even though the qualifications says: > > Speed of the game doesn't matter, as long as it is consistent > > > You should use the command `cycles 1` if you want the game to be playable There is also a version with no score which is 232 bytes ``` 8ed88ed0b800b88ec031ffb9d007b8200260f3abb8ffffb92600bfa802 f3abb91100ab60b9290031c0f3abb8ffffab6181c79e00e2ecb92600bf 4a0df3ab6189cfbd0600e86c00e460247f3c48741c3c4b74133c4d740a 3c5075ec81c7a000eb0e83c704eb0983ef04eb0481efa000b00926803d 070f94c4740626803d207580aa4f60061e0789e941bee87c01ee89f747 47fdf3a4fc076157893ee87c80fc0174098bbee87cb020aaeb054545e8 03005feb9460b9ffff66f7f181e2ff0f81fa80027df089d783c22883ea 2883fa287df883fa127dde81c7d300c1e70226803d0974d1b007aa61c3 ``` [Answer] # JavaScript (Node) (348 bytes) ``` B=_=>s.includes(c=0|Math.random()*4)?B():c;E=i=>s.includes(i)?+(i==s[0 ]):i^o?9:2;D=_=>console.log(I+`\n ##\n#${E(0)}${E(1)}#\n#${E(2)}${E(3) }#\n ##`);o=B(s=[I=0]);f='w';process.stdin.setRawMode(1).on('data',k=> f=k);setInterval(_=>D(s.includes(z=s[0]+{w:-2,s:2,a:-1,d:1}[f])|z<0|z> 3|s[0]+z==3&&process.exit(),s=[z,...s],z^o?s.pop():o=B(I++)),99);D() ``` Pretty is not a requirement, right? Or easy? Or big? [![enter image description here](https://i.stack.imgur.com/lCzm6.png)](https://i.stack.imgur.com/lCzm6.png) You start in the top-left corner of a 2x2 grid, facing up (so you better push "d" real quick). A "9" represents a background character, a "1" is the head of your snake, any "0"s are tails, and a "2" is a piece you're trying to collect. Browser-playable version ``` // Mocking Node process = { stdin: { setRawMode: () => ({ on(_, callback) { addEventListener('keydown', e => callback(e.key)) } }) } } process.exit = () => { for (let i = 0; i < 9999; ++i) clearInterval(i) throw new Error('Game Over!') } // Allow restarting document.getElementById('run') .addEventListener('click', () => { for (let i = 0; i < 9999; ++i) clearInterval(i) main() }) function main() { // The game B=_=>s.includes(c=0|Math.random()*4)?B():c;E=i=>s.includes(i)?+(i==s[0]):i^o?9:2;D=_=>console.log(I+`\n ##\n#${E(0)}${E(1)}#\n#${E(2)}${E(3)}#\n ##`);o=B(s=[I=0]);f='w';process.stdin.setRawMode(1).on('data',k=>f=k);setInterval(_=>D(s.includes(z=s[0]+{w:-2,s:2,a:-1,d:1}[f])|z<0|z>3|s[0]+z==3&&process.exit(),s=[z,...s],z^o?s.pop():o=B(I++)),99);D() } ``` ``` <button id=run>run</button> ``` A slowed-down version (A 99ms interval is pretty difficult) ``` // Mocking Node process = { stdin: { setRawMode: () => ({ on(_, callback) { addEventListener('keydown', e => callback(e.key)) } }) } } process.exit = () => { for (let i = 0; i < 9999; ++i) clearInterval(i) throw new Error('Game Over!') } // Allow restarting document.getElementById('run') .addEventListener('click', () => { for (let i = 0; i < 9999; ++i) clearInterval(i) main() }) function main() { // The game B=_=>s.includes(c=0|Math.random()*4)?B():c;E=i=>s.includes(i)?+(i==s[0]):i^o?9:2;D=_=>console.log(I+`\n ##\n#${E(0)}${E(1)}#\n#${E(2)}${E(3)}#\n ##`);o=B(s=[I=0]);f='w';process.stdin.setRawMode(1).on('data',k=>f=k);setInterval(_=>D(s.includes(z=s[0]+{w:-2,s:2,a:-1,d:1}[f])|z<0|z>3|s[0]+z==3&&process.exit(),s=[z,...s],z^o?s.pop():o=B(I++)),499);D() } ``` ``` <button id=run>run</button> ``` You know you've won when you get a max-call-stack-exceeded error :). If you want a version that's a little nicer to play, I also golfed a 3x3 version down to 381 bytes. ``` B=_=>s.includes(c=0|Math.random()*9)?B():c;D=_=>s.map((c)=>b[c]=+(s[0] ==c),b=[...1e9-1+''],b[o]=2)+console.log(I+`\n ##${b.map((h,i)=>i%3?h: '#\n#'+h).join('')}#\n ###`);o=B(s=[I=0]);f='w';process.stdin. setRawMode(1).on('data',k=>f=k);setInterval(_=>D(s.includes(z=s[0]+{w: -3,s:3,a:-1,d:1}[f])|z<0|z>8|(z%3!=1&&s[0]%3+z%3==2)&&process.exit(),s =[z,...s],z^o?s.pop():o=B(I++)),99);D() ``` Browser-playable version ``` // Mocking Node process = { stdin: { setRawMode: () => ({ on(_, callback) { addEventListener('keydown', e => callback(e.key)) } }) } } process.exit = () => { for (let i = 0; i < 9999; ++i) clearInterval(i) throw new Error('Game Over!') } // Allow restarting document.getElementById('run') .addEventListener('click', () => { for (let i = 0; i < 9999; ++i) clearInterval(i) main() }) function main() { // The game B=_=>s.includes(c=0|Math.random()*9)?B():c;D=_=>s.map((c)=>b[c]=+(s[0]==c),b=[...1e9-1+''],b[o]=2)+console.log(I+`\n ##${b.map((h,i)=>i%3?h:'#\n#'+h).join('')}#\n ###`);o=B(s=[I=0]);f='w';process.stdin.setRawMode(1).on('data',k=>f=k);setInterval(_=>D(s.includes(z=s[0]+{w:-3,s:3,a:-1,d:1}[f])|z<0|z>8|(z%3!=1&&s[0]%3+z%3==2)&&process.exit(),s=[z,...s],z^o?s.pop():o=B(I++)),99);D() } ``` ``` <button id=run>run</button> ``` Slowed down version ``` // Mocking Node process = { stdin: { setRawMode: () => ({ on(_, callback) { addEventListener('keydown', e => callback(e.key)) } }) } } process.exit = () => { for (let i = 0; i < 9999; ++i) clearInterval(i) throw new Error('Game Over!') } // Allow restarting document.getElementById('run') .addEventListener('click', () => { for (let i = 0; i < 9999; ++i) clearInterval(i) main() }) function main() { // The game B=_=>s.includes(c=0|Math.random()*9)?B():c;D=_=>s.map((c)=>b[c]=+(s[0]==c),b=[...1e9-1+''],b[o]=2)+console.log(I+`\n ##${b.map((h,i)=>i%3?h:'#\n#'+h).join('')}#\n ###`);o=B(s=[I=0]);f='w';process.stdin.setRawMode(1).on('data',k=>f=k);setInterval(_=>D(s.includes(z=s[0]+{w:-3,s:3,a:-1,d:1}[f])|z<0|z>8|(z%3!=1&&s[0]%3+z%3==2)&&process.exit(),s=[z,...s],z^o?s.pop():o=B(I++)),299);D() } ``` ``` <button id=run>run</button> ``` [Answer] # [Haskell](https://www.haskell.org/), 579 bytes ``` import System.Process;import System.IO;p=('#'<$j)++"##\n";j=[0..20];r=fromEnum<$>withBinaryFile"/dev/urandom"ReadMode hGetChar;e(a,b)x|x=a|0<1=b;m s@(h@(x,y):t)d f=e(putStrLn"You Lost",do system"clear";putStr$foldr(++)p[show$length t,"\n",p,do y<-j;'#':[let z|elem(x,y)s='@'|f==(x,y)='F'|0<1=' 'in z|x<-j]++"#\n"];c<-hWaitForInput i 99;d<-e(getChar,pure d)c;a<-r;b<-r;let n|d>'s'=(x,y-1)|d>'r'=(x,y+1)|d>'a'=(x+1,y)|0<1=(x-1,y)in m(e(id,init)(h==f)$n:s)d$e((mod a 17+2,mod b 17+2),f)$h==f)$or[h`elem`t,x<0,y<0,x>20,y>20];main=hSetBuffering i NoBuffering>>m[(9,8)]'w'(9,8);i=stdin ``` [Try it online!](https://tio.run/##VVFtq9sgGP0rkgZUYnrb@2VrjaHcsY4Ldy@sH8boCtdWU@0SDWpu09H/3pkUBvugnCPnec45qLj/Lev6dtNNa10Am4sPspl@c/Ygvaf/vz5/pS1DcAKL9ISzLJlMfpmEnth2Np0@znbUscrZ5qPpmiItzzqoJ224u6x1LZMHId8eOseNsE3yXXLx2QoJ1CcZPijuqESc7HF/7Rm/zoo529MG@BVSK9STC14GLEDFJGq7sAnuxSQ/bQderA8JERb4MV5yqCV3Cb1r0srWwqEsw@3WK3tOa2mOQYFAkhiatMPcpchPNNZZbmsZwJ@rrGUz@nkGV/BaMTYyBtdwDAUB1Cbq@ji3G/rHTTt6KHL1g@uwtu7ZRHOgwWJBRZFLdLy3I23nJBD4QHmRO7ofrsHRXEUJPRxd8jkemLuz7M74wLJ5zDD6oz4fcMzQIIm0INrogJFirMKpWXosUolQYwXgYP4ueyQD3I8Qkyi5C63bqteh6msgfTEjl3j68jGCcvjEhmvD1EaGp66qpNPmGAt9sf9YWTZbtCDv8Q6e4QioZj4IbW63vw "Haskell – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 581 bytes ``` #define S++s;for(i=0,j=0;m[i][j];i=rand()%h)j=rand()%w;m[i][j]=2; #define F for(i=0;i<h;++i){for(j=0;j<w;++j) i,j,w=24,h=12;x=6,y=9;s;*t;c='w'; main(n){int m[h][w];for(memset(m,0,4*w*h);i<h;)*m[i++]=m[i][w-1]=1;for(srand(time(0));j<w;)j++[*m]=m[h-1][j]=1;m[y][x]=-1;S for(fcntl(0,4,2048);1;*t=-s){F n=m[i][j],putchar(n+s?n<0?'O':n-1?n-2?' ':'$':'#':'@');puts("");}printf("score:%d\n\n",s);usleep(200000);while(read(0,&n,1)+1)c=n-97&&n-'w'&&n-'s'&&n-'d'?c:n;c&2?y-=((c&4)-2)/2:(x-=(c&1)*2-1);t=m[y]+x;if(*t==2){S}else if(*t){puts("you died");break;}else F if(m[i][j]<0)++m[i][j];}}} ``` [Try it online!](https://tio.run/##NZJBr@IgEMfvforGt69lCmQLMbv7HEn35HUPHvt68FHc0rVoSk01xs/u0qokE2D4M/P7EzT/q/X9/laZnXUm2lDqcXfoiFUZa1SGbWHLoinRqm7rKgLvNTSv5fA6VRJnrwrr6Hkd7apGSi1cx8RYq1kNIdHAzLKGDUouWK2ExLP6wS7qAz2mPWqVDAnO2q11xMHVuj5qi7oshnLCak3rTU9alrFFOqQ1TF0gDSCUlmriGbgolZjkfiLtbWtIBjABQENpkbajtg7CkV4EH5eyOJeKC9xM/Dvt@j0JTZjMFr8ARWBT3MN1HTn1dM2Op17X24446nO3yvLkT7J0XOSOyzyJkmXyLcRbiN8JYBB7Mp8D3o5dcLUjc68PnVm@V5/u082ZBzz5vTFHIrNxAA613RvSmW0VQGLHBFABWjn@8TOOHQ/vNE3@MVVJrpcOdSzzC1eE6HgBXMJ3uSTnsNexgFRyAdir0S09o92RYEpJuG5uZu9NNCXg@iC9HE5RZU0ViL8Cwz98aNaj6vkAqwwofX2Q2@12v/8H "C (gcc) – Try It Online") Some bytes can be saved by replacing variables `w` and `h` with fixed values, and characters `O @#$` with two-digits integers, but I prefer to keep it as it is in order to make it easier to customize. ]
[Question] [ ## Challenge description For every positive integer `n` there exists a number having the form of `111...10...000` that is divisible by `n` i.e. a decimal number that starts with all `1`'s and ends with all `0`'s. This is very easy to prove: if we take a set of `n+1` different numbers in the form of `111...111` (all `1`'s), then at least two of them will give the same remainder after division by `n` (as per pigeonhole principle). The difference of these two numbers will be divisible by `n` and will have the desired form. Your aim is to write a program that finds this number. ## Input description A positive integer. ## Output description A number `p` in the form of `111...10...000`, such that `p ≡ 0 (mod n)`. If you find more than one - display any of them (doesn't need to be the smallest one). ## Notes Your program has to give the answer in a reasonable amount of time. Which means brute-forcing is not permited: ``` p = 0 while (p != 11..10.00 and p % n != 0) p++ ``` Neither is this: ``` do p = random_int() while (p != 11..10.00 and p % n != 0) ``` Iterating through the numbers in the form of `11..10..00` is allowed. Your program doesn't need to handle an arbitrarily large input - the upper bound is whatever your language's upper bound is. ## Sample outputs ``` 2: 10 3: 1110 12: 11100 49: 1111111111111111111111111111111111111111110 102: 1111111111111111111111111111111111111111111111110 ``` [Answer] ## Mathematica, 29 bytes ``` ⌊10^(9EulerPhi@#)/9⌋10^#& ``` Code by [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner). On input \$n\$, this outputs the number with \$9\varphi(n)\$ ones followed by \$n\$ zeroes, where \$\varphi(\cdot)\$ is the [Euler totient function](https://en.wikipedia.org/wiki/Euler%27s_totient_function). With a function `phi`, this could be expressed in Python as ``` lambda n:'1'*9*phi(n)+'0'*n ``` It would suffice to use the factorial \$n!\$ instead of \$\varphi(n)\$, but printing that many ones does not have a reasonable run-time. *Claim:* \$9\varphi(n)\$ ones followed by \$n\$ zeroes is a multiple of \$n\$. *Proof:* First, let's prove this for the case that \$n\$ is not a multiple of \$2, 3, \text{or } 5\$. We'll show the number with consisting of \$\varphi(n)\$ ones is a multiple of \$n\$. The number made of \$k\$ ones equals \$\frac{10^k-1}9\$. Since \$n\$ is not a multiple of \$3\$, this is a multiple of \$n\$ as long as \$10^k-1\$ is a factor of \$n\$, or equivalently if \$10^k \equiv 1\mod n\$. Note that this formulation makes apparent that if \$k\$ works for the number of ones, then so does any multiple of \$k\$. So, we're looking for \$k\$ to be a multiple of the [order](https://en.wikipedia.org/wiki/Order_(group_theory)) of \$k\$ in the [multiplicative group modulo n](https://en.wikipedia.org/wiki/Multiplicative_group_of_integers_modulo_n). By [Lagrange's Theorem](https://en.wikipedia.org/wiki/Lagrange%27s_theorem_(group_theory)), any such order is a divisor of the size of the group. Since the elements of the group are the number from \$1\$ to \$n\$ that are relatively prime to \$n\$, its size is the [Euler totient function](https://en.wikipedia.org/wiki/Euler%27s_totient_function) \$\varphi(n)\$. So, we've shown that \$10^{\varphi(n)} \equiv 1 \mod n\$, and so the number made of \$\varphi(n)\$ ones is a multiple of \$n\$. Now, let's handle potential factors of \$3\$ in \$n\$. We know that \$10^{\varphi(n)}-1\$ is a multiple of \$n\$, but \$\frac{10^{\varphi(n)}-1}9\$ might not be. But, \$\frac{10^{9\varphi(n)}-1}9\$ is a multiple of \$9\$ because it consists of \$9\varphi(n)\$ ones, so the sum of its digits a multiple of \$9\$. And we've noted that multiplying the exponent \$k\$ by a constant preserves the divisibility. Now, if \$n\$ has factors of \$2\$'s and \$5\$'s, we need to add zeroes to end of the output. It way more than suffices to use \$n\$ zeroes (in fact \$\log\_2(n)\$ would do). So, if our input \$n\$ is split as \$n = 2^a \times 5^b \times m\$, it suffices to have \$9\varphi(m)\$ ones to be a multiple of \$n\$, multiplied by \$10^n\$ to be a multiple of \$2^a \times 5^b\$. And, since \$n\$ is a multiple of \$m\$, it suffices to use \$9\varphi(n)\$ ones. So, it works to have \$9\varphi(n)\$ ones followed by \$n\$ zeroes. [Answer] ## Python 2, 44 bytes ``` f=lambda n,j=1:j/9*j*(j/9*j%n<1)or f(n,j*10) ``` When `j` is a power of 10 such as 1000, the floor-division `j/9` gives a number made of 1's like 111. So, `j/9*j` gives 1's followed by an equal number of 0's like 111000. The function recursively tests numbers of this form, trying higher and higher powers of 10 until we find one that's a multiple of the desired number. [Answer] # Pyth, 11 bytes ``` .W%HQsjZ`TT ``` [Test suite](https://pyth.herokuapp.com/?code=.W%25HQsjZ%60TT&test_suite=1&test_suite_input=2%0A3%0A49%0A102&debug=0) Basically, it just puts a 1 in front and a 0 in back over and over again until the number is divisible by the input. Explanation: ``` .W%HQsjZ`TT Implicit: Q = eval(input()), T = 10 .W while loop: %HQ while the current value mod Q is not zero jZ`T Join the string "10" with the current value as the separator. s Convert that to an integer. T Starting value 10. ``` [Answer] # Haskell, 51 bytes ``` \k->[b|a<-[1..],b<-[div(10^a)9*10^a],b`mod`k<1]!!0 ``` Using xnor’s approach. nimi saved a byte! [Answer] ## CJam, ~~28~~ ~~25~~ 19 bytes *Saved 6 bytes with xnor's observation that we only need to look at numbers of the form `1n0n`.* ``` ri:X,:)Asfe*{iX%!}= ``` [Test it here.](http://cjam.aditsu.net/#code=Asri%3AX%2C%3A)ff*%3Am*%3As%3A~%7BX%25!%7D%3D&input=49) ### Explanation ``` ri:X e# Read input, convert to integer, store in X. ,:) e# Get range [1 ... X]. As e# Push "10". fe* e# For each N in the range, repeat the characters in "10" that many times, e# so we get ["10" "1100" "111000" ...]. {iX%!}= e# Select the first element from the list which is divided by X. ``` [Answer] # JavaScript (ES6), 65 bytes **Edit** 2 bytes saved thx @Neil It works within the limits of javascript numeric type, with 17 significant digits. (So quite limited) ``` a=>{for(n='';!(m=n+=1)[17];)for(;!(m+=0)[17];)if(!(m%a))return+m} ``` **Less golfed** ``` function (a) { for (n = ''; !(m = n += '1')[17]; ) for (; !(m += '0')[17]; ) if (!(m % a)) return +m; } ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~11~~ 10 bytes *-1 byte thanks to [Razetime](https://codegolf.stackexchange.com/users/80214)!* ``` ḟ¦⁰modṘḋ2N ``` [Try it online!](https://tio.run/##AR8A4P9odXNr///huJ/CpuKBsG1vZOG5mOG4izJO////MTAy "Husk – Try It Online") Constructs the infinite list `[10,1100,111000,...]` and selects the first element which is a multiple of the argument. [Answer] # Mathematica, ~~140~~ 55 bytes ``` NestWhile["1"<>#<>"0"&,"1",FromDigits@#~Mod~x>0&/.x->#] ``` Many bytes removed thanks to xnor's 1^n0^n trick. **Minimal value, ~~140~~ 156 bytes** This gives the smallest possible solution. ``` NestWhile["1"<>#&,ToString[10^(Length@NestWhileList[If[EvenQ@#,If[10~Mod~#>0,#/2,#/10],#/5]&,#,Divisors@#~ContainsAny~{2, 5}&],FromDigits@#~Mod~m>0&/.m->#]& ``` It calculates how many zeros are required then checks all possible `1` counts until it works. It can output a number with no 0 but that can be fixed by adding a `<>"0"` right before the final `&`. [Answer] ## Haskell, 37 bytes ``` f n=[d|d<-"10",i<-[1..n*9],gcd n i<2] ``` This uses the [fact](https://codegolf.stackexchange.com/a/74403/20260) that it works to have `9*phi(n)` ones, where `phi` is the Euler totient function. Here, it's implemented using `gcd` and filtering, producing one digit for each value `i` that's relatively prime to it that is in the range `1` and `9*n`. It also suffices to use this many zeroes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ⁵DxⱮḅ⁵ḍ@Ƈ⁸Ḣ ``` [Try it online!](https://tio.run/##y0rNyan8//9R41aXikcb1z3c0QpkPtzR63Cs/VHjjoc7Fv3//98YAA "Jelly – Try It Online") Ignoring runtime requirements, we can reduce this to 10 bytes using [xnor](https://codegolf.stackexchange.com/a/74403/66833)'s method, but with \$\varphi(n)\$ replaced with \$n!\$: ``` !,µ⁵Dx"µFḌ ``` [Try it online!](https://tio.run/##y0rNyan8/19R59DWR41bXSqUDm11e7ij5////8YA "Jelly – Try It Online") ## How they work ``` ⁵DxⱮḅ⁵ḍ@Ƈ⁸Ḣ - Main link. Takes n on the left ⁵D - Yield [1, 0] Ɱ - For each integer i in [1, 2, ..., n]: x - Repeat each element of [1, 0] i times ḅ⁵ - Convert each back into an integer Ƈ - Keep those for which the following is true: ḍ@ - Is divisible by ⁸ - n Ḣ - Take the first value of those remaining ``` ``` !,µ⁵Dx"µFḌ - Main link. Takes n on the left ! - Yield n! , - Yield [n!, n]. Call this l µ - Begin new link with l on the left ⁵D - Yield [1, 0] " - Zip [1, 0] with [n!, n] and do the following over each pair: x - Repeat - This yields [[1, 1, ..., 1], [0, 0, ..., 0]]. The first element has n! 1s and the second n 0s Call this k µ - Begin new link with k on the left F - Flatten k Ḍ - Convert to integer ``` [Answer] # Perl 5, 26 bytes includes a byte for `-n` (`-M5.01` is free) ``` ($.="1$.0")%$_?redo:say$. ``` ## Explanation [`$.`](https://perldoc.perl.org/perlvar#Variables-related-to-filehandles) starts off with value 1. We immediately concatenate it with 1 beforehand and 0 afterward, yielding 110, and reassign that to `$.` — that's what the `$.="1$.0"` does. The assignment returns the assigned value so when we take it modulo the input number `$_` we obtain 0 (false) if 110 is divisible by the input and nonzero (true) otherwise. * In the latter case, we `redo`, i.e. repeat the block (the [`-n`](https://perldoc.perl.org/perlrun#Command-Switches) switch makes the whole thing a loop block, and incidentally, assigns `$_` to the input number). This concatenates another 1 and 0, yielding 11100, etc. * If 110, or 11100, or 1111000, or whatever we're up to, is divisible by the input, we stop and `say` (print) it. Note that every number divides such a number (i.e. that has one more 1 than the numbers of 0s it has). After all, if it divides something with more 1s than 0s, you can append 0s and it'll still divide that. And if divides something with fewer 1s than 0s, say *m* 1s and *n* 0s with *m* < *n*, then it also divides the number with 2*m* 1s and *n* 0s. [Answer] ## Sage, 33 bytes ``` lambda n:'1'*9*euler_phi(n)+'0'*n ``` This uses [xnor's method](https://codegolf.stackexchange.com/a/74403/45941) to produce the output. [Try it online](http://sagecell.sagemath.org/?z=eJxLs81JzE1KSVTIs1I3VNey1EotzUktii_IyNTI09RWN1DXyuPl4uUqSS0uKVawVYg20lEw1lEwBFImlkDawCgWJJ2WX6QAUqKQmQemi614uRSAoKAoM69EIU0DJKapA5Qt0YByNBVUITpsbRUMAI-BJMY=&lang=sage) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` $Õ9*×Î׫ ``` Port of [*@xnor*'s Mathematica answer](https://codegolf.stackexchange.com/a/74403/52210), so make sure to upvote him!! [Try it online](https://tio.run/##yy9OTMpM/f9f5fBUS63D0w/3HZ5@aPX//4ZGAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLl/TesPDzVUuvwdIPKw9MPrf6vc2ib/f9oIx1jHUMjHRNLHUMDo1gA). **Explanation:** ``` $ # Push 1 and the input-integer Õ # Pop the input, and get Euler's totient of this integer 9* # Multiply it by 9 × # Repeat the 1 that many times as string Î # Push 0 and the input-integer × # Repeat the 0 the input amount of times as string « # Concatenate the strings of 1s and 0s together # (after which the result is output implicitly) ``` --- A more to-the-point iterative approach would be **11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**: ``` TS∞δ×øJ.ΔIÖ ``` [Try it online](https://tio.run/##AR4A4f9vc2FiaWX//1RT4oiezrTDl8O4Si7OlEnDlv//MTI) or [verify all test cases](https://tio.run/##AToAxf9vc2FiaWX/dnk/IiDihpIgIj95Vf9UU@KIns60w5fDuEouzpRYw5b/fSz/WzIsMywxMiw0OSwxMDJd). **Explanation:** ``` T # Push 10 S # Convert it to a list of digits: [1,0] ∞ # Push an infinite positive list: [1,2,3,...] δ # Apply double-vectorized on these two lists: × # Repeat the 1 or 0 that many times as string # (we now have a pair of infinite lists: [[1,11,111,...],[0,00,000,...]]) ø # Zip/transpose; swapping rows/columns: # [[1,0],[11,00],[111,000],...] J # Join each inner pair together: # [10,1100,111000,...] .Δ # Find the first value in this list which is truthy for: IÖ # Check that it's divisible by the input-integer # (after which the result is output implicitly) ``` [Answer] # bc, 58 bytes ``` define f(n){for(x=1;m=10^x/9*10^x;++x)if(m%n==0)return m;} ``` ## Sample results ``` 200: 111000 201: 111111111111111111111111111111111000000000000000000000000000000000 202: 11110000 203: 111111111111111111111111111111111111111111111111111111111111111111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000 204: 111111111111111111111111111111111111111111111111000000000000000000000000000000000000000000000000 205: 1111100000 206: 11111111111111111111111111111111110000000000000000000000000000000000 207: 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 208: 111111000000 209: 111111111111111111000000000000000000 210: 111111000000 211: 111111111111111111111111111111000000000000000000000000000000 212: 11111111111110000000000000 213: 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 214: 1111111111111111111111111111111111111111111111111111100000000000000000000000000000000000000000000000000000 215: 111111111111111111111000000000000000000000 216: 111111111111111111111111111000000000000000000000000000 217: 111111111111111111111111111111000000000000000000000000000000 218: 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 219: 111111111111111111111111000000000000000000000000 ``` [Answer] # dc, 27 bytes ``` Odsm[O*lmdO*sm+O*dln%0<f]sf ``` This defines a function `f` that expects its argument in the variable `n`. To use it as a program, `?sn lfx p` to read from stdin, call the function, and print the result to stdout. Variable `m` and top of stack must be reset to 10 (by repeating `Odsm`) before `f` can be re-used. ## Results: ``` 200: 111000 201: 111111111111111111111111111111111000000000000000000000000000000000 202: 11110000 203: 111111111111111111111111111111111111111111111111111111111111111111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000 204: 111111111111111111111111111111111111111111111111000000000000000000000000000000000000000000000000 205: 1111100000 206: 11111111111111111111111111111111110000000000000000000000000000000000 207: 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 208: 111111000000 209: 111111111111111111000000000000000000 210: 111111000000 211: 111111111111111111111111111111000000000000000000000000000000 212: 11111111111110000000000000 213: 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 214: 1111111111111111111111111111111111111111111111111111100000000000000000000000000000000000000000000000000000 215: 111111111111111111111000000000000000000000 216: 111111111111111111111111111000000000000000000000000000 217: 111111111111111111111111111111000000000000000000000000000000 218: 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 219: 111111111111111111111111000000000000000000000000 ``` ]
[Question] [ Given an input of a list of slices of a string, output the original string. Each slice will be given as a list of length 2, containing the start position of the slice (an integer ≥0) and the slice itself. If your language does not support arrays of arbitrary types, you may also take this as a struct or similar, or simply a string consisting of the number, a space, and then the slice. The order of the two elements of each slice is up to you. Furthermore, if you choose to use the representation of slices as a length-2 array, you may take input as either a 2-dimensional array or a single flat array. Finally, the integer representing position may be either zero-indexed or one-indexed (all the examples here are zero-indexed). The input will always be sufficient to determine the entire string up to the highest position given. That is, there will be no "holes" or "gaps." Therefore, the output must not contain any extra trailing or leading characters (other than the typical optional trailing newline). The input will always be consistent, and no slices will conflict with each other. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes will win. Test cases: ``` In Out ----------------------------------------------------------- [[2, "CG"], [0, "PP"], [1, "PC"]] | PPCG [[0, "foobarbaz"]] | foobarbaz [[0, "foobar"], [6, "baz"]] | foobarbaz [[2, "ob"], [5, "rba"], [0, "fooba"], [8, "z"]] | foobarbaz [[0, "fo"], [0, "fooba"], [0, "foobarbaz"]] | foobarbaz ``` [Answer] ## Python 2, 49 bytes ``` lambda l:`map(max,*[' '*n+s for n,s in l])`[2::5] ``` First, lines up the strings by padding their offsets with spaces (shown as underscores for clarity) ``` [[2, "CG"], [0, "PP"], [1, "PC"]] __CG PP _PC ``` Then, uses `map` to `zip` and take the maximum of each column, which ignores the smaller values of spaces (the smallest printable character) and `None`s where some strings were too short. ``` __CG PP _PC PPCG ``` Finally, `''.join` to a string using the `[2::5]` trick. [Answer] ## Haskell, 57 bytes ``` import Data.List map snd.sort.nub.(>>= \(n,s)->zip[n..]s) ``` Usage example: ``` *Main> map snd.sort.nub.(>>= \(n,s)->zip[n..]s) $ [(2,"CG"),(0,"PP"),(1,"PC")] "PPCG" ``` How it works: make pairs of `(index,letter)` for every letter of every slice, concatenate into a single list, remove duplicates, sort by index, remove indices. [Answer] # Perl, 25 Added +2 for `-lp` Get the input from STDIN, e.g. ``` perl -lp slices.pl 2 CG 0 PP 1 PC ``` (Close with ^D or ^Z or whatever closes STDIN on your system) `slices.pl`: ``` / /;$r|=v0 x$`.$'}{*_=r ``` [Answer] ## JavaScript (ES6), 61 bytes ``` a=>a.map(([o,s])=>[...s].map(c=>r[o++]=c),r=[])&&r.join`` ``` Edit: Saved 4 bytes thanks to @edc65. [Answer] # Jelly, ~~10~~ 9 bytes ``` Ḣ0ẋ;Fµ€o/ ``` [Try it online!](http://jelly.tryitonline.net/#code=4biiMOG6iztGwrXigqxvLw&input=&args=W1syLCAib2IiXSwgWzUsICJyYmEiXSwgWzAsICJmb29iYSJdLCBbOCwgInoiXV0) ### How it works ``` Ḣ0ẋ;Fµ€o/ Main link. Input: A (list of pairs) µ€ Convert the chain to the left into a link, and apply it to each pair. Ḣ Pop the first element. 0ẋ Yield a list of that many zeroes. ;F Concatenate the list of zeroes with the popped, flattened pair. o/ Reduce the generated lists by logical OR. Since all characters are truthy, this overwrites zeroes with characters, but never characters with zeroes. ``` [Answer] # [Factor](https://factorcode.org), 64 40 bytes ``` [ sbuf new tuck '[ _ copy ] assoc-each ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZZA9CsIwHMXp6ikeWXQRVFCKjh3ERQRxKkXSkGBRm5q0iEpP4tJFD-Bt9DSmjVSqyZAH7_f-H7neBWWpVMXLcVbL2Xw6hlAnbLmK-Q6aHzIeM65BtZZMI5LQYSY0Jq1LC-ZczCXelGCAvJSLBUHvIz2CvpH5FxRShlSF9GyhP6fOVsioiciw7mJKEAytrpJ10MTc38q12UT_hslvWSq67rPjV0si5kekGdui7WMNJpMTAvsRXU7ZBoHlH3uawEeiojg1QGlZoyjs-wY) This answer makes use of the fact you can set arbitrary indices of a growable sequence (in this case a string buffer) and the sequence will expand appropriately with default values. `copy` copies one sequence to another starting at an index; a perfect fit for this problem. [Answer] # [MATL](https://esolangs.org/wiki/MATL), 15 bytes ``` ''i"@Y:Y:tn:b+( ``` Works with [current version (13.0.0)](https://github.com/lmendo/MATL/releases/tag/13.0.0) of the language/compiler. Input is with curly braces and single quotes. (Curly braces in MATLAB/MATL define *cell arrays*, which are lists that can have contents of arbitrary, possibly different types.) The test cases are thus: ``` {{2, 'CG'}, {0, 'PP'} {1, 'PC'}} {{0, 'foobarbaz'}} {{0, 'foobar'}, {6, 'baz'}} {{2, 'ob'}, {5, 'rba'}, {0, 'fooba'}, {8, 'z'}} {{0, 'fo'}, {0, 'fooba'}, {0, 'foobarbaz'}} ``` [**Try it online!**](http://matl.tryitonline.net/#code=JydpIkBZOlk6dG46Yiso&input=e3syLCAnb2InfSwgezUsICdyYmEnfSwgezAsICdmb29iYSd9LCB7OCwgJ3onfX0) ``` '' % push empty string. This will be filled with the slices to produce the result i % take input: cell array of cell arrays. For example: {{0, 'foobar'}, {6, 'baz'}} " % for each (1st-level) cell @ % push that cell. Example: {{0, 'foobar'}} Y: % unpack (1st-level) cell, i.e. push its contents. Example: {0, 'foobar'} Y: % unpack (2nd-level) cell array: gives number and substring. Example: 0, 'foobar' tn: % duplicate substring and generate vector [1,2,...,n], where n is length of % current substring (in the example: 6) b+ % add input number that tells the position of that substring within the whole % string (in the example: 0; so this gives [1,2,...,6] again) ( % assign substring to the total string, overwriting if necessary. Note that % MATL uses 1-indexing % end for each % implicit display ``` [Answer] # [J](http://jsoftware.com/), 24 bytes ``` [:u:3>./@u:-@(+#&>){.&>] ``` [Try it online!](https://tio.run/##VY3BCoJAEIbvPsVosKukqyZJDrVIQl0ipKsJq5FEl4XAi0avbqtmIMNcvu//Z55dpKOfhzpGlGoGoxXsECjY4AGqdRgkl9Ohy7DGgDM3rtGJzeWCcKtlhOedpZ33DLw2wyt@DJ@w9zww6Aw5I8wMSI2WO9fa/faQsFKvfKggOYo0FWkyUtP2LAW3tJKyLF5l0dBReBAqPlKh8HRkrcxGGVkKlRZDQDRTp5@@9eP/o90X "J – Try It Online") ## alternative, 24 bytes ``` [:u:[:>./(#&0@[,3 u:])&> ``` [Try it online!](https://tio.run/##bY7BCoJAEIbvPsVksOuSrmuS1FAiCXWJkK4mrEYSXYTAi0avbmNWEMQwl@/752eu3WKEXhaMcMG5YUpewgqBgw0KkNaREB92my7FGlMMpWuNmYpS24caM8HCThj7tYRe@2SjGp3ImoxZKFrJwuwlVZviER@mx@T9j@5rmbR8VqNwf7VxPl0qmNIfHpQQb3WS6CQeqGUrQXDJy6oq8luRN3wQCgLiA9WEPyUzMnMyVaEprV8B3Xxu@umv3vxb2j0B "J – Try It Online") [Answer] # [DUP](https://esolangs.org/wiki/DUP), 14 bytes ``` [0[$;$][,1+]#] ``` `[Try it here.](http://www.quirkster.com/iano/js/dup.html)` Anonymous lambda. Usage: ``` 2"CG"0"PP"1"PC"[0[$;$][,1+]#]! ``` NOTE: DUP does not really have arrays, so I hope this input format is okay. # Explanation Well, DUP's string comprehension is... interesting. Strings are stored as a series of number variables, each of which holds a charcode from the string. Something like `2"CG"` works as pushing 2 to the stack, then creating a string with index starting from 2. Because these indexes are really variables, they can be overwritten. That's what the input is really doing: overriding! Try pressing `Step` on the interpreter site to get a better idea for this. After this, we get an unsliced string. This is where the outputting comes in. ``` [ ] {lambda} 0 {push 0 to the stack as accumulator} [ ][ ]# {while loop} $;$ {duplicate, get var at TOS value, see if that var is defined} ,1+ {if so, output charcode at TOS and increment accumulator} ``` [Answer] # PHP, 146 chars Note: Evaling user input is *always* a good idea. ## Golfed ``` <?$a=[];$f=0;eval("\$b={$argv[1]};");foreach($b as$d){$f=$d[0];$e=str_split($d[1]);foreach($e as$c){$a[$f++]=$c;}}ksort($a);echo join('',$a)."\n"; ``` ## Ungolfed ``` <?php $array = array(); $p = 0; eval("\$input = {$argv[1]};"); foreach($input as $item) { $p = $item[0]; $str = str_split($item[1]); foreach($str as $part) { $array[$p++] = $part; } } ksort($array); echo join('', $array)."\n"; ?> ``` You can see that I'm just writing the input into an array with the specific key each char has and then output it all. ## Tests `php unslice.php '[[0, "foobar"], [6, "baz"]]'` -> foobarbaz `php unslice.php '[[2, "CG"], [0, "PP"], [1, "PC"]]'` -> PPCG `php shorten.php unslice.php` -> Shortened script by 107 chars. :D [Answer] # [Ruby](https://www.ruby-lang.org/), 40 bytes ``` ->a{s="" a.sort.map{s[_1,_2.size]=_2} s} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3NXTtEquLbZWUuBL1ivOLSvRyEwuqi6PjDXXijfSKM6tSY23jjWq5imuh6q8UlJYUK7hFR0cb6SgoObsrxeooRBsAmQEBYKYhiOmsFBsbywVXCZJOy89PSixKSqzCJQXWbQbkYqgBWZSfBJY3BTKBhsAtBWsF8yyAPKxmY1GL4R6I3xYsgNAA) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 6 bytes ``` ∩÷-∩vG ``` [Try it online! (test suite)](https://vyxal.pythonanywhere.com/#WyJzQSIsIiIsIuKIqcO3LeKIqXZHIiwiIiwiW1syLCBcIkNHXCJdLCBbMCwgXCJQUFwiXSwgWzEsIFwiUENcIl1dXG5bWzAsIFwiZm9vYmFyYmF6XCJdXVxuW1swLCBcImZvb2JhclwiXSwgWzYsIFwiYmF6XCJdXVxuW1syLCBcIm9iXCJdLCBbNSwgXCJyYmFcIl0sIFswLCBcImZvb2JhXCJdLCBbOCwgXCJ6XCJdXVxuW1swLCBcImZvXCJdLCBbMCwgXCJmb29iYVwiXSwgWzAsIFwiZm9vYmFyYmF6XCJdXSJd) Input as a list of `[num, str]`. **Explanation:** ``` ∩÷-∩vG # whole program ∩ # transpose (num and str in their own groups) ÷ # split into each item - # prepend '-' to str num amount of times (vectorises) ∩ # transpose v # for each item (i.e. vectorise next element) G # get max char # s flag: concatenate list into a string, then print ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-mh`](https://codegolf.meta.stackexchange.com/a/14339/), ~~15~~ 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` P=úUÎÄ hUÎUÌ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW1o&code=UD36Vc7EIGhVzlXM&input=W1syLCAib2IiXSwgWzUsICJyYmEiXSwgWzAsICJmb29iYSJdLCBbOCwgInoiXV0KLVE) ``` P=úUÎÄ hUÎUÌ :Implicit map of each array U in input array W P= :Assign to P (an empty string, initially) ú :Right pad P with spaces to length UÎ : First element of U Ä : Add 1 h :Replace the characters starting at index UÎ : First element of U UÌ : With last element of U :Implicit output of last element of resulting array ``` [Answer] ## Seriously, 48 bytes ``` ,`i@;l(;)+(x@#@k`M;`i@X@M`MMu' *╗`iZi`M`i╜T╗`MX╜ ``` Seriously is *seriously* bad at string manipulation. [Try it online!](http://seriously.tryitonline.net/#code=LGBpQDtsKDspKyh4QCNAa2BNO2BpQFhATWBNTXUnICrilZdgaVppYE1gaeKVnFTilZdgTVjilZw&input=W1syLCAib2IiXSwgWzUsICJyYmEiXSwgWzAsICJmb29iYSJdLCBbOCwgInoiXV0) Explanation: ``` ,`i@;l(;)+(x@#@k`M;`i@X@M`MMu' *╗`iZi`M`i╜T╗`MX╜ , get input ` `M; perform the first map and dupe ` `MM perform the second map, get max element u' *╗ increment, make string of that many spaces, save in reg 0 ` `M third map ` `M fourth map X╜ discard and push register 0 ``` Map 1: ``` i@;l(;)+(x@#@k i@;l flatten, swap, dupe string, get length (;)+( make stack [start, end, str] x@#@k push range(start, end), explode string, make list of stack ``` Map 2: ``` i@X@M i@X flatten, swap, discard (discard the string) @M swap, max (take maximum element from range) ``` Map 3: ``` iZi flatten, zip, flatten (make list of [index, char] pairs) ``` Map 4: ``` i╜T╗ flatten, push reg 0, set element, push to reg 0 ``` In a nutshell, this program makes a string with `n` spaces, where `n` is the minimum length the string can be based on the input. It determines the index in the result string of each character in each slice, and sets the character in the result string at that index to the character. [Answer] # Python, 91 bytes. Saved 1 byte thanks to cat. It's a bit long. I'll golf it down more in a bit. ``` def f(x):r={j+i:q for(i,s)in x for j,q in enumerate(s)};return"".join(map(r.get,sorted(r))) ``` [Answer] ## Python, ~~119~~ 115 bytes ``` def f(x,s=""): x.sort() for e in x: a=e[0];b=e[1] for i,c in enumerate(b): if len(s)<=(i+a):s+=c return s ``` ### Test cases [![enter image description here](https://i.stack.imgur.com/oBxAD.png)](https://i.stack.imgur.com/oBxAD.png) [Answer] # [Japt](https://github.com/ETHproductions/japt), 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ñÎrÈ+S hYÌYg)x}P ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=8c5yyCtTIGhZzFlnKXh9UA&input=WwpbWzIsICJDRyJdLCBbMCwgIlBQIl0sIFsxLCAiUEMiXV0KW1swLCAiZm9vYmFyYmF6Il1dCltbMCwgImZvb2JhciJdLCBbNiwgImJheiJdXQpbWzIsICJvYiJdLCBbNSwgInJiYSJdLCBbMCwgImZvb2JhIl0sIFs4LCAieiJdXQpbWzAsICJmbyJdLCBbMCwgImZvb2JhIl0sIFswLCAiZm9vYmFyYmF6Il1dCl0tbVI) Explanation: ``` ñÎrÈ+S hYÌYg)x}P P # Starting with an empty string X r } # For each item Y in: ñ # Input sorted by Î # The first item in each sub-array È # Apply the following to X: +S # Add a space to the end h ) # Overwrite: Yg # Starting index is the first item in Y YÌ # New characters are the last item in Y x # Trim any leftover whitespace ``` Unfortunately `h` wraps its index, so attempting to write new characters at the end of a string with it instead writes them back at the start. [Answer] # [QBasic](https://en.wikipedia.org/wiki/QBasic), ~~127~~ 114 bytes ``` INPUT n FOR j=1TO n INPUT i LINE INPUT s$ l=LEN(s$) e=LEN(r$)-i-l r$=r$+SPACE$(e*(e<0)) MID$(r$,i+1,l)=s$ NEXT ?r$ ``` You can try it at [Archive.org](https://archive.org/details/msdos_qbasic_megapack). The input format is: first, [the number of slices](https://codegolf.meta.stackexchange.com/a/24639/16766); then, for each slice, the (0-based) index and the string on separate lines. Here's what running the first test case would look like: ``` ? 3 ? 2 CG ? 0 PP ? 1 PC PPCG ``` ### Explanation ``` INPUT n ``` Input the number of slices as `n`. ``` FOR j = 1 TO n ... NEXT ``` Loop `n` times: ``` INPUT i ``` Input the starting index of the next slice as `i`. ``` LINE INPUT s$ ``` Input the contents of the slice as `s$`. `LINE INPUT` is used to make sure that any printable ASCII character can be included in the input; if characters like `,` and `"` could be excluded, the two input statements could be combined as `INPUT i,s$`, saving 11 bytes. ``` l = LEN(s$) ``` Store the length of the slice as `l`. ``` e=LEN(r$)-i-l ``` The result string is stored in `r$` (initially empty by default). If merging this slice would extend `r$` beyond its current length, the number of characters we would need to add is given by `i` plus `l` minus the current length of `r$`. Calculate this amount, negated (see below for why), and store it as `e`. ``` r$ = r$ + SPACE$(e * (e < 0)) ``` Pad `r$` as necessary by appending spaces to it. Comparison operators in QBasic return -1 for true and 0 for false. Thus, if `e < 0`, we append `-e` spaces; otherwise, we append `0` spaces. ``` MID$(r$, i + 1, l) = s$ ``` Overwrite `l` characters of `r$`, starting at index `i + 1` (since `MID$` uses 1-based indexing), with the contents of `s$`. ``` PRINT r$ ``` After the loop finishes, print the final value of `r$`. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 13 bytes ``` meSd.Tm+*;hde ``` [Test suite](https://pythtemp.herokuapp.com/?code=meSd.Tm%2B%2a%3Bhde&test_suite=1&test_suite_input=%5B%5B2%2C+%22CG%22%5D%2C+%5B0%2C+%22PP%22%5D%2C+%5B1%2C+%22PC%22%5D%5D%0A%5B%5B0%2C+%22foobarbaz%22%5D%5D%0A%5B%5B0%2C+%22foobar%22%5D%2C+%5B6%2C+%22baz%22%5D%5D%0A%5B%5B2%2C+%22ob%22%5D%2C+%5B5%2C+%22rba%22%5D%2C+%5B0%2C+%22fooba%22%5D%2C+%5B8%2C+%22z%22%5D%5D%0A%5B%5B0%2C+%22fo%22%5D%2C+%5B0%2C+%22fooba%22%5D%2C+%5B0%2C+%22foobarbaz%22%5D%5D&debug=0) Takes input as a list of elements of the structure `[index, string]`. Outputs a list of characters. ##### Explanation: ``` meSd.Tm+*;hde | Full code meSd.Tm+*;hdedQ | with implicit variables ----------------+------------------------------------------------ m Q | Map over the input: + ed | Prepend the string with *;hd | <index> spaces .T | Ragged transpose meSd | Take the lexicographically last element of each ``` [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ε`ú}ζ€à ``` Output as a list of characters. [Try it online](https://tio.run/##MzBNTDJM/f//3NaEw7tqz2171LTm8IL//6OjjXSU8pOUYnWiTXWUipISQSwDHaW0/HwI20JHqUopNhYA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfeX/c1sTDu@qPbftUdOawwv@u9h7KSloHN6vqaTzPzo62khHydldKVYn2kBHKSAAxDAEMpyVYoEskFhafn5SYlFSYhWaCEilmY4SXAJoTn4SSNBURwmoHGoiWC2IbaGjhGwCujSaRbEA). **Explanation:** Uses the legacy version of 05AB1E instead of the new one for two reasons: 1. The zip/transpose builtins work on a list of strings, whereas the new version would require a list of lists of characters. 2. The minimum/maximum builtins work on characters (using their codepoint), which doesn't work in the new version. ``` ε # Map over each pair of the (implicit) input-list: ` # Pop the pair and push both values separated to the list ú # Pad the string with the integer amount of leading spaces }ζ # After the map: zip/transpose the strings, swapping rows/columns, using a default # space " " filler if strings are of unequal length € # Map over each string à # Only leave its maximum character # (after which the resulting list of characters is output implicitly) ``` [Answer] ## CJam, 26 bytes ``` q~{~0c*\+}%{.{s\s|}}*e_0c- ``` [Try it online!](http://cjam.aditsu.net/#code=q~%7B~0c*%5C%2B%7D%25%7B.%7Bs%5Cs%7C%7D%7D*e_0c-&input=%5B%5B%22CG%222%5D%5B%22PP%220%5D%5B%22PC%221%5D%5D%20). Takes input in form `[["CG"2]["PP"0]["PC"1]]`. Explanation: ``` q~ Read and eval input {~0c*\+}% Convert input strings into workable format { }% Map onto each input ~ Evaluate 0c Null character *\+ Multiply by input number and concat to string {.{s\s|}}* Combine strings { }* Fold array .{ } Vectorize, apply block to corresponding elements of arrays s\s Convert elements to strings | Set Union e_0c- Remove null characters ``` [Answer] ## R, 181 bytes ``` n=nchar;m=matrix(scan(,'raw'),ncol=2,byrow=T);w=rep('',max(n(m[,2])+(i<-strtoi(m[,1]))));for(v in 1:nrow(m)) w[seq(i[v]+1,l=n(m[v,2]))]=unlist(strsplit(m[v,2],''));cat("",w,sep="") ``` With line breaks: ``` n=nchar m=matrix(scan(,'raw'),ncol=2,byrow=T) w=rep('',max(n(m[,2])+(i<-strtoi(m[,1])))) for(v in 1:nrow(m)) w[seq(i[v]+1,l=n(m[v,2]))]=unlist(strsplit(m[v,2],'')) cat("",w,sep="") ``` Works in R Gui (single line one, or sourcing for the multi-line one) but not in ideone, example: ``` > n=nchar;m=matrix(scan(,'raw'),ncol=2,byrow=T);w=rep('',max(n(m[,2])+(i<-strtoi(m[,1]))));for(v in 1:nrow(m)) w[seq(i[v]+1,l=n(m[v,2]))]=unlist(strsplit(m[v,2],''));cat("",w,sep="") 1: 2 ob 5 rba 0 fooba 8 z 9: Read 8 items foobarbaz ``` Note on the input method: > > or simply a string consisting of the number, a space, and then the slice. > > > I assume I comply with this part of the spec with this kind of input, it can be given on multiple lines, this has no impact as long as there a blank line to end the input. I think 2 chars can be saved by removing the +1 and using 1 based indexing but I started with challenge input. [Answer] # C, 110 bytes ``` c,i,j;char s[99];main(){while(~scanf("%i ",&i))for(;(c=getchar())>10;s[i++]=c);for(;s[j]>10;putchar(s[j++]));} ``` This program takes the slice after its index in one line of input each. Ungolfed: ``` c,i,j;char s[99]; main(){ while(~scanf("%i ",&i)) for(;(c=getchar())>10;s[i++]=c); for(;s[j]>10;putchar(s[j++])); } ``` Test on [ideone.com](http://ideone.com/LMp8xg) [Answer] ## Lua, 113 bytes ``` z=loadstring("return "..io.read())()table.sort(z,function(a,b)return a[1]<b[1]end)for a=1,#z do print(z[a][2])end ``` This is probably some of the more secure code I've written. The idea is simple. The user will enter an array formatted as so: `{{1, "1"}, {3, "3"}, {2, "2"}}` and then the table will be sorted by the first index and the second index will be printed. ]
[Question] [ In math a [magic square](https://en.wikipedia.org/wiki/Magic_square) is an N×N grid of numbers from 1 to N2 such that every row, column, and diagonal sums to the same total. For example here's a 3×3 magic square: [![Wikipedia magic square example](https://i.stack.imgur.com/b3C10.png)](https://en.wikipedia.org/wiki/File:Magicsquareexample.svg) In this challenge we'll extend the idea to magic *code* squares where, instead of numbers, each grid cell is any non-newline character. They can be be repeated and in any order. And instead of sums, each row, column, and diagonal is viewed as an N-character single-line program whose output is a distinct number from 0 to 2N+1 (inclusive). For example, if you had a 4×4 magic code square that looked like ``` ABCD EFGH IJKL MNOP ``` it would need to output the numbers 0 through 9, perhaps like: ``` ABCD-9 EFGH-2 IJKL-6 MNOP-5 /||||\ 3 4180 7 ``` That is, the ten embedded 4-character single-line programs that form the rows, columns, and diagonals of the grid each need to output a unique number from 0 through 9. In this case: ``` ABCD -> 9 EFGH -> 2 IJKL -> 6 MNOP -> 5 AFKP -> 7 DHLP -> 0 CGKO -> 8 BFJN -> 1 AEIM -> 4 DGJM -> 3 ``` (Note that the diagonals are read from top to bottom. This is required.) As another example, this 3×3 code square ``` d*P 0## ! d ``` would need to output 0 through 7 when its rows, column, and diagonals are run to make it magical, perhaps like: ``` d*P-1 0##-0 ! d-6 /|||\ 5 432 7 ``` # Scoring The goal of this challenge is not necessarily to make the smallest or the biggest magic code square. In some programming languages very small magic code squares might be easy to make and in other languages very large ones might be. **The challenge here is to create what you think is the best, most elegant, or most impressive magic code square or related set of magic code squares.** Hence this is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), the answer with the highest number of votes wins. * Your submission must include at least one valid magic code square, and may include many related ones if you have found them, or even an infinite neighborhood of them. * Please list the N (or range of N's) you found at the top of your answer. * For submitting multiple magic code squares in the same language but with very different implementations use multiple answers. * Of course you are encouraged to share your process of searching for magic code squares and explain why yours is interesting! (Info about any [Parker](https://knowyourmeme.com/memes/the-parker-square) magic code squares might be funny.) [Answer] # [Keg](https://github.com/JonoCode9374/Keg), 4x4 magic square ``` 0601 7.92 3._. 8654 ``` [Try it online!](https://tio.run/##y05N///fwMzAkMtcz9KIy1gvXo/LwszU5P9/AA "Keg – Try It Online") ## Outputs ``` 0601 - 1 7.92 - 7 3._. - 3 8654 - 4 /||||\ 98652 0 ``` I can't believe this actually works! Programs need the `-hr` flag to properly output the required result. [Test suite. Uncomment each line to run it. The `-in` flag is purely to make the test suite a nicer experience, as otherwise, the newlines would interfere with the programs.](https://tio.run/##Dce7DYAwDEDB3mu8Ola@TjJNKgQIiYL9JZPr7jlOd6LFRBK6zkwXii6lCMNapQqxl8EQTNWw/bkaTUhZK3lfVyXuTx1Mdw/X5@F@fw "Keg – Try It Online") ## Programs ``` 0601 - 1 (Push 0, 6, 0 and 1,then print the top of stack (TOS)) 7.92 - 7 (Push 7 and print it. This makes the rest of the program a NOP) 3._. - 3 (Push 3 and print it. The _ will the try and pop from an empty stack, ending execution) 8654 - 4 (Push 8, 6, 5 and 4 and then print TOS) 0738 - 8 (Push 0, 7, 3 and 8 and then print TOS) 6..6 - 6 (Push 6 and print it. The . will try and print from an empty stack, end execution) 09_5 - 5 (Push 0 and 9, then pop the 9 and discard it then push 5. TOS is then printed) 12.4 - 2 (Push 1, then 2 and print TOS. The rest of the program is NOPs after that.) 0._4 - 0 (Like the program for 3, but with 0) 19.8 - 9 (Like the program for 2 but with 9) ``` [Answer] # Polyglot, 10x10 ``` 0 14 5 16 7 18 9 20 10 12 13 ``` This yields the following row/column/diagonal programs (one per line): ``` 0 01 0 2 3 4 5 6 7 8 9 10 011 12 13 0 14 15 16 17 18 19 20 021 ``` In many stack-based languages, including 05AB1E and Jelly, each of those programs outputs the corresponding integer. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~4x4~~ 5x5 ``` 8www4 w3Tαw Uw₃4< XθнĀ· wTwºß ``` [Try it online.](https://tio.run/##yy9OTMpM/a/036K8vNyEq9w45NzGcq7Q8kdNzSY2XBHndlzYe6Th0Hau8pDyQ7sOz/@vdGjZoRV6TmFcSh75RZlV@XkliTlWCko6CjAQCSLKKu2VFB61TVJQsq/UC9PRjKnlUgpLLSrJTEZTDVT/qGlN8OEdXti0@CZm5imkZCam5@ch64NoaY3xcoFrAeuAakjMK8nURdEF1aCPquE/AA) (Loops over the rows; columns; main diagonal; and main anti-diagonal of the square, and will run it as 05AB1E code with `.V`, after which it will print the result and discard everything that remains on the stack for the next iteration with `)\`.) ### Explanation: The `w` are no-ops, so I'll ignore them in the explanations below. In addition, the top of the stack is output implicitly for all of these programs as result. **Horizontal:** * 4. `8 4`: push \$8\$; push \$4\$. * 7. `3Tα`: push \$3\$; push \$10\$; take the absolute difference between the two: \$\lvert3-10\rvert\$. * 3. `U₃4<`: pop and store in variable `X` (stores an empty string in `X` with an empty stack); push \$95\$; push \$4\$; decrease the top by 1: \$4-1\$. * 2. `XθнĀ·`: push \$1\$; pop and push its last digit: \$1\$; pop and push its first digit: \$1\$; Python-style truthify it: \$1\$; double it: \$2×1\$. * 0. `Tºß`: push \$10\$; mirror it without overlap: \$1001\$; pop and push its smallest digit: \$0\$. **Vertical:** * 8. `8UX`: push \$8\$; pop and store it in variable `X`; push variable `X`. * 10. `3θT`: push \$3\$; pop and push its last digit: \$3\$; push \$10\$. * 9. `T₃н`: push \$10\$; push \$95\$; pop and push its first digit: \$9\$. * 11. `α4Āº`: take the absolute difference (no-op with an empty stack); push \$4\$; Python-style truthify it: \$1\$; mirror it without overlap: \$11\$. * 6. `4<·ß`: push \$4\$; decrease it by 1: \$4-1\$; double it: \$2×3\$; pop and push its smallest digit: \$6\$. **Main diagonal / anti-diagonal:** * 1. `83₃Āß`: push \$83\$; push \$95\$; Python-style truthify it: \$1\$; pop and push its smallest digit: \$1\$. * 5. `4α₃θ`: push \$4\$; push the absolute difference (will use the single argument on the stack twice): \$\lvert4-4\rvert\$; push \$95\$; pop and push its last digit: \$5\$. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), A simple 3 by 3 Surely we can get a bigger one in Jelly, but if not... ``` 5+2 +ḷ* 1+2 ``` **[Try them online!](https://tio.run/##y0rNyan8///h7i1hj5rW/P//31TbiMtU25DL9OGO7UZcRlpGXIZAESMgz5BLG0hqgUltAA "Jelly – Try It Online")** (splits on new lines (`Ỵ`) and evaluates (`V`) each (`€`) as Jelly programs) ``` 5+2 : 5 + 2 = 7 5+1 : 5 + 1 = 6 5ḷ2 : left(5, 2) = 5 2*2 : 2 ^ 2 = 4 1+2 : 1 + 2 = 3 2ḷ1 : left(2, 1) = 2 +ḷ* : left((0 + 0), 0) ^ 0 = 1 +ḷ+ : left((0 + 0), 0) + 0 = 0 ``` ]
[Question] [ In information theory, a "prefix code" is a dictionary where none of the keys are a prefix of another. In other words, this means that none of the strings starts with any of the other. For example, `{"9", "55"}` is a prefix code, but `{"5", "9", "55"}` is not. The biggest advantage of this, is that the encoded text can be written down with no separator between them, and it will still be uniquely decipherable. This shows up in compression algorithms such as [Huffman coding](http://chat.stackexchange.com/transcript/message/29382537#29382537), which always generates the optimal prefix code. Your task is simple: Given a list of strings, determine whether or not it is a valid prefix code. Your input: * Will be a list of strings in any [reasonable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). * Will only contain printable ASCII strings. * Will not contain any empty strings. Your output will be a [truthy/falsey](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) value: Truthy if it's a valid prefix code, and falsey if it isn't. Here are some true test cases: ``` ["Hello", "World"] ["Code", "Golf", "Is", "Cool"] ["1", "2", "3", "4", "5"] ["This", "test", "case", "is", "true"] ["111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011", "0110", "11001", "00110", "10011", "11000", "00111", "10010"] ``` Here are some false test cases: ``` ["4", "42"] ["1", "2", "3", "34"] ["This", "test", "case", "is", "false", "t"] ["He", "said", "Hello"] ["0", "00", "00001"] ["Duplicate", "Duplicate", "Keys", "Keys"] ``` This is code-golf, so standard loopholes apply, and shortest answer in bytes wins. [Answer] # Pyth, 8 bytes ``` .AxM.PQ2 ``` [Test suite](https://pyth.herokuapp.com/?code=.AxM.PQ2&test_suite=1&test_suite_input=%5B%22Hello%22%2C+%22World%22%5D++++++++++++++++++++++%0A%5B%22Code%22%2C+%22Golf%22%2C+%22Is%22%2C+%22Cool%22%5D%0A%5B%221%22%2C+%222%22%2C+%223%22%2C+%224%22%2C+%225%22%5D%0A%5B%22This%22%2C+%22test%22%2C+%22case%22%2C+%22is%22%2C+%22true%22%5D++++++++++%0A%5B%22111%22%2C+%22010%22%2C+%22000%22%2C+%221101%22%2C+%221010%22%2C+%221000%22%2C+%220111%22%2C+%220010%22%2C+%221011%22%2C+%220110%22%2C+%2211001%22%2C+%2200110%22%2C+%2210011%22%2C+%2211000%22%2C+%2200111%22%2C+%2210010%22%5D%0A%5B%224%22%2C+%2242%22%5D+++++++++++++++++++++++++++++%0A%5B%221%22%2C+%222%22%2C+%223%22%2C+%2234%22%5D+++++++++++++++++++%0A%5B%22This%22%2C+%22test%22%2C+%22case%22%2C+%22is%22%2C+%22false%22%2C+%22t%22%5D%0A%5B%22He%22%2C+%22said%22%2C+%22Hello%22%5D%0A%5B%220%22%2C+%2200%22%2C+%2200001%22%5D%0A%5B%22Duplicate%22%2C+%22Duplicate%22%2C+%22Keys%22%2C+%22Keys%22%5D&debug=0) Take all 2 element permutations of the input, map each to the index of one string in the other (0 for a prefix) and return whether all results are truthy (non-zero). [Answer] ## Haskell, 37 bytes ``` f l=[x|x<-l,y<-l,zip x x==zip x y]==l ``` Each element `x` of `l` is repeated once for every element that it's a prefix of, which is exactly once for a prefix-free list, giving the original list. The prefix property is checked by zipping both lists with `x`, which cuts off elements beyond the length of `x`. [Answer] # Java, 128 127 126 125 124 121 bytes ### (Thanks @Kenny Lau, @Maltysen, @Patrick Roberts, @Joba) ``` Object a(String[]a){for(int i=0,j,l=a.length;i<l;i++)for(j=0;j<l;)if(i!=j&a[j++].startsWith(a[i]))return 1<0;return 1>0;} ``` ### Ungolfed ``` Object a(String[] a) { for (int i = 0, j, l = a.length; i < l; i++) for (j = 0; j < l;) if (i != j & a[j++].startsWith(a[i])) return 1<0; return 1>0; } ``` ### Output ``` [Hello, World] true [Code, Golf, Is, Cool] true [1, 2, 3, 4, 5] true [This, test, case, is, true] true [111, 010, 000, 1101, 1010, 1000, 0111, 0010, 1011, 0110, 11001, 00110, 10011, 11000, 00111, 10010] true [4, 42] false [1, 2, 3, 34] false [This, test, case, is, false, t] false [He, said, Hello] false [0, 00, 00001] false [Duplicate, Duplicate, Keys, Keys] false ``` [Answer] ## Python 2, 48 ~~51~~ bytes ``` lambda l:all(1/map(a.find,l).count(0)for a in l) ``` For each element `a` of `l`, the function `a.find` finds the index of the first occurrence of `a` in the input string, giving `-1` for an absence. So, `0` indicates a prefix. In a prefix-free list, mapping this function returns only a single `0` for `a` itself. The function checks that this is the case for every `a`. --- **51 bytes:** ``` lambda l:[a for a in l for b in l if b<=a<b+'~']==l ``` Replace `~` with a character with ASCII code 128 or higher. For each element `a` in `l`, a copy is included for each element that's a prefix of it. For a prefix-free list, the only such element is `a` itself, so this gives the original list. [Answer] ## CJam, 14 bytes ``` q~$W%2ew::#0&! ``` [Test suite.](http://cjam.aditsu.net/#code=qN%2F%7B%3AQ%3B%0A%0AQ~%24W%252ew%3A%3A%230%26!%0A%0A%5DoNo%7D%2F&input=%5B%22Hello%22%20%22World%22%5D%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%5B%22Code%22%20%22Golf%22%20%22Is%22%20%22Cool%22%5D%0A%5B%221%22%20%222%22%20%223%22%20%224%22%20%225%22%5D%0A%5B%22This%22%20%22test%22%20%22case%22%20%22is%22%20%22true%22%5D%20%20%20%20%20%20%20%20%20%20%0A%5B%22111%22%20%22010%22%20%22000%22%20%221101%22%20%221010%22%20%221000%22%20%220111%22%20%220010%22%20%221011%22%20%220110%22%20%2211001%22%20%2200110%22%20%2210011%22%20%2211000%22%20%2200111%22%20%2210010%22%5D%0A%5B%224%22%20%2242%22%5D%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%5B%221%22%20%222%22%20%223%22%20%2234%22%5D%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%0A%5B%22This%22%20%22test%22%20%22case%22%20%22is%22%20%22false%22%20%22t%22%5D%0A%5B%22He%22%20%22said%22%20%22Hello%22%5D%0A%5B%220%22%20%2200%22%20%2200001%22%5D%0A%5B%22Duplicate%22%20%22Duplicate%22%20%22Keys%22%20%22Keys%22%5D) ### Explanation ``` q~ e# Read and evaluate input. $ e# Sort strings. If a prefix exists it will end up directly in front e# of a string which contains it. W% e# Reverse list. 2ew e# Get all consecutive pairs of strings. ::# e# For each pair, find the first occurrence of the second string in the first. e# If a prefix exists that will result in a 0, otherwise in something non-zero. 0& e# Set intersection with 0, yielding [0] for falsy cases and [] for truthy ones. ! e# Logical NOT. ``` [Answer] # JavaScript ES6, ~~65~~ ~~43~~ 40 bytes ``` a=>!/(.*)\1/.test(''+a.sort().join``) ^ ^ ^ embedded NUL characters ``` My previous solution, which handled string arrays of all UTF-8 characters: ``` a=>!/[^\\]("([^"]*\\")*[^\\])",\1/.test(JSON.stringify(a.sort())) ``` I was able to avoid `JSON.stringify` since the challenge specifies printable ASCII characters only. ## Test ``` f=a=>!/(\0.*)\1/.test('\0'+a.sort().join`\0`) // since stackexchange removes embedded NUL characters O.textContent += 'OK: '+ [["Hello", "World"] ,["Code", "Golf", "Is", "Cool"] ,["1", "2", "3", "4", "5"] ,["This", "test", "case", "is", "true"] ,["111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011", "0110", "11001", "00110", "10011", "11000", "00111", "10010"] ].map(a=>f(a)) O.textContent += '\nKO: '+ [["4", "42"] ,["1", "2", "3", "34"] ,["This", "test", "case", "is", "false", "t"] ,["He", "said", "Hello"] ,["0", "00", "00001"] ,["Duplicate", "Duplicate", "Keys", "Keys"] ].map(a=>f(a)) ``` ``` <pre id=O></pre> ``` [Answer] # Haskell, 49 bytes ``` g x=[1|z<-map((and.).zipWith(==))x<*>x,z]==(1<$x) ``` This has a couple parts: ``` -- Are two lists (or strings) equal for their first min(length_of_1,length_of_2) elements, i.e. is one the prefix of the other? (and.).zipWith(==) -- Check whether one element is the prefix of the other, for all pairs of elements (including equal pairs) map((and.).zipWith(==))x<*>x -- This is a list of 1's of length (number of elements that are the prefix of the other) [1|z<-map((and.).zipWith(==))x<*>x,z] -- This is the input list, with all the elements replaced with 1's (1<$x) ``` If the two lists are equal, then an element is only the prefix of itself, and it's valid. [Answer] ## [Retina](https://github.com/mbuettner/retina), 19 bytes Byte count assumes ISO 8859-1 encoding. ``` O`.+ Mm1`^(.+)¶\1 0 ``` The input should be linefeed-separated. Output is `0` for falsy and `1` for truthy. [Try it online!](http://retina.tryitonline.net/#code=JShgXHMKwrYKT2AuKwpNbTFgXiguKynCtlwxCjA&input=SGVsbG8gV29ybGQKQ29kZSBHb2xmIElzIENvb2wKMSAyIDMgNCA1ClRoaXMgdGVzdCBjYXNlIGlzIHRydWUKMTExIDAxMCAwMDAgMTEwMSAxMDEwIDEwMDAgMDExMSAwMDEwIDEwMTEgMDExMCAxMTAwMSAwMDExMCAxMDAxMSAxMTAwMCAwMDExMSAxMDAxMAo0IDQyCjEgMiAzIDM0ClRoaXMgdGVzdCBjYXNlIGlzIGZhbHNlIHQKSGUgc2FpZCBIZWxsbwowIDAwIDAwMDAxCkR1cGxpY2F0ZSBEdXBsaWNhdGUgS2V5cyBLZXlz) (Slightly modified to support multiple space-separated test cases instead.) ### Explanation ``` O`.+ ``` Sort the lines in the input. If a prefix exists it will end up directly in front of a string which contains it. ``` Mm1`^(.+)¶\1 ``` Try to match (`M`) a complete line which is also found at the beginning of the next line. The `m` activates multiline mode such that `^` matches line beginnings and the `1` ensures that we only count at most one match such that the output is `0` or `1`. ``` 0 ``` To swap `0` and `1` in the result, we count the number of `0`s. [Answer] # Java, 97 bytes ``` Object a(String[]a){for(String t:a)for(String e:a)if(t!=e&t.startsWith(e))return 1<0;return 1>0;} ``` Uses most of the tricks found in [@Marv's answer](https://codegolf.stackexchange.com/a/79097/32531), but also makes use of the foreach loop and string reference equality. Unminified: ``` Object a(String[]a){ for (String t : a) for (String e : a) if (t != e & t.startsWith(e)) return 1<0; return 1>0; } ``` Note that, as I said, this uses string reference equality. That does mean that the code can behave oddly due to [String interning](https://stackoverflow.com/a/10579062/3991344). The code does work when using arguments passed from the command line, and also when using something read from the command line. If you want to hardcode the values to test, though, you'd need to manually call the String constructor to force interning to not occur: ``` System.out.println(a(new String[] {new String("Hello"), new String("World")})); System.out.println(a(new String[] {new String("Code"), new String("Golf"), new String("Is"), new String("Cool")})); System.out.println(a(new String[] {new String("1"), new String("2"), new String("3"), new String("4"), new String("5")})); System.out.println(a(new String[] {new String("This"), new String("test"), new String("case"), new String("is"), new String("true")})); System.out.println(a(new String[] {new String("111"), new String("010"), new String("000"), new String("1101"), new String("1010"), new String("1000"), new String("0111"), new String("0010"), new String("1011"), new String("0110"), new String("11001"), new String("00110"), new String("10011"), new String("11000"), new String("00111"), new String("10010")})); System.out.println(a(new String[] {new String("4"), new String("42")})); System.out.println(a(new String[] {new String("1"), new String("2"), new String("3"), new String("34")})); System.out.println(a(new String[] {new String("This"), new String("test"), new String("case"), new String("is"), new String("false"), new String("t")})); System.out.println(a(new String[] {new String("He"), new String("said"), new String("Hello")})); System.out.println(a(new String[] {new String("0"), new String("00"), new String("00001")})); System.out.println(a(new String[] {new String("Duplicate"), new String("Duplicate"), new String("Keys"), new String("Keys")})); ``` [Answer] # PostgreSQL, 186, 173 bytes ``` WITH y AS(SELECT * FROM t,LATERAL unnest(c)WITH ORDINALITY s(z,r)) SELECT y.c,EVERY(u.z IS NULL) FROM y LEFT JOIN y u ON y.i=u.i AND y.r<>u.r AND y.z LIKE u.z||'%' GROUP BY y.c ``` Output: [![enter image description here](https://i.stack.imgur.com/Jaevb.png)](https://i.stack.imgur.com/Jaevb.png) No live demo this time. <http://sqlfiddle.com> supports only 9.3 and to run this demo 9.4 is required. How it works: 1. Split string array with number and name it `y` 2. Get all y 3. `LEFT OUTER JOIN` to the same derived table based on the same `i`(id), but with different `oridinal` that start with prefix `y.z LIKE u.z||'%'` 4. Group result based on `c` (initial array) and use `EVERY` grouping function. If every row from second table `IS NULL` it means there is no prefixes. --- Input if someone is interested: ``` CREATE TABLE t(i SERIAL,c text[]); INSERT INTO t(c) SELECT '{"Hello", "World"}'::text[] UNION ALL SELECT '{"Code", "Golf", "Is", "Cool"}' UNION ALL SELECT '{"1", "2", "3", "4", "5"}' UNION ALL SELECT '{"This", "test", "case", "is", "true"}' UNION ALL SELECT '{"111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011","0110", "11001", "00110", "10011", "11000", "00111", "10010"}' UNION ALL SELECT '{"4", "42"}' UNION ALL SELECT '{"1", "2", "3", "34"}' UNION ALL SELECT '{"This", "test", "case", "is", "false", "t"}' UNION ALL SELECT '{"He", "said", "Hello"}' UNION ALL SELECT '{"0", "00", "00001"}' UNION ALL SELECT '{"Duplicate", "Duplicate", "Keys", "Keys"}'; ``` **EDIT:** `SQL Server 2016+` implementation: ``` WITH y AS (SELECT *,z=value,r=ROW_NUMBER()OVER(ORDER BY 1/0) FROM #t CROSS APPLY STRING_SPLIT(c,',')) SELECT y.c, IIF(COUNT(u.z)>0,'F','T') FROM y LEFT JOIN y u ON y.i=u.i AND y.r<>u.r AND y.z LIKE u.z+'%' GROUP BY y.c; ``` `**[`LiveDemo`](https://data.stackexchange.com/stackoverflow/query/483366)**` Note: It is comma separated list, not real array. But the main idea is the same as in `PostgreSQL`. --- **EDIT 2:** Actually `WITH ORDINALITY` could be replaced: ``` WITH y AS(SELECT *,ROW_NUMBER()OVER()r FROM t,LATERAL unnest(c)z) SELECT y.c,EVERY(u.z IS NULL) FROM y LEFT JOIN y u ON y.i=u.i AND y.r<>u.r AND y.z LIKE u.z||'%' GROUP BY y.c ``` `**[`SqlFiddleDemo`](http://sqlfiddle.com/#!15/7015d8/4/0)**` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` ¬(⊇pa₀ᵈ) ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSuVv2obcOjpuZHHcuVSopKU5VqQKy0xJziVKXaciU9BaWHuzprH26d8P/QGo1HXe0FiY@aGh5u7dD8/z86WskjNScnX0lHKTy/KCdFKVYnWskEyDMxAjOd81NSgTz3/Jw0IOVZDCSc8/NzwHKGQI4REBuDsAmGEMgUU7BoSEYmSGNJanEJkEpOLAYZCRaCuBEoRUAd2FcgJR4goeLEzBQgBXE4SNQAyDOAEAYGhkqxsQA "Brachylog – Try It Online") Outputs through predicate success/failure. Takes more than 60 seconds on the last truthy test case `["111","010","000","1101","1010","1000","0111","0010","1011","0110","11001","00110","10011","11000","00111","10010"]` [but passes it quickly with an added byte](https://tio.run/##SypKTM6ozMlPN/r//9AajUdd7Ue6ChIfNTU83Nqh@f9/tJKhoaGSjpKBoQGINACRhoYGICFDiJghRNAAqg4mCNVlCNVgAJWEaQFLG8L0QjUbgnXHAgA) which eliminates a large number of possibilities earlier than the program does otherwise (`Ċ` before checking permutations rather than `ᵈ` after checking permutations, to limit the length of the sublist to two). ``` ¬( ) It cannot be shown that p a permutation of ⊇ a sublist of the input ᵈ is a pair of values [A,B] such that a₀ A is a prefix of B. ``` Less trivial 9-byte variants than [`¬(⊇Ċpa₀ᵈ)`](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSuVv2obcOjpuZHHcuVSopKU5VqQKy0xJziVKXaciU9BaWHuzprH26d8P/QGo1HXe1HugoSHzU1PNzaofn/f3S0kkdqTk6@ko5SeH5RTopSrE60kgmQZ2IEZjrnp6QCee75OWlAyrMYSDjn5@eA5QyBHCMgNgZhEwwhkCmmYNGQjEyQxpLU4hIglZxYDDISLARxJVCKgDqwv0BKPEBCxYmZKUAK4nCwtYYgiw0MDUCkAYg0NDQACRlCxAwhggZQdTBBqC5DqAYDqCRMC1jaEKYXqtkQrBtkKUQUYiNQa2wsAA) which run in reasonable time are [`¬(⊇o₁a₀ᵈ)`](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSuVv2obcOjpuZHHcuVSopKU5VqQKy0xJziVKXaciU9BaWHuzprH26d8P/QGo1HXe35j5oaEx81NTzc2qH5/390tJJHak5OvpKOUnh@UU6KUqxOtJIJkGdiBGY656ekAnnu@TlpQMqzGEg45@fngOUMgRwjIDYGYRMMIZAppmDRkIxMkMaS1OISIJWcWAwyEiwEcSZQioA6sMdASjxAQsWJmSlACuJwsLWGIIsNDA1ApAGINDQ0AAkZQsQMIYIGUHUwQaguQ6gGA6gkTAtY2hCmF6rZEKwbZClEFGIjUGtsLAA), [`¬(⊇o↔a₀ᵈ)`](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSuVv2obcOjpuZHHcuVSopKU5VqQKy0xJziVKXaciU9BaWHuzprH26d8P/QGo1HXe35j9qmJD5qani4tUPz///oaCWP1JycfCUdpfD8opwUpVidaCUTIM/ECMx0zk9JBfLc83PSgJRnMZBwzs/PAcsZAjlGQGwMwiYYQiBTTMGiIRmZII0lqcUlQCo5sRhkJFgI4kygFAF1YI@BlHiAhIoTM1OAFMThYGsNQRYbGBqASAMQaWhoABIyhIgZQgQNoOpgglBdhlANBlBJmBawtCFML1SzIVg3yFKIKMRGoNbYWAA), and [`¬(⊇oa₀ᵈ¹)`](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSuVv2obcOjpuZHHcuVSopKU5VqQKy0xJziVKXaciU9BaWHuzprH26d8P/QGo1HXe35iY@aGh5u7Ti0U/P//@hoJY/UnJx8JR2l8PyinBSlWJ1oJRMgz8QIzHTOT0kF8tzzc9KAlGcxkHDOz88ByxkCOUZAbAzCJhhCIFNMwaIhGZkgjSWpxSVAKjmxGGQkWAjiSqAUAXVgf4GUeICEihMzU4AUxOFgaw1BFhsYGoBIAxBpaGgAEjKEiBlCBA2g6mCCUF2GUA0GUEmYFrC0IUwvVLMhWDfIUogoxEag1thYAA). [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 24 bytes ``` {.all.starts-with(.one)} ``` [Try it online!](https://tio.run/##hVHBSgMxED27XxFyKC1oSNrVi4hIFSt6FD2UPYRuQhfGpiQpspR@@9qZTVaUijnM23l583ZmsjUerrqPlo0su2HdXmgAEaL2MVx8NnE9Fm5jJofuurDOszE0GxMmbF@cBd2yW/HwdvciRrY4dEu@MACOnzP@7jzUvGInT7Hkc1cb1D06sIhPAePcOeDV8VphNsUww1BiuKSb13VD0mhCRFzpQEaJ9TvTGyiykEoSSAKlJLEq0SrxMqsHPlerXCezYKjsJWrwyCaKXLAH6rqc/rWF72X8mnZWniz5d3iroU8j/X5B30E3NWL/MsindtNejoMheb/bQrPSkWp@JM@mDQNWXw "Perl 6 – Try It Online") Wow, surprisingly short while using a long built-in. ### Explanation ``` { } # Anonymous code block taking a list .all # Do all of the strings .starts-with( ) # Start with .one # Only one other string (i.e. itself) ``` [Answer] # Racket, 70 bytes ``` (λ(l)(andmap(λ(e)(not(ormap(curryr string-prefix? e)(remv e l))))l)) ``` [Answer] # JavaScript (ES6), 52 ~~54~~ **Edit** 2 bytes saved thx @Neil ``` a=>!a.some((w,i)=>a.some((v,j)=>i-j&&!w.indexOf(v))) ``` **Test** ``` f=a=>!a.some((w,i)=>a.some((v,j)=>i-j&&!w.indexOf(v))) O.textContent += 'OK: '+ [["Hello", "World"] ,["Code", "Golf", "Is", "Cool"] ,["1", "2", "3", "4", "5"] ,["This", "test", "case", "is", "true"] ,["111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011", "0110", "11001", "00110", "10011", "11000", "00111", "10010"] ].map(a=>f(a)) O.textContent += '\nKO: '+ [["4", "42"] ,["1", "2", "3", "34"] ,["This", "test", "case", "is", "false", "t"] ,["He", "said", "Hello"] ,["0", "00", "00001"] ,["Duplicate", "Duplicate", "Keys", "Keys"] ].map(a=>f(a)) ``` ``` <pre id=O></pre> ``` [Answer] # Mathematica ~~75 69~~ 68 bytes Loquacious as usual. But Martin B was able to reduce the code by 7 bytes. ## Method 1: Storing output in an `Array` (68 bytes) ``` f@a_:=!Or@@(Join@@Array[a~Drop~{#}~StringStartsQ~a[[#]]&,Length@a]) ``` --- ``` f@{"111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011", "0110", "11001", "00110", "10011", "11000", "00111", "10010"} ``` > > True > > > --- ``` f@{"He", "said", "Hello"} ``` > > False > > > --- [Answer] ## Mathematica, 41 bytes ``` !Or@@StringStartsQ@@@Reverse@Sort@#~Subsets~{2}& ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 13 [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") -2 bytes: ``` ≢=∘≢∘⍸∘.(⊃⍷)⍨ ``` [Try it online!](https://tio.run/##hVGxTsMwEN37FWxOBpDdhJEpSCRiQKKVmK3GgUiWXNXp0BmpAiRXMCAxMzEgMcLMp/hHgu9sh1YqIsN7und3z3cXPpeH9YpLdd339v71xN69OAI0Xw6PEvtwa81nas1b39j1ozUbu3muLpz8/ZHZ9ZOLJpeFw2lZTfomIaWQUpE0IVdqIWuSHuz9Rq6yULWAwjMlG@BKAxZKSZJCnkE4BsgAcoBjn5retFjcCd0Bz7hGq6AulmL7YTRjaEcZRaJIjFFUWZBZ0GmsHvTYzWIfjQVDpy9hg0c0Yd5lZM07DIJr5OO/DrM98u7@Wb635/9zNFz6sPPHKzHQvK2Bw/@CRJg7HAg2BPV0OZftjHfYtROci5X@5R8 "APL (Dyalog Unicode) – Try It Online") Explanation: ``` ≢=∘≢∘⍸∘.(⊃⍷)⍨ ⍝ Monadic function train ⍷ ⍝ "Find": Convert the right argument into a boolean vector, ⍝ where ones correspond to instances of the left argument ⊃ ⍝ Take the first item of the above vector (i.e., only prefixes) ∘.( )⍨ ⍝ Commutative outer product: take the above function and apply ⍝ it for each possible pair of elements in the input ⍝ If the input is a prefix code, the above should have a number of ones ⍝ equal to the length of the input (i.e., each item is a prefix of only itself) ⍝ To test this... ⍸ ⍝ Find the location of all ones in the above ≢∘ ⍝ Take the length of the above ≢=∘ ⍝ Compare to the length of the input ``` [Answer] # [J](http://jsoftware.com/), 17 bytes ``` #=1#.1#.{.@E.&>/~ ``` [Try it online!](https://tio.run/##jVFbS8MwGH3vrzg4WBC27Pu2@rJZEedlovggAx@ltCmrBCJL9iCCf73mgqAYxJKEnJwLyenLcCRFh2oJgQkISz@nEuvH@@thVPFI@vEuz6/k@Gz2MRwXxcOFhNsfVFGoZmfAqNDhdCWf2SdslNYGT2avW5Hj16ZVuDG6w631wOisijHHAiVOsux211s4ZR2a2ioE4K@TD2IGMYGI/J4YHBAHSJFLkFkgZ/dE9FFUJqd3cQqICeGERGqlq7X9qoV@BJUo5wJ/fTlXqmFRin/qfxcTbwQncuqNgq37Nv2yrCK8MVRHnKUvD6@6b2qnvu3u1JuNi69k@AQ "J – Try It Online") *Note: I actually wrote this before looking at the APL answer, to approach it without bias. Turns out the approaches are almost identical, which is interesting. I guess this is the natural "array thinknig" solution* Take boxed input because the strings are of unequal length. Create a self-function table `/~` of each element paired with each element and see if there is a match at the start `{.@E.`. This will produce a matrix of 1-0 results. Sum it twice `1#.1#.` to get a single number representing "all ones in the matrix", and see if that number is the same as the length of the input `#=`. If it is, the only prefix matches are self matches, ie, we have a prefix code. ## sorting solution, 18 bytes ``` 0=1#.2{.@E.&>/\/:~ ``` Attempt at different approach. This solution sorts and looks at adjacent pairs. [Try it online!](https://tio.run/##jVHLSsQwFN33Kw4KBkEz93bqploRx8fIiAsR3AhS2pSpBCKTzEIEf73mgaAYxEBCTs6D5ORl2pFiQFND4ACE2s9DicX97dVEDe/K8l2eXcq909nTrP6Y9ovi7lzCbbaqKFS3NmA0GHByLJ/ZRyyV1gaPZqN7keMXple4NnrAjfXA6KyKUWKOCkdZ9mE9WjhlHbrWKgTgr5MPYgYxgYj8nhgcEAdIkUuQWSBn90T0UVQmp3dxCogJ4YREamVotf2qhX4EVahKgb9GzpVqmFfin/rfxcQbwYmceqlg27FPX5ZVhDeG6oiz9MX2VY9d69S33Uq92bj4SqZP "J – Try It Online") [Answer] # [R](https://www.r-project.org/), 48 bytes ``` function(s)sum(outer(s,s,startsWith))==length(s) ``` [Try it online!](https://tio.run/##jVE9a8MwEN37K4InCTLoEnf0lEITuhYyC1uqBapVpNOQX@9apw9ImyE23OOe3nvWnf2qh1XHZUTjFhZ4iN/MRVSehf32ovQYrgZnzofBquUL5020ajay7qysdd1@112dt1PH@e7f80LCk5tU0r07qxNeQqon5@xmyhJIzCGVYyp9Kq/t9HM2ZEEVMOEoAwUW1keVv16ygNIECAJBACCIhUJD4UVVN766ofpEFTRnlkDLqCFAKfXWNER/eLiY@wX9mf7YPzm5lja32Axn6oM0U8L8i@pZuWzZyjZWPXiLP9aMEsl713yoW2jI@foL "R – Try It Online") Explanation: `outer(s,s,startsWith)` outputs a matrix of logicals checking whether `s[i]` is a prefix of `s[j]`. If `s` is a prefix code, then there are exactly `length(s)` TRUE elements in the result, corresponding to the diagonal elements (`s[i]` is a prefix of itself). [Answer] # Pyth - ~~13~~ 12 bytes ``` !ssmm}d._k-Q ``` [Try it online here](http://pyth.herokuapp.com/?code=%21ssmm%7Dd._k-Q&test_suite=1&test_suite_input=%5B%22Hello%22%2C+%22World%22%5D++++++++++++++++++++++%0A%5B%22Code%22%2C+%22Golf%22%2C+%22Is%22%2C+%22Cool%22%5D%0A%5B%221%22%2C+%222%22%2C+%223%22%2C+%224%22%2C+%225%22%5D%0A%5B%22This%22%2C+%22test%22%2C+%22case%22%2C+%22is%22%2C+%22true%22%5D++++++++++%0A%5B%22111%22%2C+%22010%22%2C+%22000%22%2C+%221101%22%2C+%221010%22%2C+%221000%22%2C+%220111%22%2C+%220010%22%2C+%221011%22%2C+%220110%22%2C+%2211001%22%2C+%2200110%22%2C+%2210011%22%2C+%2211000%22%2C+%2200111%22%2C+%2210010%22%5D%0A%5B%224%22%2C+%2242%22%5D+++++++++++++++++++++++++++++%0A%5B%221%22%2C+%222%22%2C+%223%22%2C+%2234%22%5D+++++++++++++++++++%0A%5B%22This%22%2C+%22test%22%2C+%22case%22%2C+%22is%22%2C+%22false%22%2C+%22t%22%5D%0A%5B%22He%22%2C+%22said%22%2C+%22Hello%22%5D%0A%5B%220%22%2C+%2200%22%2C+%2200001%22%5D&debug=0). [Answer] # Ruby, 48 bytes Uses arguments as input and stdout as output. ``` p !$*.map{a,*b=$*.rotate! a.start_with? *b}.any? ``` [Answer] # Python, ~~58~~ 55 bytes ``` lambda l:sum(0==a.find(b)for a in l for b in l)==len(l) ``` [Answer] # Scala, 71 bytes ``` (s:Seq[String])=>(for{x<-s;y<-s}yield x!=y&&x.startsWith(y)).forall(!_) ``` [Answer] ## Racket 130 bytes ``` (define g #t)(for((n(length l)))(for((i(length l))#:unless(= i n))(when(string-prefix?(list-ref l i)(list-ref l n))(set! g #f))))g ``` Ungolfed: ``` (define(f l) (define g #t) (for ((n (length l))) (for ((i (length l)) #:unless (= i n)) (when (string-prefix? (list-ref l i) (list-ref l n)) (set! g #f))))g) ``` Testing: ``` (f [list "Hello" "World"]) (f [list "Code" "Golf" "Is" "Cool"]) (f [list "1" "2" "3" "4" "5"]) (f [list "This" "test" "case" "is" "true"]) (f [list "111" "010" "000" "1101" "1010" "1000" "0111" "0010" "1011" "0110" "11001" "00110" "10011" "11000" "00111" "10010"]) (f [list "4" "42"]) (f [list "1" "2" "3" "34"]) (f [list "This" "test" "case" "is" "false" "t"]) (f [list "He" "said" "Hello"]) (f [list "0" "00" "00001"]) (f [list "Duplicate" "Duplicate" "Keys" "Keys"]) ``` Output: ``` #t #t #t #t #t #f #f #f #f #f #f ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 93 bytes ``` p(r,e,f,i,x)char**r;{for(f=i=0;i<e;++i)for(x=0;x<e;++x)f|=x!=i&&strstr(r[i],r[x])==r[i];r=f;} ``` [Try it online!](https://tio.run/##dY1BbsMgEEX3OQXJIgKbVDNrygF6BscLi0KK1GJr7FZISc5OGbxtBxb/Px7gLjfnSlkkaa@Djjor9zFR15G5h5lksNGCia/e9H1UTHLtufWswsPmo43n87pR3ZKGOGoa8qis5WzIBvMsMW3ia4pJcpjo5rTgT0RX888wKnE/iDoxCHlcJMMeNXsX1MBLqSbwLFQfCfL0ttboQ8zCze/@5ZpOyjTJf67@LzvN2z83yG/flASYw7MURCyAUACgZsCC3JArtLO9NgubAg3uUsW4u01mAr8 "C (gcc) – Try It Online") Simple double for loop using `strstr(a,b)==a` to check for prefices. Mainly added since there doesn't seem to be a C answer yet. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 2.ÆDí«ε`Å?}O_ ``` Too long.. Initially I had a 9-byte solution, but it failed for the duplicated key test case. [Try it online](https://tio.run/##yy9OTMpM/f/fSO9wm8vhtYdWn9uacLjVvtY//v//aKWQjMxiJR0FpZLU4hIQnZxYnAqiIaJpiTkQbolSLAA) or [verify all test cases](https://tio.run/##hZCxCsIwEEB/pWQukqt17qCg4uAiOJSi0UYsBCKmCh0c9QP8DXH0B@zuR/gj9S5JQXBwuLvk3T1yrTZiVcjmWCUseF@uAUuqJurUl0F9f95ej2V9Tk7TRRM2acpGUinNQjbXe5WzLExZX@cSwVCrDZaxwdTXWtke4CXC6GLEGD1LZ9uCpkppSixrYch3aH@QTgRSOXDKnDIAJwSOgYPcz7XQW@AF7putYtvQul4Ga2dhEKR2xzj6Wb0b/9l7I5S9lHZuREcjihyL@19E3Zvue3AxQoPDThVrUdL893kiK9OWLPsA). **Explanation:** ``` 2.Æ # Get all combinations of two elements from the (implicit) input-list Dí # Duplicate and reverse each pair « # Merge the lists of pairs together ε # Map each pair to: ` # Push both strings to the stack Å? # And check if the first starts with the second }O # After the map: sum to count all truthy values _ # And convert it to truthy if it's 0 or falsey if it's any other integer # (which is output implicitly as result) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 bytes ``` á2 ËrbÃe ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=4TIgy3Jiw2U&input=WyJDb2RlIiwiR29sZiIsIklzIiwiQ29vbCJd) ``` á2 ËrbÃe :Implicit input of array á2 :Permutations of length 2 Ë :Map each pair r : Reduce by b : Get the index of the second in the first - 0 (falsey) if it's a prefix à :End map e :All truthy (-1 or >0) ``` [Answer] ## [C# (Visual C# Interactive Compiler)](https://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 70 bytes ``` l=>!l.Any(x=>l.Where((y,i)=>l.IndexOf(x)!=i).Any(z=>z.StartsWith(x))); ``` [Try it online!](https://tio.run/##pVJNT4NAEL37KyinJalkt8VTC4mp0TY28aAJZ4RFJtnsGnYbocbfjuzwET25Kod5mcd7byYDub7MNXS3J5lvj6DNVpsa5EuyfFZKJGXciThZiPBatqSJExGmFa85Ie0SAtseZMGbh5I0wSKGAGXnODmHjyarjU7BVP2rINh0G298LtIaDD@C5KQkkr95X6e@@3suhPKXnp@qWhT@R@/9wbFTBbeGOyVKiwdt665f38XNrHhly9qWyJYrF@NTBTjIcG0s5pnGNZD9xXyGG1BGESgCYxRZNtJs5OmknvnJzSYfnQSzc5CwOWMKYZjisCLeJFr94Zrr6N@X9MtMDK1xydqjVGdQWBx@JgfbeJnxE/Q3dPDcnF4F5JnBid@ae97qGW1S9wk) [Answer] # [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` å·↑↑¶Ω ``` [Run and debug it](https://staxlang.xyz/#p=86fa181814ea&i=[%22Hello%22,+%22World%22]++++++++++++++++++++++%0A[%22Code%22,+%22Golf%22,+%22Is%22,+%22Cool%22]%0A[%221%22,+%222%22,+%223%22,+%224%22,+%225%22]%0A[%22This%22,+%22test%22,+%22case%22,+%22is%22,+%22true%22]++++++++++%0A[%22111%22,+%22010%22,+%22000%22,+%221101%22,+%221010%22,+%221000%22,+%220111%22,+%220010%22,+%221011%22,+%220110%22,+%2211001%22,+%2200110%22,+%2210011%22,+%2211000%22,+%2200111%22,+%2210010%22]%0A[%224%22,+%2242%22]+++++++++++++++++++++++++++++%0A[%221%22,+%222%22,+%223%22,+%2234%22]+++++++++++++++++++%0A[%22This%22,+%22test%22,+%22case%22,+%22is%22,+%22false%22,+%22t%22]%0A[%22He%22,+%22said%22,+%22Hello%22]%0A[%220%22,+%2200%22,+%2200001%22]%0A[%22Duplicate%22,+%22Duplicate%22,+%22Keys%22,+%22Keys%22]%0A&a=1&m=2) This produces non-zero for truthy. The general idea is to consider every pair of strings in the input. If the substring index of one in the other is ever zero, then it's not a valid prefix code. In stax, index of a non-existing substring yields `-1`. This way, all the pair-wise substring indices can be multiplied together. This is the same algorithm as isaacg's pyth solution, but I developed it independently. ]
[Question] [ This is [**Weekly Challenge #1.**](http://meta.codegolf.stackexchange.com/q/3578/8478) Theme: **Audio Processing** Your task is to write a program, which writes an audio file to disc (in a format of your choice), which contains the [Morse code](http://en.wikipedia.org/wiki/Morse_code) for `2015`, i.e. ``` ..--- ----- .---- ..... ``` You are free to choose any sort of sound for the segments, like a single-frequency sine wave, a chord, noise, some instrument (e.g. using MIDI files), as long as it's audible. However, there are some constraints on the timing: * Short segments need to be at least 0.2 seconds in length. * Long segments need to be at least 3 times as long as short segments. * Breaks between segments within a digit should be the same length as short segments. * Breaks between digits should be the same length as long segments. * Each segment and break may deviate up to 10% from the average length of that type of segment/break. * The entire audio file may not be longer than 30 seconds. The breaks don't need to be completely silent, but the Morse segments should be audibly louder than the breaks. Note that you *have* to write an audio file. You cannot just play the sound, e.g. using system beeps. You're allowed to use any sort of library to handle the file format and audio generation, but you must not use built-in features for Morse encoding. This is code golf, so the shortest answer (in bytes) wins. Please consider linking to an upload of the resulting audio file (on SoundCloud or similar), so people can check out the result without having to run your code. If you upload to SoundCloud, please make sure to enable downloads in the Permissions tab of the track. If your output uses a rather uncommon file format, please add some information about how to play it back and/or convert it to a more common format and upload it. ### Example track This is a manually generated example track which conforms with the spec and uses noise for the Morse segments (microphone background noise, to be precise). **[Here is a link to SoundCloud](https://soundcloud.com/martin-b-ttner-7/2015-morse-example-1)** if the embedded player doesn't work for you. ## Bounty Details I will award the bounty to the shortest submission in an [audio programming language](http://en.wikipedia.org/wiki/Audio_programming_language), i.e. a language that is designed to synthesise sound. That list is not complete, so feel free to use another audio programming language, if you know one. If you're not sure whether some language you want to use classifies as an audio programming language, please let me know in the comments or in [chat](http://chat.stackexchange.com/rooms/240/the-nineteenth-byte), and we can discuss that. Note that your submission still has to comply with all the rules - in particular, it has to write a file, which might not be possible in all audio programming languages. E.g., as far as I can tell, [gibber](http://gibber.mat.ucsb.edu/) can only play the sound and not save it to a file. [Answer] # x86 machine code (.COM file): ~~121~~ ~~120~~ ~~113~~ 109 bytes Hexdump: ``` 00000000 b4 3e bb 01 00 cd 21 b4 3c 31 c9 ba 3e 01 cd 21 |.>....!.<1..>..!| 00000010 4a b4 09 cd 21 be 56 01 8a 0c 46 e8 0c 00 b1 32 |J...!.V...F....2| 00000020 e8 07 00 81 fe 6d 01 75 ef c3 88 cb c0 e3 07 c1 |.....m.u........| 00000030 e1 04 30 d2 b4 02 00 da cd 21 e2 fa c3 2e 73 6e |..0......!....sn| 00000040 64 00 00 00 18 ff ff ff ff 00 00 00 02 00 00 10 |d...............| 00000050 00 00 00 00 01 24 33 33 99 99 99 66 99 99 99 99 |.....$33...f....| 00000060 99 66 33 99 99 99 99 66 33 33 33 33 33 |.f3....f33333| 0000006d ``` Can be easily run under DosBox; the output is a [.SND file](http://en.wikipedia.org/wiki/Au_file_format) named `SND`. [Here is a FLAC version](https://bitbucket.org/mitalia/pcg/downloads/morse.flac) of its output (and [here](https://bitbucket.org/mitalia/pcg/downloads/morse.com) the .COM file). Commented assembly: ``` org 100h start: ; close stdout mov ah,3eh mov bx,1 int 21h ; open snd mov ah,3ch xor cx,cx mov dx,filename int 21h ; write the header ; we used the `snd` part of the header as file name, back off one byte dec dx mov ah,9h int 21h mov si,data .l: ; data read cycle ; read the current byte in cl (zero-extending to 16-bit) ; notice that ch is already zero (at the first iteration it's 0 from the ; int 21h/3ch, then we are coming from gen, which leaves cx to zero) mov cl,[si] ; move to next byte inc si ; generate the tone call gen ; generate the pause mov cl,50 call gen ; repeat until we reach the end of data cmp si,eof jne .l ; quit ret gen: ; generate a sawtooth wave at sampling frequency/2 Hz ; receives length (in samples>>4) in cx, with lowest bit indicating if ; it has to write a wave or a pause mov bl,cl ; shift the rightmost bit all the way to the left; this kills the ; unrelated data and puts a 128 in bl (if cx & 1 != 0) shl bl,7 ; rescale the samples number shl cx,4 ; zero the starting signal xor dl,dl ; prepare the stuff for int 21h mov ah,2h .l: ; increment the signal add dl,bl ; write it int 21h ; decrement iteration count and loop loop .l ret ; .SND file header (4096 samples, mono, PCM) header: db "." ; we also use "snd" as the file name filename: db "snd",0,0,0,24,0xff,0xff,0xff,0xff,0,0,0,2,0,0,0x10,0,0,0,0,1 ; terminator for int 21h/ah=9h db '$' data: ; generated by gendata.py incbin "data.dat" eof: ``` The `data.dat` included above is an easy-to-use representation of the morse string (lower bit: sound on/sound off, upper 7 bits: sound length in samples >> 4) generated by a Python script: ``` #!/usr/bin/env python2 import sys # source string s = "..--- ----- .---- ....." # samples sr = 4096 conv = { '.': 1 | (((sr/5) >> 4) & ~1), # dot: 1/5 second, dI/dt=1 '-': 1 | (((sr/5*3) >> 4) & ~1), # line: 3/5 second, dI/dt=1 ' ': ((sr/5*2) >> 4) & ~1 # space: 2/5 second (+1/5 from the always-present pause), dI/dt=0 (silent) } sys.stdout.write(''.join(chr(conv[a]) for a in s)) ``` [Answer] # Mathematica - 130 ``` r = Riffle; s = SoundNote; Export["m.mid", Sound@ r[Flatten@ r[ s[0,.4(Boole@#+.5)]&/@Array[#>4&,5,5-#]&/@{2,0,1,5}, (b=None~s~#&)@.6 ],[[email protected]](/cdn-cgi/l/email-protection) ] ] ``` [Play online](http://onlinesequencer.net/import2/1897e09bc8e94e9bd7c93405794bae73?title=m.mid) [Answer] # Perl 5: 94 122 140 SND files have simpler headers, no need to print in binary. This versions produce 8khz mono SND file named 'a': ``` open A,'>a';print A".snd",pack"N*",24,-1,2,8e3,1,map{(--$|x3)x(894261072>>$_&1?1600:400)}0..39 ``` The result [file](https://www.dropbox.com/s/l72ujazdidp9qzr/a.snd?dl=0). Old solution. Produces a 1khz 8-bit mono WAV file named 'a': ``` open A,'>a';print A pack"A4lA8lssllssA4ls*",RIFF,17040,WAVEfmt,16,1,1,(1e3)x2,1,8,data,17004,map{($_)x(894261072>>$v++&1?400:100)}(255,0)x20 ``` The result [file](https://www.dropbox.com/s/h00900dda7qfmu4/a.wav?dl=0). To get to 122 characters I had to paste the header in binary instead of packing it which makes the code hard to copy here. The escaped version is: ``` open A,'>a';print A"RIFF\x90B\0\0WAVEfmt \0\0\0\0\0\xe8\0\0\xe8\0\0\0\0datalB\0\0",pack"s*",map{($_)x(894261072>>$v++&1?400:100)}(255,0)x20 ``` Base64 encoding of the actual 122 bytes solution: ``` b3BlbgpBLCc+YSc7cHJpbnQKQSJSSUZGkEIAAFdBVkVmbXQgEAAAAAEAAQDoAwAA6AMAAAEACABk YXRhbEIAACIscGFjayJzKiIsbWFweygkXyl4KDg5NDI2MTA3Mj4+JHYrKyYxPzQwMDoxMDApfSgy NTUsMCl4MjA= ``` [Answer] ## AWK: ~~172~~ 170 bytes ...and without using any wave library! (\*) ``` BEGIN{for(;++i<204;){d=d"\177\177\n";D=D"\n\n"}t=d d d D;d=d D;T=D D D;u=t t t;print".snd\0\0\0\30\0\0\221\306\0\0\0\2\0\0\20\0\0\0\0\1"d d u T u t t T d u t T d d d d d} ``` This outputs a Sun au audio file on stdout which can be played by vlc (among others). While the au fileformat don't have any sample rate limitation, VLC refuses to play any file with a sampling rate inferior to 4096 Hz, so I used this frequency EDIT: Link to [resulting audio file](https://www.dropbox.com/s/avk44q9qn93td2b/morse.au?dl=0) on DropBox --- (\*) Shouldn't there be a bonus for this? ;o) [Answer] # Python, 155 Uses the python built-in wave module. ``` import wave n=wave.open(*"nw") k=17837 n.setparams((2,2,k,0,"NONE",0)) h=k*1314709609 while h:[n.writeframes(`i%9`)for i in[0]*(2-h%2)*k+range(h%4*k)];h/=4 ``` Writes to a file called `n`. Thanks [Sp3000](https://codegolf.stackexchange.com/users/21487/sp3000) for suggestion on using list comprehension for loop (this helped remove a bit of indentation). **Listen to it:** <https://soundcloud.com/bitpwner/morse-the-new-year-2015> [**Here is a link to SoundCloud**](https://soundcloud.com/bitpwner/morse-the-new-year-2015) if the embedded player doesn't work for you. **Commented code:** ``` import wave n=wave.open("n.wav","w") # Open a wav file for writing k=44100 n.setparams((2,2,k,0,"NONE","")) # Sets the minimal params for the wav file w=n.writeframes h=23450475295733 # Contains base-4 morse: '.'=1, '-'=3, ' '=0 while h: for i in range(h%2*k):w(h%4*chr(i%99)) # Writes saw-tooth signal using i%99 w((2-h%2)*k*" ") # Writes the pauses h/=4 ``` [Answer] # C#, ~~556~~ ~~552~~ ~~536~~ ~~535~~ ~~516~~ ~~506~~ ~~503~~ ~~491~~ 483 bytes Uses the library [Wav.Net](https://github.com/ArcticEcho/Wav.Net). ``` using System;using System.Linq;namespace WavDotNet.Core{using S=Samples<float>;class P{static void Main(){var w=new WavFileWrite<float>("a",9999);var b=new Tools.Generators.Sawtooth(9999);Func<long,float,S>g=(t,a)=>b.Generate32Bit(new TimeSpan(t),99,a);var l=2500000;S x=g(l,1),y=g(l*3,1),z=g(l*3,0),_=g(l,0),v=new S(new[]{x,_,x,_,y,_,y,_,y,z,y,_,y,_,y,_,y,_,y,z,x,_,y,_,y,_,y,_,y,z,x,_,x,_,x,_,x,_,x}.SelectMany(c=>c).ToList());w.AudioData.Add(new Channel<float>(v,0));w.Flush();}}} ``` Outputs to a file named `a`. **[Result hosted on Dropbox](https://www.dropbox.com/s/m2qchcese9jvj1g/Morse2015.wav?dl=0)** Ungolfed code: ``` using System; using System.Linq; namespace WavDotNet.Core { using FloatSamples = Samples<float>; class P { static void Main() { var file = new WavFileWrite<float>("output.wav", 9999); var sawtoothGen = new Tools.Generators.Sawtooth(9999); Func<long, float, FloatSamples> generate = (t, amplitude) => sawtoothGen.Generate32Bit(new TimeSpan(t), 99, amplitude); var length = 2500000; FloatSamples shortBeep = generate(length, 1), longBeep = generate(length * 3, 1), shortPause = generate(length * 3, 0), longPause = generate(length, 0), allSamples = new FloatSamples(new[] { shortBeep, longPause, shortBeep, longPause, longBeep, longPause, longBeep, longPause, longBeep, shortPause, longBeep, longPause, longBeep, longPause, longBeep, longPause, longBeep, longPause, longBeep, shortPause, shortBeep, longPause, longBeep, longPause, longBeep, longPause, longBeep, longPause, longBeep, shortPause, shortBeep, longPause, shortBeep, longPause, shortBeep, longPause, shortBeep, longPause, shortBeep } .SelectMany(c => c).ToList()); file.AudioData.Add(new Channel<float>(allSamples, 0)); // 0 == ChannelPositions.Mono file.Flush(); } } } ``` [Answer] # Python ~~3~~ 2, ~~191~~ ~~188~~ ~~174~~ 171 (no libraries) Wav files are incredibly simple. Wanted to try without libraries. For some reason my files seem to crash Windows Media Player. Quicktime ~~works~~ bugs out halfway into the file. Conversion to a larger sample rate using Audition fixes this. **Update**: Implemented some optimizations from the Perl answer. Now outputs with just the name `n` and in 1000Hz sampling. Edited info above accordingly. ``` w,s=200*" ",50*"~~ " a,b,c=s+w,3*s+w,2*w open(*"nw").write("RIFF\xD46\0\0WAVEfmt \20\0\0\0\1\0\1\0\xE8\3\0\0\xE8\3\0\0\1\0\10\0data\xB06\0\0"+a*2+b*3+c+b*5+c+a+b*4+c+a*5) ``` ### Old version ``` w,s=1600*" ",200*"~~~~ " a,b,c=s+w,3*s+w,2*w open("n.wav","wb").write("RIFF\244\265\1\0WAVEfmt \20\0\0\0\1\0\1\0@\x1f\0\0@\x1f\0\0\1\0\10\0data\200\265\1\0"+a*2+b*3+c+b*5+c+a+b*4+c+a*5) ``` [Answer] ## ~~AWK~~ BASH: ~~66~~ ~~86~~ ~~67~~ 74 bytes As requested by Martin Büttner, I added a tempo since after checking the [ABC Notation standard](http://abcnotation.com/wiki/abc:standard:v2.1#qtempo), it seems there is no defined default value for this (thanks nutki for pointing this). I also write into a disk file (a) instead of STDOUT since the question wanted explicitly "a file on disc". ``` a=C3z;echo "X:1 K:A Q:99 CzCz$a$a$a3$a$a$a$a${a}3Cz$a$a$a${a}3CzCzCzCzC">a ``` I put a tempo of 99 which causes the audio file to last 22 seconds; It's slower than my previous version, but at least now it is supposed to be the same length on every ABC player, and it fit under 30 seconds. It looks ... very much like the previous version as you can see: ![Last (I hope :o) ) version of 2015's score](https://i.stack.imgur.com/rXkok.jpg) Here is [the new midi file](https://www.dropbox.com/s/l05gjzrd3uqrgmd/morse4.mid?dl=0). ## First BASH version (tempo is missing) Why didn't I think to this first... :o) That's 22 less bytes than with AWK, for the same result ``` a=C3z;echo "X:1 K:A CzCz$a$a$a3$a$a$a$a${a}3Cz$a$a$a${a}3CzCzCzCzC" ``` Like the previous version in AWK, it write on stdout a valid "ABC" notation file (thanks Tobia for finding out that the "L" statement was optional) It looks like this: ![last version of "2015" partition](https://i.stack.imgur.com/s2QXl.jpg) And it sounds [exactly like the previous version](https://www.dropbox.com/s/n2g3b30z0ngj1ge/morse2.mid?dl=0). ## Previous version in AWK (86 Bytes) Here is a new version; a little longer, but with a more accurate timing. I let the first version bellow for comparison/reference: ``` BEGIN{a="C3z";print"X:1\nK:A\nL:1/8\nCzCz"a a a"3"a a a a a"3Cz"a a a a"3CzCzCzCzCz";} ``` This is still a valid "abc" file, which looks like this: ![score of 2015](https://i.stack.imgur.com/pfy3O.jpg) Here is [the new midi file](https://www.dropbox.com/s/n2g3b30z0ngj1ge/morse2.mid?dl=0) (I accelerated the tempo to stay under the 30 seconds limit). ## First version in AWK (66 Bytes): This is a lot less interesting than [my previous answer](https://codegolf.stackexchange.com/a/43132/34386), but it is a lot shorter, so: ``` BEGIN{print"X:1\nK:A\nL:1/4\nCCC2C2C2zC2C2C2C2C2zCC2C2C2C2zCCCCC"} ``` This outputs a valid "abc" file, which can be read into (among others) EasyABC. It will look like this: ![Score of "2015" in morse](https://i.stack.imgur.com/uYOaM.jpg) and it will sound [like this (midi file)](https://www.dropbox.com/s/z02u551akgqt2xu/morse.mid?dl=0). + [Answer] # C# ~ 485 bytes Using the [Wav.Net](https://github.com/ArcticEcho/Wav.Net) library. ``` using WavDotNet.Core;namespace System.Collections.Generic{using f=Single;class T{static void Main(){var i=new WavFileWrite<f>("x",8000);Func<long,Samples<f>>g=d=>new WavDotNet.Tools.Generators.Sawtooth(8000).Generate32Bit(new TimeSpan(d),600,1);var s=new List<f>();var k="..--- ----- .---- .....";foreach(var c in k){s.AddRange(c=='.'?g(2000000):g(6000000));s.AddRange(new f[1600]);if(c==' '){s.AddRange(new f[3200]);}}i.AudioData.Add(new Channel<f>(new Samples<f>(s),0));i.Flush();}}} ``` And [here's](https://drive.google.com/file/d/0BzrSbYUBjyaZVEhZTW5iUVFyNXc/view?usp=sharing) the output. Readable version, ``` using WavDotNet.Core; namespace System.Collections.Generic { using f = Single; class T { static void Main() { var i = new WavFileWrite<f>("x", 8000); Func<long, Samples<f>> g = d => new WavDotNet.Tools.Generators.Sawtooth(8000).Generate32Bit(new TimeSpan(d), 600, 1); var s = new List<f>(); var k = "..--- ----- .---- ....."; foreach (var c in k) { s.AddRange(c == '.' ? g(2000000) : g(6000000)); s.AddRange(new f[1600]); if (c == ' ') { s.AddRange(new f[3200]); } } i.AudioData.Add(new Channel<f>(new Samples<f>(s), 0)); i.Flush(); } } } ``` [Answer] # C# ~~382~~ 333bytes Doesn't use any non-standard libraries, writes out an 8bits-per-sample 44100samples-per-second wav, with what I hope is a valid header (seems to play/load happily in WMP/.NET/Audacity). The header is base64 encoded, and the morse is encoded as signal on/off which is stored in a single long (64bits) because the last 5 bits are the same as the first. The result can be found [here](http://visualmelon.onl/w.wav) Golfed code: ``` using System.IO;class P{static void Main(){using(var w=new FileStream("w.wav",FileMode.Create)){int i=0,d=9980;w.Write(System.Convert.FromBase64String("UklGRhCCCgBXQVZFZm10IBAAAAABAAEARKwAAESsAAABAAgAZGF0YeyBCgA="),0,44);for(var k=5899114207271221109L;i++<d*69;w.WriteByte((byte)(System.Math.Sin((k>>(i/d)%64&1)*i*0.1)*127+127)));}}} ``` With comments: ``` using System.IO; class P { static void Main() { using(var w=new FileStream("w.wav",FileMode.Create)) { int i=0,d=9980; // d is samples per tone // write wav header w.Write(System.Convert.FromBase64String("UklGRhCCCgBXQVZFZm10IBAAAAABAAEARKwAAESsAAABAAgAZGF0YeyBCgA="),0,44); for(var k=5899114207271221109L; // 0101000111011101110111010001110111011101110111000111011101110101 as long i++<d*69; // 69 is number of bits w.WriteByte((byte)( System.Math.Sin( (k>>(i/d)%64&1) // read bit (0 or 1) *i*0.1) // mul by ticker (sin(0) = 0) *127+127)) // make sensible ); } } } ``` [Answer] # [SuperCollider](http://supercollider.sourceforge.net/), ~~625~~ 605 bytes Audio programming language submission! Output is written to a file `b` in AIFF format. Windows Media Player fails to open it, but it works fine in VLC media player. The generated file `a` is an [OSC file](https://en.wikipedia.org/wiki/Open_Sound_Control). ``` c=0;d=0;f={c=c+d;d=0.2;[c,[\s_new,\w,1001,0,0,\freq,800]]};g={c=c+d;d=0.2;[c,[\n_free,1001]]};h={c=c+d;d=0.6;[c,[\s_new,\w,1001,0,0,\freq,800]]};i={c=c+d;d=0.6;[c,[\n_free,1001]]};x=[f.value,g.value,f.value,g.value,h.value,g.value,h.value,g.value,h.value,i.value,h.value,g.value,h.value,g.value,h.value,g.value,h.value,g.value,h.value,i.value,f.value,g.value,h.value,g.value,h.value,g.value,h.value,g.value,h.value,i.value,f.value,g.value,f.value,g.value,f.value,g.value,f.value,g.value,f.value,i.value];Score.recordNRT(x,"morse.osc","Morse2015.aiff");SynthDef("w",{arg freq=440;Out.ar(0,SinOsc.ar(freq,0,0.2))}).writeDefFile; ``` I created a few SuperCollider functions: `f` generates a short beep, `g` a short break, `h` a long beep and `i` a long break. SuperCollider needs the starting positions for each sine wave and not a length, so I had to create functions that generate a wave with the correct starting position and I have to call the functions each time I need a sine wave. (I could not store a wave with a specific length in a variable to reuse). The `\w` definition is created at the end of the code block. On my Windows computer, it did not save the audio file in the same directory as my code, but in this directory: ``` C:\Users\MyName\AppData\Local\VirtualStore\Program Files (x86)\SuperCollider-3.6.6 ``` **[Result hosted on Dropbox](https://www.dropbox.com/s/opia403cpxfav7g/Morse2015.aiff?dl=0)** Code with indentation: ``` c = 0; d = 0; f = { c=c+d;d=0.2;[ c, [ \s_new, \w, 1001, 0, 0, \freq, 800 ] ] }; g = { c=c+d;d=0.2; [ c, [\n_free, 1001]] }; h = { c=c+d;d=0.6; [ c, [ \s_new, \w, 1001, 0, 0, \freq, 800]]}; i = { c=c+d;d=0.6;[ c, [\n_free, 1001]] }; x = [ f.value, g.value, f.value, g.value, h.value, g.value, h.value, g.value, h.value, i.value, h.value, g.value, h.value, g.value, h.value, g.value, h.value, g.value, h.value, i.value, f.value, g.value, h.value, g.value, h.value, g.value, h.value, g.value, h.value, i.value, f.value, g.value, f.value, g.value, f.value, g.value, f.value, g.value, f.value, i.value ]; Score.recordNRT(x, "morse.osc", "Morse2015.aiff"); SynthDef("w",{ arg freq = 440; Out.ar(0, SinOsc.ar(freq, 0, 0.2) ) }).writeDefFile; ``` [Answer] # ChucK - ~~1195~~ ~~217~~ ~~201~~ ~~147~~ ~~145~~ 144 ChucK is an audio programming language. bitpwner helped me get this down from 201 bytes to 147 bytes. ``` SinOsc s;WvOut w=>blackhole;"y"=>w.wavFilename;int j;for(1016835=>int i;i>0;2/=>i){s=>w;j++;(i%2?200:600)::ms=>now;s=<w;(j%5?200:600)::ms=>now;} ``` [**Here is a direct link to SoundCloud**](https://soundcloud.com/ksft/2015-morse-code-1) if the embedded player doesn't work for you. [Answer] # Csound, 140 + 40 = 180 Audio programming language. This is the Orchestra file: ``` instr 1 a1 oscil 2^15,990,1 out a1 endin ``` and this is the Score file: ``` f1 0 512 10 1 t0 300 i1 0 1 i1 2 i1 40 i1 60 i1 62 i1 64 i1 66 i1 68 i1 4 3 i1 8 i1 12 i1 18 i1 22 i1 26 i1 30 i1 34 i1 42 i1 46 i1 50 i1 54 ``` The sizes are computed assuming no extra whitespace, single line terminator (UNIX) and no terminator after the last line. You invoke them using the csound command: ``` csound morse.org morse.sco ``` which will produce an output file in the current directory, by default named "test.aif" <https://soundcloud.com/whatfireflies/morse-code-golf-in-csound/s-qzsaq> I could have shaved two or three bytes by choosing an uglier waveform, but I like the sound of the traditional Morse sine wave. PS: I'm a total newbie at Csound, any golfing tips are appreciated, especially concerning the score file! [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 649 bytes ``` ++[>-[+>++[++<]>]>[>..........-..........+<-]-[+>++[++<]>]>[....................-]<<<<<-]+++[>+++[>-[+>++[++<]>]>[>..........-..........+<-]<<<-]-[+>++[++<]>]>[....................-]<<<-]-[+>++[++<]>]>[....................-]+++++[>-[+>++[++<]>]>[....................-]+++[>-[+>++[++<]>]>[>..........-..........+<-]<<<-]<<<-]+++[>-[+>++[++<]>]>[....................-]<<<-]-[+>++[++<]>]>[>..........-..........+<-]++++[>-[+>++[++<]>]>[....................-]+++[>-[+>++[++<]>]>[>..........-..........+<-]<<<-]<<<-]++[>-[+>++[++<]>]>[....................-]<<<-]+++++[>-[+>++[++<]>]>[....................-]-[+>++[++<]>]>[>..........-..........+<-]<<<<<-] ``` This generates a sequence of 8 bit unsigned samples that may be played at 8000 samples per second with a tool such as `aplay` on Linux. Credit to [table of BF constants](https://esolangs.org/wiki/Brainfuck_constants). [Try it online!](https://tio.run/##SypKzMxLK03O/v9fWzvaTjda2w5Ia2vbxNrF2kXb6cGBLoKpbaMbi6ZQDwvQjbUBAd1YbZDJ2iQZD9ZHrB1EqtTWxuYGnGpJdS3Cq2S7G7cNdHE6KS4nJTBJcQzI7P//AQ "brainfuck – Try It Online") Somewhat less golfed ``` DIT DIT DAH DAH DAH ++[> -[+>++[++<]>]>[>..........-..........+<-] -[+>++[++<]>]>[....................-] <<<<<-] +++[> +++[> -[+>++[++<]>]>[>..........-..........+<-] <<<-] -[+>++[++<]>]>[....................-] <<<-] -[+>++[++<]>]>[....................-] DAH DAH DAH DAH DAH +++++[> -[+>++[++<]>]>[....................-] +++[> -[+>++[++<]>]>[>..........-..........+<-] <<<-] <<<-] +++[> -[+>++[++<]>]>[....................-] <<<-] DIT DAH DAH DAH DAH -[+>++[++<]>]>[>..........-..........+<-] ++++[> -[+>++[++<]>]>[....................-] +++[> -[+>++[++<]>]>[>..........-..........+<-] <<<-] <<<-] ++[> -[+>++[++<]>]>[....................-] <<<-] DIT DIT DIT DIT DIT +++++[> -[+>++[++<]>]>[....................-] -[+>++[++<]>]>[>..........-..........+<-] <<<<<-] ``` ]
[Question] [ I have one hundred vaults, each one within another. Each vault has a password, consisting of a single number. > > 95 43 81 89 56 89 57 67 7 45 34 34 78 88 14 40 81 23 26 78 46 8 96 11 28 3 74 6 23 89 54 37 6 99 45 1 45 87 80 12 92 20 49 72 9 92 15 76 13 3 5 32 96 87 38 87 31 10 34 8 57 73 59 33 72 95 80 84 11 4 11 11 37 71 77 91 49 21 52 48 43 11 77 52 64 3 9 21 38 65 69 84 96 78 7 71 80 78 3 97 > > > It's too hard to memorize all these passwords, and it's not safe to keep the passwords on a piece of paper. The only solution I can think of is to use a program with exactly one hundred characters. The password to the `n`th vault will be found by treating the first `n` characters of the code as a program. Thus, the first character of the program, if run as a program by itself, must output `95`. The first two characters by themselves must output `43`. The entire program must output `97`. I admit that this is really hard. So just do your best. **Try to make your program work for as many vaults as possible**, and I'll memorize the passwords to the rest. ## Rules * If there is a tie, the winner is the earliest submission. * Standard loopholes forbidden. That includes reading from other files or from the Internet. * You have a few options for the code: + A full program which prints the correct number + A function which returns or prints it + An expression which evaluates to it (e.g. in C, `4+3` evaluates to `7`) * You *may* assume a REPL environment * You *may* use different techniques for each value of `n`. For example, you can use different languages for each `n`, or sometimes use a full program and sometimes a function. *Note: This scenario is completely fictional. If you have a similar issue, do not post your passwords online.* [Answer] # ><> (Fish), 95 Starting after the `'` puts all characters onto the stack and at the end of the line it wraps around; closes the string with the same `'`; outputs the top of the stack as a number (`n`) and finish execution (`;`). Characters for 13 and 10 were changed to space to not ruin the layout of the code (as fish is a 2D language.) Some non-printable ASCII disappears in the answer. [Correct program here.](http://pastebin.com/raw.php?i=egvcY2Tc) ``` 'n;Y8Y9C-""NX(QN.`JY6%c--WP\1H \LX `W&WX"9I;!H_PT%GM[140+M4@ &AET`NGPNa ``` Thanks for [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner) and [Sp3000](https://codegolf.stackexchange.com/users/21487/sp3000) for improvements of 2 and 5 bytes. Hex dump: ``` 0000000: 276e 3b59 3859 3943 072d 2222 4e58 0e28 'n;Y8Y9C.-""NX.( 0000010: 5117 1a4e 2e08 600b 1c03 4a06 1759 3625 Q..N..`...J..Y6% 0000020: 0663 2d01 2d57 500c 5c14 3148 095c 0f4c .c-.-WP.\.1H.\.L 0000030: 5803 0520 6057 2657 1f58 2208 3949 3b21 X.. `W&W.X".9I;! 0000040: 485f 5054 0b04 0b0b 2547 4d5b 3115 3430 H_PT....%GM[1.40 0000050: 2b0b 4d34 4003 0915 2641 4554 604e 0747 +.M4@...&AET`N.G 0000060: 504e 0361 PN.a ``` [Answer] # CJam, 40 I just used a greedy approach (most of the time) to print the next possible number (carets mark correct program ends): ``` 43;56) ; 34 K- 9+ 2* ;11;3Z+;54;6;1 ;80C+K- K+G-;32 6+ 7-Z+;73( ; 11 60+K+;52;11;64;9;65;7 8;1;8 ^ ^ ^ ^^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^^ ^ ^ ^ ^ ^ ^ ^ ^^^ ^ ``` The following numbers are printed correctly: > > 95 **43** 81 89 **56** 89 **57** 67 7 45 **34** **34** 78 88 **14** 40 81 **23** 26 78 **46** 8 96 **11** 28 **3** 74 **6** 23 89 **54** 37 **6** 99 45 **1** 45 87 **80** 12 **92** 20 49 **72** 9 **92** 15 **76** 13 **3** 5 **32** 96 87 **38** 87 **31** 10 **34** 8 57 **73** 59 33 **72** 95 80 84 **11** 4 **11** **11** 37 **71** 77 **91** 49 21 **52** 48 43 **11** 77 52 **64** 3 **9** 21 38 **65** 69 84 96 **78** **7** **71** 80 **78** 3 97 > > > [Test it here.](http://cjam.aditsu.net/) [Answer] # CJam, 56 Here is a somewhat more elaborate approach. It prints the last 56 numbers correctly: ``` 0{;"箪⇓ⲩ䏨攛믹Ğᅏꛥ훻ᆾ㼖ꦅ땶읥湓ᠤ䡶"2G#b99bW):W=}:F;FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ``` Chances are, SE has swallowed some characters, [so here's a pastebin](http://pastebin.com/qs1N3LZq). You can try the code [here](http://cjam.aditsu.net/). It makes use of the fact, that the challenge asks for the programs in characters, so I'm using Unicode characters to encode the last 56 characters in a function, which then leaves the correct element on the stack by incrementing a variable on each invocation and selecting the corresponding element. The rest of the code just calls the function repeatedly. The first correct program is the one ending at the second `F` in the code. I've fiddled around with the length of characters to be encoded for a while until I hit the right balance to make as much use as possible. One or two more might be possible with this approach. [Answer] # (vintage) C - 88 *No need for all these silly dedicated golfing languages. Better go back to the good old days, before the quiche eaters and their "program = algorithm+data" nonsense ruined all the fun.* The code is a C function, stored as a string. It returns the binary value as an integer. Run it in DosBox with Borland Turbo C 2.0. There are no control characters in the string, so a copy-paste should work. Compile with **`tiny`** memory model or else... ``` typedef int (* pfun)(); main () { pfun passwd = (pfun) "¬< sûŠDþ,#ÃEq{1Kt:=qQ+ƒ.?&m):|YH)†P$Pzs/7Tk,2o0&(CƒzIzB-E+\l^Dk‚sw.'..Hjp~T8WSN.pWc&,8Idhwƒq*jsq&„"; printf ("password %d\n", passwd()); } ``` If you disassemble the start of the string, you'll see something like: ``` scan: lodsb cmp al,32 jae scan mov al,[si-2] sub al, 35 ret ``` since `si` is used as function address, it points directly to the code, followed by the passwords. All values are shifted by 35 to avoid escaping control characters and double quotes. The code is 11 bytes long, so it will work up to 12 characters. Unfortunately, the 11th value (34) is too low to produce a valid password with an increased shift value (`ret` opcode is 195, so you would need a shift of 161, and the maximal shift to avoid a rollover is 255-99=156). 11 characters will produce a wrong value, and your virtual PC will experience severe (and usually lethal) undefined behaviours with 10 characters or less. [Answer] # Pyth, ~~92~~ 93 ``` +_32Ce"c'MBBnx.Hq7:nN(+<#j&7yVE&M!Mwp,|4Qh)|/l-#%@wFw?*B(Yi[Ahpt+$++Egm{Q5TPK+mT`#)5Faetn'gpn# ``` The above code will obviously be messed up because SE removes control characters, so find the actual code [here](http://pastebin.com/9HbiMbUF) The logic is simple, the string is the character representation of each number, except for the first 3 which are used by the conversion logic and some quotes and newlines which I replaced with dummy characters. I will try to increase the score here. [Try it online here](http://pyth.herokuapp.com/) [Answer] # Matlab ~~37~~ 39 You can use part (without the semicolons) of this idea with any programming language you like, that prints the results directly to console. This will produce at least 39 times the right answers. (I did not check those where only a half number might give a correct answer, but I've found two so far.) ``` 43+13+11-33+54;81;78;8+20;74+15-83;01+79-59-12+6-2;;87+0-53+39;72;;11+00+66-56+22;52;3*7+48;78-7+7+0 ``` [Answer] # [Python 3](https://docs.python.org/3/), Score 71 ``` sum(*open(__file__,'br'))%112#M_Q]:D,*i,P( 1S#=1fr@g?18[V1bV'at'iwp"v~FTlkPBW|3v|t|^)@yn%^ ``` [Try it online!](https://tio.run/##NVJRa5xAEH73pe1TSkPpsCGcXjbg6J67CpIQSt8KKSnpg1zEM2sqvaiod83RS//6dfbWguO3zvfNN@PudrvxZ9uEh7J91Clj7DBsnt152@nGzfOqXus857NVP/O8c8Tg7Gv@bZl85vOa37ofT/DuLMWqP71@ukKVvb/Ht6v72Ukxzurf3Qe2/fvl@6f1r9ubH/twu393Or7ZP3jXu@b84UCNMkwucek4Q5rFCw4i5KCQIuawiCaUHCIKegRJQmFDKqIpkNbCt2UBlQeR5YQp5xAToKFoTawkdWSFR29jJo@pOLb@aEFRVpEtBkRRBLQWJJHm26aQZNLYh0drM1tgG5riUE1IhujbmZX9G2nUZBKGk9/C9lLCzjqBCTOcJJSEMdoRAsIFlQllNwwn3uQicZxlUpkZIjKPYmseT3szmZqe0u5LLOkQynbTjJCC71RtDzXUDfRF86Rd9H0vcWDsd/SGMjXXJEvqC3NyAHUFelus3ZL/YebKsGRdPK8ei/lLkq12ox6IYZuxulTMW3L2/0KxhLFXL01hyOql8QXb/yIFJFv9UupuTKArhsHp@roZXXZXtr1OGLdK7/AP "Python 3 – Try It Online") Note: the code contains unprintable char Read the code source, and sum all the char value modulo 112 (to include the comment sign `#`. Then adjust each value with the right char in a comment [Answer] # Python 2, 39 I wrote a script that tries lots of combinations of expressions, and tests them against the safe combinations. The best I could manage was 39 matches. I was surprised how many combinations resulted in the score of 39. I have included a sample in my answer. I tried including the logical `^&|` operators but the precedence rules got complicated. ``` 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2*5+82+0-53+39 -1+8-76+33+54-39-41*0-43/3+46-6-7*011 43+13+11-33+54/8-14-18+3-8+3+48*0 -5+79-60-11+67-71+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2+19 +6-7+3+39 -1+12-73 +66-56+22 +9-43/3+46-6-7*011 43+13+11-33+54/8-14-18+3+63/5+14 +8+0-33+8-11+67-71+82+0-53+39 -1+8-76+33+54-39-9 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35+63/5+14 +8+0-33+8-11+67-71+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35+63/5+14 +8+0-33+8-11/2-2+19 +6-7+3+39 -1+8-76+33+54-39-9 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48+45-54-33+8-11/2-2*5+82+0-53+39 -1+12-73 +66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48+45-54-33+8-11/2-2+19 +6-7+3+39 -1+8-76+7+66-56+22 +9-43/3+46-6 +2+17 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2*5+82+0-53+39 -1+8-76+33+54-39-9 +9-43/3+46-6-7-681 43+13+11-33 -20 +9+23-35-8+3+48+45-54-33+8-11/2-2*5+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6 +2+17 43+13+11-33 -20 +9+23-35+63/5+14 +8+0-33+8-11+67-71+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6 +2+17 43+13+11-33 -20 +9+23-35-8+3+48+45-54-33+8-11/2-2*5+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7*011 43+13+11-33+54/8-14-18+3-8+3+48*0 -5+79-60/7-57-2*5+82-56+3+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35+63/5+14 +8+0-33+8-11/2-2+19 +6-7+3+39 -1+12-73 +66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60-11+67-71+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7-681 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2+19 +6-7+3+39 -1+12-73 +66-56+22 +9-43/3+46-6 +2+17 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2*5+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7*011 43+13+11-33+54/8-14-18+3-8+3+48*0 -5+79-60/7-57-2*5+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60-11+67-71+82-56+3+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35+63/5+14 +8+0-33+8-11+67-71+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7-681 43+13+11-33+54/8-14-18+3-8+3+48*0 -5+79-60/7-57-2*5+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6 +2+17 43+13+11-33 -20 +9+23-35-8+3+48+45-54-33+8-11+67-71+82+0-53+39 -1+8-76+33+54-39-9 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2*5+82-56-23+51+36-84+00+66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+20+14 +8+0-33+8-11+67-71+82+0-53+39 -1+8-76+33+54-39-41*0-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2+19 +6-7+3+39 -1+12-73+60-22+3-41*0-43/3+46-6 +2+17 43+13+11-33+54 -7 -35-35-8+3+48*0 -5+79-60/7-57-2*5+82+0-53+39 -1+8-76+33+54-39-41*0-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35+63/5+14 +8+0-33+8-11/2-2*5+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6 +2+17 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2+19 +6-28+47+2+36-84+00+66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+20+14 +8+0-33+8-11+67-71+82+0-53+39 -1+8-76+33+54-39-9 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2+19 +6-28-2+51+36-84+00+66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60-11/2-2*5+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6 +2+17 43+13+11-33 -20 +9+23-35+63/5+14 +8+0-33+8-11/2-2*5+82+0-53+39 -1+8-76+33+54-39-9 +9-43/3+46-6-7-681 43+13+11-33+54 -7 -35-35-8+3+48*0 -5+79-60-11/2-2*5+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6 +2+17 43+13+11-33+54 -7 -35-35-8+20+14 +8+0-33+8-11/2-2+19 +6-7+3+39 -1+12-73 +66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2+19 +6-28-2+51+36-84+00+66-56+22 +9-43/3+46-6 +2+17 43+13+11-33 -20 +9+23-35-8+20+14 +8+0-33+8-11/2-2*5+82-56+3+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7-681 43+13+11-33+54/8-14-18+3-8+3+48*0 -5+79-60/7-57-2*5+82+0-53+39 -1+8-76+33+54-39-9 +9-43/3+46-6 +2+17 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2*5+82+0-53+39 -1+12-73+60-22+3-9 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60-11/2-2*5+82+0-53+39 -1+8-76+33+54-39-9 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2+19 +6-7+3+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48+45-54-33+8-11/2-2*5+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7-681 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2*5+82-56+3+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2*5+82+0-53+39 -1+8-76+33+54-39-9 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+20+14 +8+0-33+8-11+67-71+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7-681 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2*5+82-56+3+39 -1+8-76+33+54-39-9 +9-43/3+46-6-7-681 43+13+11-33+54/8-14-18+3-8+3+48*0 -5+79-60-11/2-2*5+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6 +2+17 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2*5+82-56-23+51+36-84+0+60-22+3-9 +9-43/3+46-6-7-681 43+13+11-33+54/8-14-18+3-8+20+14 +8+0-33+8-11/2-2*5+82-56+3+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48+45-54-33+8-11/2-2+19 +6-7+3+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48+45-54-33+8-11/2-2+19 +6-28-2+51+36-84+0+60-22+3-41*0-43/3+46-6-7*011 43+13+11-33+54 -7 -35-35-8+20+14 +8+0-33+8-11/2-2*5+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+20+14 +8+0-33+8-11/2-2*5+82-56+3+39 -1+8-76+33+54-39-9 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35+63/5+14 +8+0-33+8-11/2-2*5+82+0-53+39 -1+8-76+33+54-39-9 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+20+14 +8+0-33+8-11/2-2*5+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7*011 43+13+11-33+54/8-14-18+3-8+3+48*0 -5+79-60-11/2-2*5+82+0-53+39 -1+8-76+33+54-39-9 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60-11/2-2*5+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7-681 43+13+11-33 -20 +9+23-35-8+3+48+45-54-33+8-11/2-2*5+82-56+3+39 -1+8-76+7+66-56+22 +9-43/3+46-6 +2+17 43+13+11-33+54/8-14-18+3-8+3+48*0 -5+79-60/7-57-2*5+82-56-23+51+36-84+00+66-56+22 +9-43/3+46-6-7-681 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2+19 +6-7-23+51+36-84+00+66-56+22 +9-43/3+46-6-7*011 43+13+11-33+54/8-14-18+3-8+3+48*0 -5+79-60-11/2-2+19 +6-7+3+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7-681 43+13+11-33 -20 +9+23-35+63/5+14 +8+0-33+8-11+67-71+82-56+3+39 -1+12-73 +66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35+63/5+14 +8+0-33+8-11/2-2*5+82-56-23+51+36-84+00+66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60-11/2-2*5+82+0-53+39 -1+12-73 +66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60-11/2-2*5+82-56+3+39 -1+12-73 +66-56+22 +9-43/3+46-6-7-681 43+13+11-33+54/8-14-18+3-8+3+48*0 -5+79-60/7-57-2+19 +6-7+3+39 -1+8-76+7+66-56+22 +9-43/3+46-6 +2+17 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60-11/2-2+19 +6-7+3+39 -1+8-76+33+54-39-41*0-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2*5+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6 +2+17 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2*5+82+0-53+39 -1+12-73+60-22+3-41*0-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35+63/5+14 +8+0-33+8-11/2-2+19 +6-7-23+51+36-84+00+66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2*5+82+0-53+39 -1+8-76+33+54-39-41*0-43/3+46-6 +2+17 43+13+11-33 -20 +9+23-35-8+20+14 +8+0-33+8-11/2-2*5+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6 +2+17 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2+19 +6-7+3+39 -1+8-76+33+54-39-41*0-43/3+46-6-7-681 43+13+11-33+54 -7 -35-35-8+3+48*0 -5+79-60/7-57-2+19 +6-7+3+39 -1+8-76+7+66-56+22 +9-43/3+46-6 +2+17 43+13+11-33 -20 +9+23-35-8+20+14 +8+0-33+8-11/2-2*5+82+0-53+39 -1+12-73+60-22+3-9 +9-43/3+46-6-7*011 43+13+11-33+54 -7 -35-35-8+3+48*0 -5+79-60/7-57-2*5+82+0-53+39 -1+8-76+33+54-39-9 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2*5+82-56-23+51+36-84+0+60-22+3-9 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2*5+82+0-53+39 -1+12-73 +66-56+22 +9-43/3+46-6 +2+17 43+13+11-33+54/8-14-18+3-8+3+48+45-54-33+8-11/2-2*5+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6 +2+17 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60-11+67-71+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7*011 43+13+11-33+54/8-14-18+3-8+20+14 +8+0-33+8-11/2-2*5+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+20+14 +8+0-33+8-11+67-71+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+20+14 +8+0-33+8-11/2-2*5+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7-681 43+13+11-33 -20 +9+23-35-8+20+14 +8+0-33+8-11+67-71+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6 +2+17 43+13+11-33 -20 +9+23-35-8+3+48+45-54-33+8-11/2-2*5+82-56-23+51+36-84+0+60-22+3-9 +9-43/3+46-6 +2+17 43+13+11-33 -20 +9+23-35-8+20+14 +8+0-33+8-11/2-2*5+82+0-53+39 -1+12-73 +66-56+22 +9-43/3+46-6-7*011 43+13+11-33+54/8-14-18+3+63/5+14 +8+0-33+8-11/2-2*5+82+0-53+39 -1+12-73 +66-56+22 +9-43/3+46-6 +2+17 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60-11/2-2*5+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2*5+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7-681 43+13+11-33 -20 +9+23-35-8+20+14 +8+0-33+8-11/2-2+19 +6-7+3+39 -1+8-76+33+54-39-9 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60-11/2-2+19 +6-7+3+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2*5+82+0-53+39 -1+12-73+60-22+3-9 +9-43/3+46-6-7-681 43+13+11-33 -20 +9+23-35-8+20+14 +8+0-33+8-11/2-2+19 +6-7+3+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+20+14 +8+0-33+8-11+67-71+82+0-53+39 -1+12-73 +66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35+63/5+14 +8+0-33+8-11+67-71+82+0-53+39 -1+12-73 +66-56+22 +9-43/3+46-6-7*011 43+13+11-33+54 -7 -35-35+63/5+14 +8+0-33+8-11/2-2*5+82-56-23+51+36-84+00+66-56+22 +9-43/3+46-6 +2+17 43+13+11-33+54/8-14-18+3-8+3+48*0 -5+79-60/7-57-2*5+82+0-53+39 -1+12-73+60-22+3-9 +9-43/3+46-6 +2+17 43+13+11-33+54/8-14-18+3-8+3+48+45-54-33+8-11/2-2*5+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2*5+82+0-53+39 -1+12-73 +66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2*5+82-56+3+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7-681 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2*5+82-56+3+39 -1+8-76+33+54-39-9 +9-43/3+46-6-7*011 43+13+11-33+54/8-14-18+3+63/5+14 +8+0-33+8-11/2-2*5+82-56+3+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7-681 43+13+11-33 -20 +9+23-35+63/5+14 +8+0-33+8-11/2-2*5+82+0-53+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7*011 43+13+11-33+54/8-14-18+3-8+3+48*0 -5+79-60/7-57-2*5+82+0-53+39 -1+8-76+33+54-39-9 +9-43/3+46-6-7*011 43+13+11-33+54/8-14-18+3+63/5+14 +8+0-33+8-11/2-2+19 +6-7+3+39 -1+8-76+7+66-56+22 +9-43/3+46-6-7*011 43+13+11-33 -20 +9+23-35-8+3+48*0 -5+79-60/7-57-2+19 +6-7+3+39 -1+8-76+33+54-39-9 +9-43/3+46-6-7*011 ``` [Answer] # DEBUG.COM, 93 ``` 0000h: BE FF 00 01 CE AC CC 67 07 45 34 34 78 88 14 40 0010h: 81 23 26 78 46 08 96 11 28 03 74 06 23 89 54 37 0020h: 06 99 45 01 45 87 80 12 92 20 49 72 09 92 15 76 0030h: 13 03 05 32 96 87 38 87 31 10 34 08 57 73 59 33 0040h: 72 95 80 84 11 04 11 11 37 71 77 91 49 21 52 48 0050h: 43 11 77 52 64 03 09 21 38 65 69 84 96 78 07 71 0060h: 80 78 03 97 ``` Usage: ``` DEBUG.COM FILENAME.COM G ``` and the result appears in `AL` ]
[Question] [ Given a position with a row of rooks and/or empty spaces, output how many different rook moves are possible. A rook can move left or right to an empty space, but not to one that requires passing over another rook. When a rook moves, the other rooks remain in place. For example, from this position, **6 moves** are possible: ``` .R..RRR. ``` * The first (leftmost) rook can move 1 space left, or 1 or 2 spaces right (3 moves) * The next rook can only move 1 or 2 spaces left (2 moves) * The third rook cannot move at all because it's squeezed between two other rooks (0 moves) * The last rook can only move 1 space right (1 move) Note that a position might have no rooks at all, or no empty spaces at all. **Input:** A non-empty list (string, array, etc..) of rooks and empty spaces. You can represent them as `True`/`False`, `1`/`0`, `'R'`/`'.'`, or any two consistent distinct single-byte characters or one-digit numbers of your choice. It's up to you which one means rook and which means empty space. **Output:** A non-negative integer. Whole-number floats are also fine. **Test cases** The output is the number on the left. ``` 6 .R..RRR. 0 . 0 R 4 R..RR 3 ...R 8 ..R..R.. 0 ...... ``` For more test cases, here are all inputs up to length 5. ``` 0 . 0 R 0 .. 1 .R 1 R. 0 RR 0 ... 2 ..R 2 .R. 1 .RR 2 R.. 2 R.R 1 RR. 0 RRR 0 .... 3 ...R 3 ..R. 2 ..RR 3 .R.. 3 .R.R 2 .RR. 1 .RRR 3 R... 4 R..R 3 R.R. 2 R.RR 2 RR.. 2 RR.R 1 RRR. 0 RRRR 0 ..... 4 ....R 4 ...R. 3 ...RR 4 ..R.. 4 ..R.R 3 ..RR. 2 ..RRR 4 .R... 5 .R..R 4 .R.R. 3 .R.RR 3 .RR.. 3 .RR.R 2 .RRR. 1 .RRRR 4 R.... 6 R...R 5 R..R. 4 R..RR 4 R.R.. 4 R.R.R 3 R.RR. 2 R.RRR 3 RR... 4 RR..R 3 RR.R. 2 RR.RR 2 RRR.. 2 RRR.R 1 RRRR. 0 RRRRR ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~14~~ 9 bytes ``` w`_+R|R_+ ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8L88IV47qCYoXvv///ig@PigoKB4rniuIC4wmyseSAKJIDAC8YAAAA "Retina – Try It Online") Link includes test cases. Uses `_` for empty space as it's the most pleasant non-regex character. Works by counting the number of substrings that correspond to a valid Rook move. A substring is a valid Rook move if it contains at least one `_` plus a single `R` at either the beginning or the end. [Answer] # [Python 3](https://docs.python.org/3/), ~~30~~ 29 bytes ``` lambda s:sum((s+s).strip())/9 ``` [Try it online!](https://tio.run/##RY5Ra8MgFIXf/RUXX6osbIGOsQZ8GGUPexr42pSRpEoDrRHvDUsJ@@2ZmrGqD@c7nuPV3@g8uO1iVb1cmmt7agArHK9C4APKR6TQeyHl024hg/TVNWgQFByYeCmAgwbQWgOXBRNlMv6Vzuo5qZTJtE2JSBleM@h87v28Eh4Zs0MAM/kCEHoH9/kVS6E2fqO9RVccymkHvYUOlIJN3OaCBkpI/S5V8ShzZRgplqxoV2wQTaDVVesky2v34fxIVQrM@FO7z5H@eI7JaLxP3nRkThXMsRMNnl/zoXck@H4IIV7Dm8NvE7hcfgE "Python 3 – Try It Online") *-1 byte thanks to @JoKing* The function takes a Python byte string as input. Each empty space is encoded as a tab and each rook is encoded as a byte `b'\x00'` having value `0`. The computation is equivalent to `lambda s:(s+s).strip().count(b'\t')` while having a lower byte count. [Answer] # JavaScript (ES6), ~~38~~ 33 bytes *Saved 5 bytes thanks to @JoKing* Takes input as a string. Expects a space for an empty square and any other character for a rook. ``` s=>(s+s).trim().split` `.length-1 ``` [Try it online!](https://tio.run/##dc1BDsIgEAXQfU/xd4WYUo3GuKGH4ARtKq0YLE2H9PoIBnQlmQ1vZv48h32gcTOrbxZ312GSgWTH6EBc@M28GBe0WuN79MLqZfaP5hS8Jg8JguwwuoWc1cK6mU2MOK@q1GY1FKCUQs2BtsW1cPrnF/mYWf3hlJFbkS8lJHJZiHz@svpUPnn7TQP5bsoObw "JavaScript (Node.js) – Try It Online") ### Commented ``` s => // s = input, e.g. " R RRR " (s + s) // double -> " R RRR R RRR " .trim() // remove leading and trailing spaces -> "R RRR R RRR" .split` ` // split on spaces -> [ 'R', '', 'RRR', '', 'R', '', 'RRR' ] .length - 1 // return the length - 1 -> 6 ``` --- # [Python 2](https://docs.python.org/2/), ~~40~~ 33 bytes *Saved 7 bytes thanks to @Grimy* ``` lambda s:(s+s).strip().count(' ') ``` [Try it online!](https://tio.run/##LY2xDsIwDER3vuLUxbZadWCsxE94BYYWFBEJkigOA18f0sDJuju9G5w@5RHDsbrTpT7X13ZfYQvbaDJbyT6xzLf4DoUJJNXFDIMPOBMUUFXQBOqm3XbYUSu/1H5/1kTXBSn7UNAesGMTwdjGgVrYXgeqhy8 "Python 2 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ²x èS ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=sngg6FM&input=IiBSICBSUlIgIg) ``` ²x èS Implicit input string of U ² U + U x Remove trailing and leading whitespace èS Number of spaces ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 16 bytes ``` {+m:ex/s+R|Rs+/} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1o71yq1Qr9YO6gmqFhbv/a/NVdOZl5qsV5uYoGGlp5aml5xYqXm/@Kg4uKgoKBirmKuIC4wm6sYSAKJIDAC8YCACwA "Perl 6 – Try It Online") A regex that matches all exhaustive instances of rooks followed by spaces, or spaces followed by a rook and returns the number of matches. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` «ðÚð¢ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//0OrDGw7POrzh0KL//xUUAA "05AB1E – Try It Online") ``` « # concatenate the input with itself ðÚ # remove leading and trailing spaces ð¢ # count spaces ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~23~~ 15 bytes Double the number of spaces between rooks, grep lines with at least one rook, then count the number of spaces. ``` R.+R $0$0 G`R ``` [**Try it online!**](https://tio.run/##K0otycxLNPyvquGewBWjx6XwP0hPO4hLxUDFgMs9IQjI/68XpKcXFBSkx6XHFcQFZnPpAUkgEQRGIJ4eiAoCQwA "Retina – Try It Online") Though the program uses spaces instead of periods, I added prefix code so that the test cases provided may be easily pasted in and used. I was hoping I could use overlapping matches with `(?<=R.*) | (?=.*R)`, but overlaps aren't quite that aggressive. It would need to count all possible ways a match could be obtained in order to return the correct result with that method. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` t1;ḟẠS ``` [Try it online!](https://tio.run/##PU8rDkIxEPQ9RSUIGv7mBQ4xKA6AIUgMwRAMHoWAQDAkBEUQD5AvHKTvIqXdT0V3d7qfmZnPFotVCMtO4cuz/1wm4bf370NRb462Nbb15lRUuzXBRgKxOjWNL5/@fR/F2lU3X16N/76qXb19TENoW2faFvE5ZzrWIQbQF/85040RKYIHUg36B0/LuMw700sJlCDrhMA9yDU9l3pIe/2UGEHOE5eQKZvSKV9adMRIGSqAMaQPVZQlUZ@IB5QFQ0WyZhWdVWfZYMGxP6SMeAfEz0a4DzEGdZatEVbj6lytZ@9qPrvP9vEH "Jelly – Try It Online") A monadic link taking a list of `0` for rook and `1` for space and returning an integer with the number of moves. The TIO link takes the pasted list of possible boards given in the question, converts to the right format and then outputs the calculated and correct answers. ## Explanation ``` t1 | Trim 1s from end ; | Concatenate to input ḟẠ | Filter out 1s if all input were 1s, otherwise filter out 0s S | Sum ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Spaces for spaces, any other character for rooks. ``` ²x ¸ÊÉ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=sngguMrJ&input=IiBSICBSUlIgIg) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~43~~ 38 bytes ``` Count[Subsequences@#,{0,1..}|{1..,0}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zm/NK8kOrg0qTi1sDQ1Lzm12EFZp9pAx1BPr7amGkjqGNTGqv0PKMoEKlPWtUtzUI5V03eo5qo21AGq0gGRIGhYqwMUAhEGYAImBRaGcGBMmJwhVJMOHNZy1f4HAA "Wolfram Language (Mathematica) – Try It Online") Port of [Neil's Retina solution](https://codegolf.stackexchange.com/a/191192/81203). Uses 1 for spaces and 0 for rooks. [Answer] # Snails, 7 bytes At least it beats Retina :) ``` o \.+\R ``` [Try it online!](https://tio.run/##K85LzMwp/v8/nytGTzsm6P9/vSA9vaCgID0A "Snails – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` ḲẈ+ƝS ``` [Try it online!](https://tio.run/##y0rNyan8///hjk0Pd3VoH5sb/P//f3U9BT09BQUFPXUA "Jelly – Try It Online") -1 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan). `0` represent a rook, `1` represents an empty space. [Answer] # [Stax](https://github.com/tomtheisen/stax), 7 6 5 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` àσQ█ε ``` [Run and debug it](https://staxlang.xyz/#p=85e551dbee&i=%22%09R%09%09RRR%09%22%0A%22%09%22%0A%22R%22%0A%22R%09%09RR%22%0A%22%09%09%09R%22%0A%22%09%09R%09%09R%09%09%22%0A%22%09%09%09%09%09%09%22&m=2) Use tab for empty square and any other character for rook. [Answer] # [C (clang)](http://clang.llvm.org/), 57 bytes ``` i,r,o;g(*n,z){for(o=r=i=0;z--;i=-~i*!*n++)o+=*n?r=1,i:r;} ``` [Try it online!](https://tio.run/##fc7RDoIgFAbge57Cam2oxwaWF0XUg1RrTcvOVodGdZOzVzezWXmhMGA733@AOIhPO0oLpJtDq43OJIhy1nt15opVvBV14LeaAfkOtPeHH24gyC@P6@5mefL71v9l0X/6XWYFggWjUu4RPNzsYCw32mrUQj2CQKEOnuj1PPJ91/jao6XVEnBmVV6wAVJ8uid7Z369JWhGx0X1zHmHxF0nYyknkMJV7GLL@sHh/WGypj6YslTaVnSqhGk7hl04hqgdJ10YtWE18uIF "C (clang) – Try It Online") * Saved 1 thanks to @ceilingcat I realized it didn't worked for empty lists.. Now it works! Plus saved some bytes! 1=rook. 0=space. for(.. i+=*n++?-i:1)// counts spaces or reset extra moves => i=-~i*!\*n++ ( @ceilingcat ) o+=\*n?r=1,i:r; // adds to output -i-(extra moves) when a rook is met plus sets -r-(rook met), -i- will be cleared in for increment sentence. adds -r- for every space(rook met guaranteed ) [Answer] # [Haskell](https://www.haskell.org/), 36 bytes ``` f s=sum$snd.span(>0)=<<[s,reverse s] ``` [Try it online!](https://tio.run/##JYjBCsMgGIPvPkWQgi10pbvXPcR/LT1Ip1uZFfHv9vhz2oUkH8nT8Mt6n7MDa37vDYf7wNGE9jZ2eppm7pP92MQWvGSGgtJXUUhKj0LsZgvQiGkLBxrsJrZuKA3uypwlCCAiyF7WUE196i48Qaf/T5Fc8nd13jw4X9YYfw "Haskell – Try It Online") Uses 1 for empty space, 0 for rook. Counts the number of 1's not in an initial block of ones, and adds that to the result for the reversed string. [Answer] # [Haskell](https://www.haskell.org/), 33 bytes ``` sum.(t.reverse<>t) t=snd.span(>0) ``` [Try it online!](https://tio.run/##JYvBDsIgEETvfMWGmBQSJfVeevLqhat62LRUiYUSFv18EXSysy8zyTyQnnZdi/NxSxlOmFGdt7C5GYQYRinZAhquhV5eiaySfdtEdhizZFlTmBVFDGLsZSHooNNHVmk63TPm0YW6jcmFDDvwGMWi6geSNV44GABjDPA9bzbNrWm58gfzu39TxW/lMy0r3qkcphi/ "Haskell – Try It Online") Anonymous function that takes input as a list of 1s (spaces) and 0s (rooks). This trims spaces from the start and the end of the list, then concatenates the two versions of the list and sums them. This uses GHC 8.4.1 or later to have access to the `<>` operator without importing it. [Answer] # [Python 2](https://docs.python.org/2/), 59 bytes ``` def f(r):S=map(len,r.split('R'));return sum(S)*2-S[0]-S[-1] ``` [Try it online!](https://tio.run/##LY5BDsIgEEXX9hSzGzCUaJc1XmJYNixMhEjSUjLQhadHRCc/7/@81aR3ee1xqvXpPHjBcjb37ZHE6qJindMaikBCKW/sysER8rEJI8/TaJaLbRivtvqdIUOIsKAmrYlIowLsoI6v7KqNX1PP37VDOw@nxCEWyKp9kmUdPg "Python 2 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ²x ¸ÊÉ ``` [Try it online](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=sngguMrJ&input=IiBSICBSUlIgIg) [Answer] # [Haskell](https://www.haskell.org/), ~~68~~ ~~58~~ 54 bytes ``` (n#y)(a:x)|a<1=n+(0#1)x|m<-n+1=y+(m#y)x (_#_)x=0 f=0#0 ``` [Try it online!](https://tio.run/##RYrLCsMgEEX3foXEQBTbQbdF@xGzLSW4aGholFC7MJB/t9NHWhg499w715Bvl2mqVSaxKBkORa3BWZ@0NMKqska3T9r6RctID4XJXvSqeMMGb4SpmXfQecuI2FEbw5j8fB/To5UDxDDzrFx7ZJyfeAMIgIjQkO5Iv8SNr3XbKP8ivu@/wEfO9Qk "Haskell – Try It Online") [Answer] # [Red](http://www.red-lang.org), 46 bytes ``` func[s][length? next split trim append s s sp] ``` [Try it online!](https://tio.run/##XYw7DoAwDEN3TmH1GCzcIWvVAdEUKkEUtUHi9kWw8LEnP1suHBtx9KFLPVraZfI1@JVltmWA8GGoumaDlbxhVGWJqJc1NC1ZDAkOBBARXPegm@GN7tE345e/F@/ukmsn "Red – Try It Online") Just a [Red](http://www.red-lang.org) port of [Arnauld's JavaScript/Python solutions](https://codegolf.stackexchange.com/a/191182/75681). Takes a space as an empty square. [Answer] # Java 11, ~~35~~ 32 bytes ``` s->(s+s).strip().chars().sum()/9 ``` Port of [*@Joel*'s Python 3 answer](https://codegolf.stackexchange.com/a/191195/52210). -3 bytes thanks to *@Joel* as well. Uses NULL-bytes (`\0`) for Rooks and tabs (`\t`) for spaces. [Try it online.](https://tio.run/##bVHBbsIwDL3zFVZOiTpCrxsaf8AuHMcOIWRboA1R7SKhiW8vbhoEqyorjvzs5xc7B3M288P@2NnKIMLa@PA3A/CBXPNtrIMP6OOEgJUbanz4AVRLBq8zdkiGvOWyAO/Q4XwlsUClkQujVNr@mgb5xraWavHaLXtObHcVczL1fPJ7qFk4d//8AqMGUXJIUmxpW/LpfW8kkvojO4rLcXznjnkDPoGWDz/JoYlMebdJ9X9az3tLw6fSvFofYkt5/M0FydX61JKOnKQqyJTWjYsVf04a9kVw2yeEGOHHFeINRBG0HSgqK1@7Gw) I tried using `s->(s+s).trim().chars().sum()/9` at first as 31-byter, but this doesn't work because the [`String#trim` builtin](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#trim()) not only removes leading and trailing spaces/tabs/newlines, but also all other bytes that are smaller than or equal to `U+0020` (unicode 32; a space), so it'll remove the NULL-bytes as well.. Thanks to *Joel* for recommending me the new Java 11+ [`String#strip` builtin](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#strip()) (which I forgot they added) as alternative. This one also removes trailing/leading portions, but in this case only [whitespaces](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Character.html#isWhitespace(int)), so the NULL-bytes are retained. **Explanation:** ``` s-> // Method with String as parameter & integer return-type (s+s) // Concatenate the input to itself .strip() // Then trim all leading and trailing tabs .chars().sum() // Sum the unicode values of the remaining characters /9 // And divide it by 9 to get the amount of remaining tabs ``` [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=sum -pF/R/`, 40 bytes ``` $\=2*sum map$_=y///c,@F}{$\-="@F"+$F[-1] ``` [Try it online!](https://tio.run/##K0gtyjH9/18lxtZIq7g0VyE3sUAl3rZSX18/WcfBrbZaJUbXVsnBTUlbxS1a1zD2/389vSAw@pdfUJKZn1f8X9fXJ7O4xMoqtCQzxxZoBFDAVM/A0OC/boGbfpA@AA "Perl 5 – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 27 bytes ``` x=>(x+x).Trim().Sum(d=>d)/9 ``` Saved a byte thanks to @someone [Try it online!](https://tio.run/##RcyxCsIwEIDhvU9x3HSHNbpKTUYf4BRcutQklYBNJUmlbx@hDq4f/L/Ne5tDvSzRnnNJIT7bEIsZdV21oXW3srqlMBGr6zKR08bx4VS75jMHB8XnQr8KHvOQHIM2cE@heBppEyX@/RqsJxRsAfsj8p8AW@wLMnPXNNsMQQBEBJC7@gU "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~7~~ 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) -1 byte thanks to recursive ``` ╣ë|óêπ ``` [Run and debug it](https://staxlang.xyz/#p=b9897ca288e3&i=%22+R++RRR+%22%0A%22+%22%0A%22R%22%0A%22R++RR%22%0A%22+++R%22%0A%22++R++R++%22%0A%22++++++%22&m=2) [Answer] # [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), 73 bytes ``` #;ep10fp#;>#v~:'.-#v_$1+0k v0+ge0*gf0$_v#!-R':< >ep20fp v >0fg1-*0eg+.@ ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9Xtk4tMDRIK1C2tlMuq7NS19NVLotXMdQ2yOYqM9BOTzXQSk8zUIkvU1bUDVK3suGySy0wAipXUFAoU7AzSEs31NUySE3X1nP4/18vSE8vKChIDwA "Befunge-98 (PyFunge) – Try It Online") [Answer] ## [C](https://en.wikipedia.org/wiki/C_%28programming_language%29), 183 156 151 ~~137~~ ~~96~~ 91 bytes Thanks to ceilingcat for 91 bytes. ``` c,e;char*z,b[9];main(d){for(gets(z=b);e=*z>81?c-=e*~!d,d=0:e+1,*++z;);printf("%i",d?:c+e);} ``` R is a rook, everything else is a space. [TIO](https://tio.run/##BcFLDoIwEADQu5CY9DNt7E6ZjNyhW@MCpgN2IZrKqgSvXt9jtzC3xpBAkJ9jMRWm@/WBrzGvSu/zu6hFtq@qNGkUMvV2CQM7EvNLkCjAuRcbwFhbUeOn5HWbVXfKHbClNEjvWOPRmo/exxj9Hw) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 7 bytes ``` /r6*2Qd ``` [Try it online!](https://tio.run/##K6gsyfj/X7/ITMsoMOX/f6UgBYWgICUA "Pyth – Try It Online") Takes a string of `R` for rooks, (space) for empty spaces ``` / d # Count spaces in r6 # Strip spaces from *2Q # 2 * input() (= concatenation) ``` [Answer] # x86-64 - 26 Bytes Input is an array of up to 32 bits and an integer representing number of squares, 1 representing rook, 0 representing empty. ``` C4 E2 69 F7 C1 shlx eax,ecx,edx 0B C1 or eax,ecx F3 0F BC C8 tzcnt ecx,eax D3 E8 shr eax,cl F3 0F BD C8 lzcnt ecx,eax F7 D0 not eax F3 0F B8 C0 popcnt eax,eax 2B C1 sub eax,ecx C3 ret ``` Copies the bits so that it is added to the left of it and removes the trailing zero bits. Then gets number of leading zero bits and subtracts it from the total number of zero bits. # x86-64 Machine Code - 22 Bytes - regular length chess ranks only. Input is a 32-bit integer with the least significant byte made of 8 bits representing the rooks. 1 is a rook, 0 is empty. ``` 8A E9 mov ch,cl 91 xchg eax,ecx F3 0F BC C8 tzcnt ecx,eax D3 E8 shr eax,cl F3 0F BD C8 lzcnt ecx,eax F7 D0 not eax F3 0F B8 C0 popcnt eax,eax 2B C1 sub eax,ecx C3 ret ``` Copies the bits into the next significant byte and removes the trailing zero bits. Then gets number of leading zero bits and subtracts it from the total number of zero bits. ]
[Question] [ Given a string `x`, output the characters in `x` sorted according to the order of appearance in your source code. ## Examples ``` Source: ThisIs A Test Input: Is it a Test? Output: TissI etta? Source: Harry - yer a wizard. Input: I'm a what? Output: aa wh'?Imt Source: Mr. H. Potter, The Floor, Hut-on-the-Rock, The Sea Input: Output: ``` ## Rules * Standard loopholes & i/o rules apply * Input & output can be either a string, a list of characters, or a list of bytes. * If a character is used multiple times in the source, use the first occurrence. * If one or more characters does not appear in the source, they should be at the end; their order does not matter, nor does it have to be consistent. * **Source must be non-empty** * Newlines are treated the same as other characters. * The order in which the code is executed doesn't matter; just the raw string. * The input is in the same encoding as the code. * The input is sorted by characters, not by bytes. * Sorting is case sensitive * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes for each language wins! ``` let f = (s, i, o) => o.split("").map(x => [x, s.indexOf(x) == -1 ? s.length + 100 : s.indexOf(x)]).sort(([, a], [, b]) => a - b).map(([x]) => x).join("") === o && i.split("").sort().join("") === o.split("").sort().join("");let g = (s, i) => i.split("").map(x => [x, s.indexOf(x) == -1 ? s.length + 100 + Math.random() : s.indexOf(x)]).sort(([, a], [, b]) => a - b).map(([a]) => a).join("");$(() => $("button").click(() => $("#result").text(f($("#source").val(), $("#input").val(), $("#output").val()) ? "Valid" : `Invalid; example output: \`${g($("#source").val(), $("#input").val())}\``))); ``` ``` body,label{display: flex;flex-direction: column;}*{white-space: pre;font-family: Inconsolata, Consolas, mono-space;font-size: 14px;} ``` ``` <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><label>Source: <textarea id="source">ThisIs A Test</textarea></label><label>Input: <textarea id="input">Is it a Test?</textarea></label><label>Output: <textarea id="output">TissI etta?</textarea></label><div><button>Validate</button> <span id="result"></span></div> ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~102~~ ~~100~~ ~~96~~ ~~85~~ ~~79~~ ~~76~~ ~~68~~ ~~61~~ ~~59~~ 60 bytes ``` c="print(sorted(x:=input(),key=('c=%r;'%c+x).find))";exec(c) ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P9lWqaAoM69Eozi/qCQ1RaPCyjYzr6C0RENTJzu10lZDPdlWtchaXTVZu0JTLy0zL0VTU8k6tSI1WSNZ8/9/RSVlFVU1dQ1NLW0dXT19A0MjYxNTM3MLSytrG1s7ewdHJ2cXVzd3D08vbx9fP/@AwKDgkNCw8IjIqOiY2Lj4hMSk5JTUtPSMzKzsnNy8/ILCouKS0rLyisqq6praOgA "Python 3.8 (pre-release) – Try It Online") *-2 bytes by using [this](https://codegolf.stackexchange.com/a/62/83048)* *-4 bytes by realizing that `<0` == `==-1` and removing the unnecessary `+1`* *-11 bytes thanks to Neil* *-6 bytes thanks to dzaima* *-3 bytes thanks to rod* *-8 bytes thanks to negative seven pointing out that the program can output a list of chars* *-7 bytes due to Embodiment of Ignorance switching back to Python 3.8 and using `:=`* *-2 bytes due to Jo King switching out the variable name s for c, so we could leave out the `;c`* *+1 bytes because negative seven pointed out that it wasn't filtering `;` correctly* [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 14 [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. ``` '''∘⍋⊃¨⊂'∘⍋⊃¨⊂ ``` `⊂` enclose argument (to act on it as a whole) …`⊃¨` from that, pick one character for each of the following indices: `∘⍋` the indices that would sort the argument in the the order given by the following string (all non-members go in order of appearance at the end): `'''∘⍋⊃¨⊂'` the characters `'∘⍋⊃¨⊂` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X11d/VHHjEe93Y@6mg@teNTVhMb9n/aobcKj3r5HfVM9/UGC640ftU0E8oKDnIFkiIdn8P80BXXPYoXMEoVEhZDU4hJ7dS6QiLp6LlCgPCMRKgAm6nJzdTVANnQ1qwMA "APL (Dyalog Unicode) – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 48 bytes ``` n=>n.OrderBy((@"n=>.OrdeBy(@""+)Ixf"+n).IndexOf) ``` [Try it online!](https://tio.run/##JczZWoJAGADQe9@isWwmBCvbWSTNhaJot4UWHGZ0Sn9rgIK2Vyc@vTw3h0YqjUTeSYAaUSwFDKtOG5IJk8FgzAw6CqRlcTMH0wLNkyGTzQxjGxWesZCNkEKclCMFiOZAyFKPk1wv9aWImSuA4XmstaZAgxhzjBZ8VF5cqixjsqJUVa22urZe39jc2t7Z3dMN02rY@83WQbvT7TmHR@7xiXd6dn5xeXXdv7m9u/f9h8en52BAQ8aHI/HyOp7A9O1dRnHy8ZlmX98/v3@IEKLn/w "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~60 58~~ 56 bytes *-2 bytes from Jo King* ``` f=_=>_.sort((a,b)=>(p=g=>`f=${f+g}`.indexOf(g))(a)-p(b)) ``` [Try it online!](https://tio.run/##FcxBCsMgEEDRq4ShixlqvMF4hR6gFKNGJSWoxBAKpWe3uvhv@d/mMtUdWznnlFffWmDNSsuajxPRCEussHBktQS@fcM9/ha5pdV/HgEjERqaC1qi5nKqefdyzxEDPiGAmMAM7MANpgEP8qCCANXTPYZXn/wB "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “;fɓḟṾⱮ”ṾɓfⱮ;ḟ ``` A full program accepting a (Python formatted) string (of Jelly [code-page](https://github.com/DennisMitchell/jelly/wiki/Code-page) characters) which prints the output. (as a monadic link it yields a list of lists of characters) **[Try it online!](https://tio.run/##hY47DsIwDIav4gs0EnMQR0EKiasWVU3lOEO33qErFTdAYoOFvcdoLhJcHnO3T7//h8/YNH3Oabjoch6Xx3V5vtL9loZJYB5LYS1qzhmUUlwh2MqQsYwUoG7ho3iHUBzEpsW@1kjHMAkLiCo1Wga2Nrby@wKwdRA7CJ4YHZz6db4m2AUGb20kwtbi/63gI9nfd0cwEu0ig@HvkQ2xegM "Jelly – Try It Online")** ### How? ``` “;fɓḟṾⱮ”ṾɓfⱮ;ḟ - Main Link: list of characters, S “;fɓḟṾⱮ” - list of characters = [';', 'f', 'ɓ', 'ḟ', 'Ṿ', 'Ɱ'] Ṿ - un-evaluate = ['“', ';', 'f', 'ɓ', 'ḟ', 'Ṿ', 'Ɱ', '”'] ɓ - start a new dyadic chain, F(S, T=that): Ɱ - for each character, t, in T: f - (S) filter keep any of (the single character, t) ḟ - (S) filter discard any of (the characters in T) ; - concatenate ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 56 bytes ``` <slurp.comb.sort({"<$_>~EVAL$^a".index($a)}).say>~~.EVAL ``` [Try it online!](https://tio.run/##FcnnGoFQAADQVyGhjGvvZGZm75mWmUqJMnr163P@HlXUpCSEhC4Zmgp45coBXdHu2BshUIa0qWmJRrcsAk6yIJoYyuJfHOisRdo2@B@EDifiQt0eL4b7/IEgCIUj0Vg8kUylM9kckScLxVK5UqVq9Uaz1aY73V5/MByNJ9PZfLFcrTdbZsdyvCDuD8fT@SJdZUW9afrdeDxN6/X@fO0f "Perl 6 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 14 bytes (Jelly Code page), 25 bytes (UTF8) ``` “Ṿv`Ṿ;³³i@Þ”v` ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5yHO/eVJQAJ60ObD23OdDg871HD3LKE/3jkAA "Jelly – Try It Online") A full program that takes a single argument, the string to be sorted. Thanks to @JonathanAllan for pointing out a bug! As per @EriktheOutgolfer, although the code can be input using the Jelly code page, the characters sorted are the equivalent UTF-8 ones rather than the bytes of the source. As such, I’ve included the score in UTF-8 bytes as well. Note the same probably applies to all languages with custom code pages. ### Explanation ``` “Ṿv`Ṿ;³³i@Þ” | The string "Ṿv`Ṿ;³³i@Þ", referred to below as S v` | Evaluate this string as Jelly code using the string itself as the argument ``` The string above evaluates as: ``` Ṿ | Uneval the string S (effectively wraps it in “”) v` | Eval it (effectively removes the “”) Ṿ | Uneval it again, adding back in the “” ;³ | Concatenate the input to this ³i@Þ | Sort the input with respect to the first occurence of each character in the “”-wrapped string S concatenated to the input ``` `Ṿv`` is a no-op effectively here, but exists to ensure all characters are represented. [Answer] # [Ruby](https://www.ruby-lang.org/), 57 bytes ``` ->s{s.sort_by{|o|%{->s{.ort_by|%}index()9}.index(o)||99}} ``` [Try it online!](https://tio.run/##JcvfCoIwGIfh867ix0BQWIP@N1BvRCTmnORJxlbU2rdrX5ZnLw@89tn5NFRpXbvghJvs49L5QBNl4UdiAcrieOvNOy9kFEtNBZGUMSatnHGowLyxUHiNH2V7jquy1jMOFkJZUl3HyDjbbHf7w/F0lnOz1f8URukrAkgT7jkazTE0Wuj5dy1aFIjpCw "Ruby – Try It Online") Fairly straightforward, assuming I haven't missed a golfing trick. Take in a list of characters and sort by their index in a string consisting of all the uniq characters in the code in order of their appearance. Often their first appearance is in that very string, but that doesn't change the order. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~24~~ ~~22~~ 21 bytes ``` Σ"Σ"'"«"'«Rrk}"«Rrk}R ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3GIlIFJXOrRaSf3Q6qCi7FolCBUEkstIzTm3OCff2ES9FgA "05AB1E – Try It Online") **Explanation:** ``` Σ } # Sort "Σ" # Σ string literal '" # " string literal « # Concatenate last two literals "'«Rrk}" # '«Rrk} another literal « # Concat again R # Reverse literal (so: }krR'«'"Σ) r # reverse stack k # find the current sorting index in our code string R # reverse our sorted string ``` First time trying stuff in 05AB1E so probably lots to be saved [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~31~~ ~~26~~ 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Σ'"'ÿs"Σ'ÿÿsìyk"ìyk ``` -7 bytes by taking inspiration of [@EmbodimentOfIgnorance's approach in his C# answer](https://codegolf.stackexchange.com/a/187443/52210) of appending the current character before indexing. [Try it online](https://tio.run/##FYvBCcQwDARbEfqoh6sjDTiJwEEHBiv3cD36pgc/9FdLPoVZlnnsNi37xWuFEZJPxRSfKf4MwbfW2iorw1FLL8fNXUFr@31P2Bm09ZvPDwyfwx@lsDyG@cQMCaEgIhGJqI5cJPMlLOwP) or [try it with added debug-line to see the strings that's being indexed into](https://tio.run/##FYuxDcMwDARXEdiwyQQGskUWkG0CChhAgOgULDyNWu2ggj1XUhjcF1fcV8n7m9byjoA2BUJshthQBhtP5fux1quQUDpKbvm4qEmSUr@fM@2UpLaLzi2pTbUh6D2@3m1CDBmBAQARmUU0imD@8e79Bw). **Explanation:** ``` Σ # Sort the (implicit) input-string by: '" '# Push string '"' 'ÿ '# Push string "ÿ" s # Swap the order of these two strings on the stack "Σ'ÿÿsìyk" # Push string "Σ'ÿÿsìyk", where the `ÿ` are automatically filled with # the previous strings we created: `Σ'"ÿsìyk` # (top to bottom from stack; left to right in string) ì # Prepend this string in front of the character we're sorting yk # And then get the index of the character we're sorting in this string # (after the sorting the resulting string is output implicitly) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes ``` ≔´≔´´´η´F´Φ´θ´⁼´ι´κ´¬´№ηFηΦθ⁼ικΦθ¬№ηι ``` [Try it online!](https://tio.run/##S85ILErOT8z5//9R55RDW8AECJ7bfmjL@z3LgAwQ3gGUadwDZOwE4l1A@TVAgZZp57YDlZzbfm7ZuR1A6XM7z@0CMQ@tAUud24luJkHzQNYSMBMA "Charcoal – Try It Online") Explanation: ``` ≔´≔´´´η´F´Φ´θ´⁼´ι´κ´¬´№η ``` There are two ways of quoting characters in Charcoal; `´` quotes any single character while `”y`...`”` quotes any character except `”` and also counts as a separate string. It turns out that the overhead in having to deal with `”` means that it doesn't end up any golfier. ``` FηΦθ⁼ικ ``` Loop over the characters in turn, outputting any matching characters from the input. This sorts the input. ``` Φθ¬№ηι ``` Output any unmatched characters in the input. [Answer] # [J](http://jsoftware.com/), 14 bytes Anonymous tacit prefix function. ``` ]/:']/:''i'i:] ``` [Try it online!](https://tio.run/##TcihCoAwGEXhvqe4WC6CzOUfxGy3ycIQhxOmYYIWn31q0nDg8C3Zp0bDQGCyrYVvDAxic6kKDfpGExUugU9KTeO8wYNdQtjh0E9pb/kxGR89ZvfX74YY1jq60wrzDQ "J – Try It Online") `]` the argument …`i:` last occurrence (non-members get the index beyond end of lookup string) of each character in: `']/:''i'` the characters `]/:'i` …`/:` use that to sort: `]` the argument [Answer] # Java 10, ~~129~~ 100 bytes ``` s->{s.sort(java.util.Comparator.comparing(c->("s->{.ort(javuilCmpcng\"\\+)dexOf;}"+c).indexOf(c)));} ``` -29 bytes by porting the `+c` from [*@EmbodimentOfIgnorance*'s C# answer](https://codegolf.stackexchange.com/a/187443/52210). [Try it online.](https://tio.run/##lVL7V9MwGP2dvyLGB62l8f2iUMUpDgWGbD4paJZmW0qb1CQdG3P@6zPJqjyc5@hdz06/fje53@NmeIjDLD2ekRwrBXYw45MlABjXVPYwoWDXhgAMBUsB8TJDR5VmOdpmSq81BlhiYqgxUH5kiNMl86c01oyAXcDBOpipMJ4opITU5043RFGao1pIRNwr432PhLEHLR3V5IrljaIkvJ/AJAn8lI5avWgKA@Ijxl3kEd/3o@kssrpl1c2Nbi3vKi5MP15b2@sPDgH2581oqrQHOwOmgHmwi6Gr/1euiaUcgxCMqTT5E3aKZYouUnYkAk0E9oQ2/a@AzoCCzVwI89qsdCh4qAc03BfkeJ5rU3zx/P/NJfnLYBI7mnPDSRZM56Ju4n6ehW8RBGEYIocoiuO40Wi1EgfsQCzSlNJer99nBlmW50VRcM6FRVmW0kIZaIOqGg5Ho8lkekn3SgKvXrt@Y9nzbwYrIbp1@87de/cfPHz0@MlqtLYeP3228bzx4uXmq@bW6zfbO7utvbf77c679x8@fvp8kCSHR1@@4i5Jaa8/YNlxXnBRfpNKV8OT0fh08n36A/5hQOcAJz53gHF1WenaA@2x0rRAotKoNEmdcw9u2fwqSCAMHDVYhst1D2cr2pASjy@7PzexMTunJ4uYnrsNEcNXno8KXHZEq5u5xdqPvlkZEXlOyXkvKC0pLowlXEJIhbRwt9mluqI4Ip5VrsNFLbUq/bsnS61vnVdhCyABhP@mngnGrR2NZc7mskCz3sN09hM) **Explanation:** ``` s->{ // Method with char-List parameter and no return-type s.sort(java.util.Comparator.comparing(c-> ("s->{.ort(javuilCmpcng\"\\+)dexOf;}" // Push a String containing the characters in the code +c) // Append the current character .indexOf(c) // And get the first index of the current character in the String ``` NOTE: Usually it's cheaper to use `s.sort((a,b)->Long.compare(a,b))` instead of `s.sort(java.util.Comparator.comparing(c->c)`, but in this case it would be 11 bytes longer: ``` s->{var v="s->{var =\"\\;.ot(,)Lngcmpe+idxOf}";s.sort((a,r)->Long.compare((v+a).indexOf(a),(v+r).indexOf(r)));} ``` [Try it online.](https://tio.run/##jVNtW9MwFP3Or4j1hdSuEXx3ZZs4xaGDIZuvFDWk2dbSJjVJy8acf30mWXGCfPC0T58m9zT33nNPE1xiP4lOFyTFUoI9HLPZGgAxU1QMMaFg3ywBKHkcAQITTUeFilPUjaXaao@xwERTm0C6gSbO1/RDKqxiAvYBAw2wkH5zVmIByoZz8doInTAMEFew5nbZiGQ59eJo0hvOnUAiyYWCENeE6ze7nI0Q4VmOBYWw9LCLYhZRTYXYrekNsdoQrusG80VgSsiLk1SXUFVii890a7CvRMxGR8cAu8u@FJUKOoNxLIG@sV07tpWLWAcLMQU@mFKh42fxORYRukzZEwh0EDjgSktRA4MxBTsp5/q1UyifM1@NqX/Iyeky1qf48vdGl6rvlcBt2zVWXFQC6MIh8ZswtHxUsYs4bWc5YSOtamh0DUMrhxtsbbQ26/PQ8chKI2I1upwd6K/0BQ1cA8/3fWSxsVkPgq1Gs9lstdu9XmiBLYhBFFE6HI5GsUaSpGmWZYwxbpDnuTCQGkqjKMpyMpnN5ley3widm7du31mH7l2v5qN7G5v3Hzx89PjJ02d1k7n1fPtF@@Wrnded3Tdvu3v7vYN3h/3B@w8fP33@chSGx1@/fccnJKLD0ThOTtOM8fyHkKoozybT89nP@S/nH19aN9jkSzdos@eFqvzQn0pFM8QLhXIdVCmDzq6J17VMjmep3rqzXvWwGte2EHh69adI9Vr/A4yeXceE9jRENF9CF2U4H/DeSWKHbDZdPTjC05SSv30hlaA40/awAS4kUtyeZkZri2KIQJO5Wl7XUq9Qf3oy1OrUZRWmAOI5zv9lT3jMjDW1b1a6XJOzmsN88Rs) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 68 bytes ``` $p=$args &($t={$p|sort-object{"`$p=`$args &(`$t={$t})$_"|% i*f $_}}) ``` [Try it online!](https://tio.run/##NY7HVsMwFET3@oqHeLbikNA7mJhO6CV0iEtwYgcHG0sQQBa/bnTgsJjFnbmLydJhmPMoTJISA1uWmNno5z1OzAoKW2JW8DQX9TTohx0hqad371/wfg2hLHRpYUBc7QK6SlmlIqzJIRbgQyvkosFqumBsoHkY@X@s4zDiTU3PzM7NLywuTdbt7xFnFI22Wa1Y7tir/iU@3@I0u388u94@b91eNk9OiVQ@f@r2ov5zssLYw/rF1s7u3v7B4TItvj4678HLoDY@cXezebVxfLS61iDMgYIYIAkA5mCDCRiA42qkDHNGiSp/AA) [Answer] # [Python 2](https://docs.python.org/2/), 62 bytes ``` lambda a:sorted(a,key=('lambd :sorted(,ky=\'\\+).fin'+a).find) ``` Same concept as my C# answer. [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHRqji/qCQ1RSNRJzu10lZDHSyuABPVya60jVGPidHW1EvLzFPXTgTTKZr/C4oy80oU1NX1svIz8zTSNIoSy@Mz8wpKSzQ0NTX/KygqKauoqqlraGpp6@jq6RsYGhmbmJqZW1haWdvY2tk7ODo5u7i6uXt4enn7@Pr5BwQGBYeEhoVHREZFx8TGxSckJiWnpKalZ2RmZefk5uUXFBYVl5SWlVdUVlXX1NYBAA "Python 2 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~18~~ 7 bytes Takes input as an array of characters ``` nQi"nQi ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=blFpIm5RaQ&input=WyduJywnaScsJ1EnLCdpJywnUScsJ24nLCciJ10) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes (UTF-8\*) ``` “®³nÞṾ©V”Ṿ©VV ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5xD6w5tzjs87@HOfYdWhj1qmAthhP3//18dytscdmjnoZ36@iDFK8Oc4h0f7lp4aHnYoZV5QNnD8w6tUwcA "Jelly – Try It Online") Takes input as a Python-formatted string in the 1st command-line argument. [Unique characters](https://tio.run/##y0rNyan8/z/w////6o8a5hxad2hz3uF5D3fuO7Qy7FHDXAgjTB0A): ``` “®³nÞṾ©V” ``` \*Note: I discovered that this doesn't work when encoded in JELLY, since it sorts the UTF-8 characters instead of its own bytes. [Answer] # [ReRegex](https://github.com/TehFlaminTaco/ReRegex), 335 bytes ``` ([^(])\(/($1/([^(])\[/[$1/([^(\[])\^/^$1/([^(\[^])]/]$1/([^(\[^\]])\)/)$1/([^(\[^\])])\\/\\$1/([^(\[^\])\\])\//\/$1/([^(\[^\])\\\/])\$/\$$1/([^(\[^\])\\\/$])1/1$1/([^(\[^\])\\\/$1])\#/\#$1/([^(\[^\])\\\/$1\#])i/i$1/([^(\[^\])\\\/$1\#i])n/n$1/([^(\[^\])\\\/$1\#in])p/p$1/([^(\[^\])\\\/$1\#inp])u/u$1/([^(\[^\])\\\/$1\#inpu])t/t$1/#input ``` A Naïve solution, bubble sorts characters to the left based on their occurance in the source code, which only consists of the characters `([^])\/$1#input` (in order). Unfortunately, it requires a separate regex for each character, which gets progressively longer per index. Seperating the regexes for readability gives: ``` ([^(])\(/($1/ ([^(])\[/[$1/ ([^(\[])\^/^$1/ ([^(\[^])]/]$1/ ([^(\[^\]])\)/)$1/ ([^(\[^\])])\\/\\$1/ ([^(\[^\])\\])\//\/$1/ ([^(\[^\])\\\/])\$/\$$1/ ([^(\[^\])\\\/$])1/1$1/ ([^(\[^\])\\\/$1])\#/\#$1/ ([^(\[^\])\\\/$1\#])i/i$1/ ([^(\[^\])\\\/$1\#i])n/n$1/ ([^(\[^\])\\\/$1\#in])p/p$1/ ([^(\[^\])\\\/$1\#inp])u/u$1/ ([^(\[^\])\\\/$1\#inpu])t/t$1/ #input ``` [Try it online!](https://tio.run/##dYxLCsMwDAWvIogX1qYP36U7S4ZQTJNFk2A7tLdP3VL6S7KwzMwIpZjiOd6WxfpglcXCGocXePgXiK8YEN4YlBX6QdG6wOBvw1UJRH6cPB4g@LOCOg3ErLxRdnBr7erfQJqNIo1yj36z9MoDhu00KE@YdtqkPGPei7NyQan1CWVZjl2fiamOlg5UYi4kIHsdu3F0ZChQHi@RlPLUpkjNqWtTeyoxZfH0vHEH "ReRegex – Try It Online") [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 647 bytes ``` ,[>>>+>,]<<<<[<<<<]>>>>[[->+>+<<]--[>-<++++++]>-<+>[<->[-]]<[>>.>-<<<-]>>[-<<+>>]>>]<<<<[<<<<]>>>>[[->+>+<<]-[>-<---]>------<+>[<->[-]]<[>>.>-<<<-]>>[-<<+>>]>>]<<<<[<<<<]>>>>[[->+>+<<]----[>-<----]>+<+>[<->[-]]<[>>.>-<<<-]>>[-<<+>>]>>]<<<<[<<<<]>>>>[[->+>+<<]--[>-<++++++]><+>[<->[-]]<[>>.>-<<<-]>>[-<<+>>]>>]<<<<[<<<<]>>>>[[->+>+<<]-[>-<---]>--------<+>[<->[-]]<[>>.>-<<<-]>>[-<<+>>]>>]<<<<[<<<<]>>>>[[->+>+<<]----[>-<----]>+++<+>[<->[-]]<[>>.>-<<<-]>>[-<<+>>]>>]<<<<[<<<<]>>>>[[->+>+<<]--[>-<++++++]>--<+>[<->[-]]<[>>.>-<<<-]>>[-<<+>>]>>]<<<<[<<<<]>>>>[[->+>+<<]--[>-<++++++]>---<+>[<->[-]]<[>>.>-<<<-]>>[-<<+>>]>>]<<<<[<<<<]>>>>[>>>[<<<.>>>-]>] ``` This was a mouthful. For each of Brainfuck's 8 command characters (In order of source appearance), compares them to each character of the input and outputs it when they occur. After each character is done, it outputs whatever wasn't found. ## Ungolfed ``` ,[>>>+>,] Load each character of input with some memory padding <<<<[<<<<]>>>> Navigate to the start [ For each COMMA [->+>+<<] Copy over the next two --[>-<++++++]>- Subtract 44 <+>[<->[-]]<[ If NOT Zero >>. Write it >- Unset the remember flag <<<- And unset the test flag ] >>[-<<+>>] Copy Back >> Next Char ]<<<<[<<<<]>>>> And Reset [ For each LEFT BRACKET [->+>+<<] Copy over the next two -[>-<---]>------ Subtract 91 <+>[<->[-]]<[ If NOT Zero >>. Write it >- Unset the remember flag <<<- And unset the test flag ] >>[-<<+>>] Copy Back >> Next Char ]<<<<[<<<<]>>>> And Reset [ For each RIGHT ANGLE BRACKET [->+>+<<] Copy over the next two ----[>-<----]>+ Subtract 62 <+>[<->[-]]<[ If NOT Zero >>. Write it >- Unset the remember flag <<<- And unset the test flag ] >>[-<<+>>] Copy Back >> Next Char ]<<<<[<<<<]>>>> And Reset [ For each PLUS [->+>+<<] Copy over the next two --[>-<++++++]> Subtract 43 <+>[<->[-]]<[ If NOT Zero >>. Write it >- Unset the remember flag <<<- And unset the test flag ] >>[-<<+>>] Copy Back >> Next Char ]<<<<[<<<<]>>>> And Reset [ For each RIGHT BRACKET [->+>+<<] Copy over the next two -[>-<---]>-------- Subtract 93 <+>[<->[-]]<[ If NOT Zero >>. Write it >- Unset the remember flag <<<- And unset the test flag ] >>[-<<+>>] Copy Back >> Next Char ]<<<<[<<<<]>>>> And Reset [ For each LEFT ANGLE BRACKET [->+>+<<] Copy over the next two ----[>-<----]>+++ Subtract 60 <+>[<->[-]]<[ If NOT Zero >>. Write it >- Unset the remember flag <<<- And unset the test flag ] >>[-<<+>>] Copy Back >> Next Char ]<<<<[<<<<]>>>> And Reset [ For each MINUS [->+>+<<] Copy over the next two --[>-<++++++]>-- Subtract 45 <+>[<->[-]]<[ If NOT Zero >>. Write it >- Unset the remember flag <<<- And unset the test flag ] >>[-<<+>>] Copy Back >> Next Char ]<<<<[<<<<]>>>> And Reset [ For each DOT [->+>+<<] Copy over the next two --[>-<++++++]>--- Subtract 46 <+>[<->[-]]<[ If NOT Zero >>. Write it >- Unset the remember flag <<<- And unset the test flag ] >>[-<<+>>] Copy Back >> Next Char ]<<<<[<<<<]>>>> And Reset [ For each remaining character >>>[ If the remember flag is still set <<<. Write it >>>- Unset the flag ]> Next character ] Until it is done ``` [Try it online!](https://tio.run/##rY9LCsMwDESv0r08PoHQRYQW6Y@UmgYCocd3x4FCu@im9oBtaZAenuM63R7X7XSvNbmZiaVQytsVNMwddIUd4AaVXdEqc4U5IpSrmY4quOMsxIzVb1QjAZzGri4W8MZxQ/pQnwlHBhwaUQaG7P3YN@sfWDtsMl8ORq2SkOdLKcvhuazlrObxAg "brainfuck – Try It Online") [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `J`, 18 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` "XÞxṘs+nȮ"XÞxṘs+nȮ ``` #### Explanation ``` "XÞxṘs+nȮ"XÞxṘs+nȮ # Implicit input "XÞxṘs+nȮ" # Push the string "XÞxṘs+nȮ" X # Pop and store in the variable x Þ # Sort the input by the following: x # Push x, "XÞxṘs+nȮ" Ṙ # Get its representation (surround by quotes) s+ # Append the current character nȮ # And get its index in this string # Implicit output, joined by the J flag ``` #### Screenshot [![Screenshot](https://i.stack.imgur.com/1VCyMm.png)](https://i.stack.imgur.com/1VCyM.png) ]
[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/154617/edit). Closed 2 years ago. [Improve this question](/posts/154617/edit) **Notice: I'm willing to give a bounty to any answer that I find interesting.** Your challenge is to design a [Turing-complete](http://esolangs.org/wiki/Turing-complete) [one instruction set computer](https://en.wikipedia.org/wiki/One_instruction_set_computer) (OISC): > > An OISC is an abstract machine that uses only one instruction – obviating the need for a machine language opcode. With a judicious choice for the single instruction and given infinite resources, an OISC is capable of being a universal computer in the same manner as traditional computers that have multiple instructions. > > > [Here](https://gist.github.com/aaronryank/2806c4ce8a3602c6cae6c18e52fcfe63) are some examples of single commands that make a Turing-complete OISC. Rules: ### You must provide an interpretation or proof thereof You must provide an interpreter for your language. This interpreter should only be restricted by memory/time (e.g. must have no user-imposed restrictions). If you do not provide an interpreter for your language (for whatever reason other than laziness) you must prove that it is possible for one to be written. An interpreter *must be possible*. ### You must prove its Turing-completeness You must include a formal proof that your language is Turing-complete. A simple way to do this is by proving that it can interpret or have the same behavior as another Turing-complete language. The most basic language to interpret would be [Brainf\*\*k](//esolangs.org/wiki/Brainfuck). For example, a normal language that has all the same commands as Brainf\*\*k (and the same lack of user-imposed memory restrictions) is Turing-complete because anything that can be implemented in Brainf\*\*k can be implemented in the language. [Here](https://gist.github.com/aaronryank/772e68017fc431459d39547534b89dc2) is a list of very simple-to-implement Turing-complete languages. ### Additional OISC requirements * This OISC should only have one instruction - it cannot have multiple instructions with one of them making it Turing-complete. * Your OISC may use any syntax you like. You should define in your answer what is instruction, what is data, and what is a no-op (e.g. whitespace). Be creative! * Arguments do not just need to be integers. For example, [///](http://esolangs.org/wiki////) is a beautiful example of a Turing-complete OISC. * How and if input and output are taken and given are left up to you. Most OISCs implement I/O via specific memory locations, but there may be other ways to do so, and you are encouraged to find one. * A valid answer must provide some example code in your OISC, either by including it in the post or linking to a simple challenge solved in the language. ### Voting Voters, please remember not to upvote boring submissions. Examples: * [Lenguage](https://esolangs.org/wiki/Lenguage)-equivalents * An implementation of an existing OISC (answerers, please create your own!) * An "OISC" in which the first argument specifies a command to call ([example](https://pastebin.com/raw/1R4cgkEJ)) However, you should upvote interesting, creative submissions, such as: * An OISC based off of a mathematical equation * A Turing-complete [ZISC](https://en.wikipedia.org/wiki/Zero_instruction_set_computer) based on a neural network * An OISC in which output I/O happens in other ways than certain memory locations ### Winning As with [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), the answer with the most votes wins! Good luck! [Answer] # [XOISC](https://github.com/bforte/xoisc) This OISC is based on [Fokker's X-combinator](http://www.staff.science.uu.nl/~fokke101/article/combinat/index.html) which is defined as follows: $$ X = \lambda f\ . f\ (\lambda g\ h\ x\ . g\ x\ (h\ x))\ (\lambda a\ b\ c\ . a) $$ If we acknowledge the fact that the [SKI-calculus](https://en.wikipedia.org/wiki/SKI_combinator_calculus) is Turing complete the above \$X\$-combinator is Turing complete as well. This is because \$S\$, \$K\$ and \$I\$ can be written in terms of \$X\$, like this: $$ \begin{align} S &= X\ (X\ X) \\ K &= X\ X \\ I = S\ K\ K &= X\ (X\ X)\ (X\ X)\ (X\ X) \end{align} $$ ## How XOISC works Internally XOISC has an (initially empty) stack, from there the instruction taking \$n\$ as an argument does the following: * Pop \$n\$ elements (functions \$ f\_1 \dots f\_N\$) from the stack, push \$f\_1\ (f\_2\ (\dots (f\_N\ X) \dots ))\$ Once there are no more instructions left XOISC will push all command-line arguments (if any) to the stack, for example: $$ [ \underbrace{s\_1, \dots,\ s\_M}\_{\text{stack before}} ,\ \underbrace{a\_1, \dots,\ a\_N}\_{\text{arguments}} ] $$ The final computation will be \$(\dots ((\dots (s\_1\ s\_2) \dots)\ s\_M)\ a\_1) \dots) a\_N \$. --- Since the one instruction in XOISC takes only one argument (memory offset) there is no reason to even use a name for that instruction. So a valid source file will constitute solely of integers separated by newlines or whitespaces, like for example: ``` 0 0 2 0 1 0 1 ``` [Try it online!](https://tio.run/##jVn9bts4Ev9fTzHwBmtpa@uS3n9BHTTbS4vcJo3RdO8COIZBy7QtrEyqEpWkd70nu3fYV8rODEl92EpRA7EpcjgczudvlK0o/5BZ9vz83/FPcHX@8cPv5x8u4ErslivxTpQSfhr/Lwh2elVlEq5FquBxKwsZBOku14WBd1qZQmfxtVZi1TsZ3xphJIgSbj97gtuvpZG7GOlKncn4gzQ3udlbvLzZm7hQD2mh1U6qmvSzfDLxVBSlTHqm4ounvOjMf5JiBWGB3xepwXtEQRCMx/AN/iGMAPM1l7DWBVSKhivIWA2QiCypsqoMVkSFTGEC/xIFXCojN7LA7agvnv8G53nOI/t0FwCsZJE@pGoDF1/cYZdqnT6BzmUhDJ5GJ64rlZhUKxB5nqWJoHEQxkcRHoUsUd2qNEIlEm63@pG5WzsAlDQRkjyCqPlR1PMkmXgbklgLWEREMfjz/@EAXr1ypDQaRIPuDkfXIqvXiZWAZZdnixW0mC/3mbvN@1taOzzpHUlwN3AqI08xRZWgb22rItmCqnaovizA3yWa4PS0tsb4jNTjFxSyoRvxtcK1zlYF24gVdhLBjH5f4wkLeDOG2Ukcq/k8ityxU2GMLBTshMEzf9XorEKVgdE0pEPJEHjgtfi6lLzu1ySKAMhBkrdMwElzDCjOP6vSwHuRlbJNYTTxGv429BSfi8oSaPLUxxRjcQIf8QF9qVe8rmZIyo/V7kBIpya3OoGNjksMkSxdf8XT2KlwzumLv6ym2Mws2DHS2U@Xrlbr6wieLD0SPNXUbe5O@47jSYum4dzlh7ThyasI3hyd7bOttyxaGnph2iruk1xVGEs2zQHqcFcCpjali53IxrrAmKUkkGaAuud1WGlZqqEBrywM2YIME9QTjabJ/@ppZ@UhGVkCOcChWRviYW0E2kHSywN1c3TS4IimRHCgNEfEYbaURrjrCo6uLq0LRt5GzCL@WUZtQsky1zNdjiR9tYQTHIkDU9MK5jRrxhbT5vONInTCbMQLy2@Al4nFESzHJ71kbW3yYQdUtSyknWWjQpoP1Sv0xjBVyftCSgxT0t7LHEhbS0hqxfkF5FqPk6h3PyZMTm13wcGyP135bP6iPkStDvHqx9Qhvnfank/5FauU7@7c96BmSUTtpx7T@8VaHT6lYeUGUWwqqvMlCLWCUmNikyOQDyKrCEvkhd4UJDQu5kWqDBSyrDJTBkWlbouEQpGzMMbi7NYgxWZOYzuk0eUNhJGnXhIp4hNS1iPigk/pZmsg/E@a/xufriEnmS5VXhmYHcfxHGkj1NN9SlMlsqOYbfbtRH4NDcZAykfMKMieN5HsJMFKs0oyiSnFiOQPPLuQD5Ju7/hiSZRPMrHwibkuWAWXVApZB1i@5rViuY40meQIbLEL11mak3Uia@gjcLmXT613I@BB7bMm@DPBokLlYoD13NB5A1f9BsinqXFdu3b9bp9Btz5ZPlSDajbbaWXQRFcKZcMMjFvep0pkVtJTGDCR1UO4TxsTaBi2b5V7giPPBw9CPykRWp22EAfpDceogKDOvSywYfDg8YxhpNLeqBpw4@KbRPgOQBoeIqRhGyL1cTnY2966tyd7yxZetI3yDbIWurgbOlTVbzNneb5dtsf8yS88uUi98NEo0OnUJiO/tRiNsGvjqBaacfh9dr3ADIWZUwA2VKRqDgl0iny01CYiPFaiL5tzMgSXfWkCtqtz7qzj3PUVI7xtDqfozMaLagNxLbCgI9heaUwpO8mAgAMX6CoyaGKYSrnd41KGIPlD4VIHWsUNWnuwdaA6abeFqb4oCl3EVSkLHkW4LLtJzqPCNv4fA@5YcU@Q6N0OM9w4S5XPCUErFbX0Wqe1rtAEQ1obVEu8K7k2ELNBI7DyxzbP2ZOm6KM8aLl7VIeHI0GHyEWC0obuImQkzMZTePPtjOJqikb8BaReB@0sNYVmJxb0Ks1WF3VksmoKmM1sk4Tt0BTOy1InJPEcU6/Ru2nNjZ@QGxqwmHZLDImA/VvPrHUUklUrebNGJ0IISo@o8CUmCuzJyuhwG8KeRymx6CVbTKDDEP3MDSMaugvxrZvrsvyUCtXXE3tn@OUME72pELZTY@cJ6QKuVnst1mt0DVedaS20YmN7dn8/IHashdahbIIJlyDeYE9fpZvUNEROXvQi2yx7pwkj6@yHs/tbc2/GkoTIydT20Xn5r2hZM0ZY3dIrOzb5GWHx9jzKMQvfoTpHaJxo3lmbwAzC4e1wxCqIW9@2mP0dYlfVaGBbhnoq2oceI@T1W4eXpXzdR3jpCD2zHpK7Lgkd7FLR7ZDleUHoA8HmQWA3oi5IE76TsJMJaRvxTgxbsitmQNQuhXKYTCZRjD4ctRW9h6dUq/gxbEq0QrBhUFQ0t8dT4TotMBZet/BXusGmSK6iQJS7H4VVRLrgrsunm/1qfQAHw7pax9h4WbwUU623uSf28t7RtNF3CMDiNi479rmJGRMBN0/BXt/pKuQBtEZYrQ3DUYLWd2Q2/qIuqVKuTezZ1YY7ieCcjsnuEJBbzwBSEfMN7RHRS@MXWCwsC0n1BAaPmvrRLaYYqQY9O7jPsTvwHt4DcXhkl3q2uMamV07ffS47T0mfrAtikAV9Db2DNNRqOjbLfTrBvSDPeqvwhpN9a7pGKSWGKfxtAmqfVbu5IQl6OhpL1RWN@reff7ajA/GsZ/PbGV6q/eMlIR/eOjGDnl6OJGfQRSRhOj75vpM9vHxD/6KruWf0nYs2Lb/yTf9Bm8aXJdz3ZG/axCBf9bjHHl09HlvQWku0PBSImr@ZmvcrudfRO4mtg5G6XSN1VvT2BqEV1u5NqoIdvb4m2MRZip8mBCpvcgNTWewqhKY6JxhWerx5XmxKODubwD2FN8FTPKQcFXI3ms0ZBRKERQalf7kYHqE2bWM5ci@dRvyyLyL5MG/hXuKzGC1GlAn5xtQPptjkoYYTYYAzZI22vEhUBm94DAM5gNmAUvoAcfQn@QXlhFIawlEwuLibfsL2alDmMqFW0PbPfSliVDMUxBATN/H7qB2783KHbEwhVJkRbm/VEKN/iO2S2FJX2eFLRQQZI06RBXI0oCtDWZxfwGMjLrgRpWazh3njK1ZCUmU5YpcL8QI8bpNwxQrXOL9gGhpR9HaIWHFkQ7TK0pHxq0nmVlOSkUoO1wN8T2@SuEO7V4yZq1JssDittR15K9as7CyxGvDwFJ50WiYwGwv07vFyjiMJZEp8fH95dYETlx@nv3@@nd9TFNSAuvE/K7GkC4jSN3NrejFXtt4itjd4B6UXV@KUXmtM6P8S6n2aUS2jf5dc65XkCNh@kIb@scMBRhOW8yHfBdepvc@EdTfwIco3wlD4UqWILvBCz8/PY/l8jCnjNf6d0N9f) ## Example Let's take the above example (stack growing to the right): $$ \begin{align} & \texttt{0} & \text{pop 0 and apply (ie. push single } X \text{)}: & \quad [X] \\ & \texttt{0} & \text{again simply push } X: & \quad [X,\ X] \\ & \texttt{2} & \text{pop 2 (} a,b \text{) and push } a\ (b\ X): & \quad [X\ (X\ X)] \\ & \texttt{0} & \text{simply push } X: & \quad [X\ (X\ X),\ X] \\ & \texttt{1} & \text{pop 1 (} a \text{) and push } a\ X: & \quad [X\ (X\ X),\ X\ X] \\ & \texttt{0} & \text{simply push } X: & \quad [X\ (X\ X),\ X\ X,\ X] \\ & \texttt{1} & \text{pop 1 (} a \text{) and push } a\ X: & \quad [X\ (X\ X),\ X\ X,\ X\ X] \end{align} $$ Finally evaluate the stack: \$((X\ (X\ X))\ (X\ X))\ (X\ X)\$ or with less parentheses \$X\ (X\ X)\ (X\ X)\ (X\ X)\$ which we recognize as the good old \$S\ K\ K\$ identity function. ## Turing completeness ### Proof idea For XOISC to be Turing complete we need to be able to translate any (valid) interleaving of parentheses and \$X\$ combinators. This is possible because when popping, applying and pushing it does so in a right-associative manner (function application is left-associative). To translate any such \$X\$ expression there is an easy way to do so: Always pop as many elements such that from the beginning of the current level of parentheses there will only be one element left. As an example, the previously used expression: \$((X\ (X\ X))\ (X\ X))\ (X\ X)\$ * to get \$X\$, we simply need a `0` * next we're in a new level of parentheses, so we again only need a `0` * now two parentheses close, so we need to pop 2 elements: `2` * again we're in a new level of parentheses, so we need a `0` * two parentheses, close so again a `2` * and the same again So we end up with a different (yet semantically equivalent) XOISC-program: `0 0 2 0 2 0 2` [Try it online!](https://tio.run/##jVn9bts4Ev9fTzHwBmtpa@uS3n9BHTTbS4vcJo3RdO8COIZBy7QtrEyqEpWkd70nu3fYV8rODEl92EpRA7EpcjgczudvlK0o/5BZ9vz83/FPcHX@8cPv5x8u4ErslivxTpQSfhr/Lwh2elVlEq5FquBxKwsZBOku14WBd1qZQmfxtVZi1TsZ3xphJIgSbj97gtuvpZG7GOlKncn4gzQ3udlbvLzZm7hQD2mh1U6qmvSzfDLxVBSlTHqm4ounvOjMf5JiBWGB3xepwXtEQRCMx/AN/iGMAPM1l7DWBVSKhivIWA2QiCypsqoMVkSFTGEC/xIFXCojN7LA7agvnv8G53nOI/t0FwCsZJE@pGoDF1/cYZdqnT6BzmUhDJ5GJ64rlZhUKxB5nqWJoHEQxkcRHoUsUd2qNEIlEm63@pG5WzsAlDQRkjyCqPlR1PMkmXgbklgLWEREMfjz/@EAXr1ypDQaRIPuDkfXIqvXiZWAZZdnixW0mC/3mbvN@1taOzzpHUlwN3AqI08xRZWgb22rItmCqnaovizA3yWa4PS0tsb4jNTjFxSyoRvxtcK1zlYF24gVdhLBjH5f4wkLeDOG2Ukcq/k8ityxU2GMLBTshMEzf9XorEKVgdE0pEPJEHjgtfi6lLzu1ySKAMhBkrdMwElzDCjOP6vSwHuRlbJNYTTxGv429BSfi8oSaPLUxxRjcQIf8QF9qVe8rmZIyo/V7kBIpya3OoGNjksMkSxdf8XT2KlwzumLv6ym2Mws2DHS2U@Xrlbr6wieLD0SPNXUbe5O@47jSYum4dzlh7ThyasI3hyd7bOttyxaGnph2iruk1xVGEs2zQHqcFcCpjali53IxrrAmKUkkGaAuud1WGlZqqEBrywM2YIME9QTjabJ/@ppZ@UhGVkCOcChWRviYW0E2kHSywN1c3TS4IimRHCgNEfEYbaURrjrCo6uLq0LRt5GzCL@WUZtQsky1zNdjiR9tYQTHIkDU9MK5jRrxhbT5vONInTCbMQLy2@Al4nFESzHJ71kbW3yYQdUtSyknWWjQpoP1Sv0xjBVyftCSgxT0t7LHEhbS0hqxfkF5FqPk6h3PyZMTm13wcGyP135bP6iPkStDvHqx9Qhvnfank/5FauU7@7c96BmSUTtpx7T@8VaHT6lYeUGUWwqqvMlCLWCUmNikyOQDyKrCEvkhd4UJDQu5kWqDBSyrDJTBkWlbouEQpGzMMbi7NYgxWZOYzuk0eUNhJGnXhIp4hNS1iPigk/pZmsg/E@a/xufriEnmS5VXhmYHcfxHGkj1NN9SlMlsqOYbfbtRH4NDcZAykfMKMieN5HsJMFKs0oyiSnFiOQPPLuQD5Ju7/hiSZRPMrHwibkuWAWXVApZB1i@5rViuY40meQIbLEL11mak3Uia@gjcLmXT613I@BB7bMm@DPBokLlYoD13NB5A1f9BsinqXFdu3b9bp9Btz5ZPlSDajbbaWXQRFcKZcMMjFvep0pkVtJTGDCR1UO4TxsTaBi2b5V7giPPBw9CPykRWp22EAfpDceogKDOvSywYfDg8YxhpNLeqBpw4@KbRPgOQBoeIqRhGyL1cTnY2966tyd7yxZetI3yDbIWurgbOlTVbzNneb5dtsf8yS88uUi98NEo0OnUJiO/tRiNsGvjqBaacfh9dr3ADIWZUwA2VKRqDgl0iny01CYiPFaiL5tzMgSXfWkCtqtz7qzj3PUVI7xtDqfozMaLagNxLbCgI9heaUwpO8mAgAMX6CoyaGKYSrnd41KGIPlD4VIHWsUNWnuwdaA6abeFqb4oCl3EVSkLHkW4LLtJzqPCNv4fA@5YcU@Q6N0OM9w4S5XPCUErFbX0Wqe1rtAEQ1obVEu8K7k2ELNBI7DyxzbP2ZOm6KM8aLl7VIeHI0GHyEWC0obuImQkzMZTePPtjOJqikb8BaReB@0sNYVmJxb0Ks1WF3VksmoKmM1sk4Tt0BTOy1InJPEcU6/Ru2nNjZ@QGxqwmHZLDImA/VvPrHUUklUrebNGJ0IISo@o8CUmCuzJyuhwG8KeRymx6CVbTKDDEP3MDSMaugvxrZvrsvyUCtXXE3tn@OUME72pELZTY@cJ6QKuVnst1mt0DVedaS20YmN7dn8/IHashdahbIIJlyDeYE9fpZvUNEROXvQi2yx7pwkj6@yHs/tbc2/GkoTIydT20Xn5r2hZM0ZY3dIrOzb5GWHx9jzKMQvfoTpHaJxo3lmbwAzC4e1wxCqIW9@2mP0dYlfVaGBbhnoq2oceI@T1W4eXpXzdR3jpCD2zHpK7Lgkd7FLR7ZDleUHoA8HmQWA3oi5IE76TsJMJaRvxTgxbsitmQNQuhXKYTCZRjD4ctRW9h6dUq/gxbEq0QrBhUFQ0t8dT4TotMBZet/BXusGmSK6iQJS7H4VVRLrgrsunm/1qfQAHw7pax9h4WbwUU623uSf28t7RtNF3CMDiNi479rmJGRMBN0/BXt/pKuQBtEZYrQ3DUYLWd2Q2/qIuqVKuTezZ1YY7ieCcjsnuEJBbzwBSEfMN7RHRS@MXWCwsC0n1BAaPmvrRLaYYqQY9O7jPsTvwHt4DcXhkl3q2uMamV07ffS47T0mfrAtikAV9Db2DNNRqOjbLfTrBvSDPeqvwhpN9a7pGKSWGKfxtAmqfVbu5IQl6OhpL1RWN@reff7ajA/GsZ/PbGV6q/eMlIR/eOjGDnl6OJGfQRSRhOj75vpM9vHxD/6KruWf0nYs2Lb/yTf9Bm8aXJdz3ZG/axCBf9bjHHl09HlvQWku0PBSImr@ZmvcrudfRO4mtg5G6XSN1VvT2BqEV1u5NqoIdvb4m2MRZip8mBCpvcgNTWewqhKY6JxhWerx5XmxKODubwD2FN8FTPKQcFXI3ms0ZBRKERQalf7kYHqE2bWM5ci@dRvyyLyL5MG/hXuKzGC1GlAn5xtQPptjkoYYTYYAzZI22vEhUBm94DAM5gNmAUvoAcfQn@QXlhFIawlEwuLibfsL2alDmMqFW0PbPfSliVDMUxBATN/H7qB2783KHbEwhVJkRbm/VEKN/iO2S2FJX2eFLRQQZI06RBXI0oCtDWZxfwGMjLrgRpWazh3njK1ZCUmU5YpcL8QI8bpNwxQrXOL9gGhpR9HaIWHFkQ7TK0pHxq0nmVlOSkUoO1wN8T2@SuEO7V4yZq1JssDittR15K9as7CyxGvDwFJ50WiYwGwv07vFyjiMJZEp8fH95dYETlx@nv3@@nd9TFNSAuvE/K7GkC4jSN3NrejFXtt4itjd4B6UXV@KUXmtM6P8S6n2aUS2jf5dc65XkCNh@kIb@scMBRhOW8yHfBdepvc@EdTfwIco3wlD4UqWILvBCz8/PY/l8jCnjtf/7Cw) If we stay with this strategy we can easily transform any expression consisting of \$X\$ combinators to an XOISC program which only leaves a single function on the stack. ### Formal proof Given that the SKI-calculus is Turing complete, we need to show two things: 1. the \$X\$-combinator is a basis for the SKI-calculus 2. XOISC is able to represent any expression formed with the \$X\$ combinator The first part - proving the three equalities in the introduction - is very tedious and space consuming, it's also not very interesting. So instead of putting it in this post, you can find [here](https://pastebin.com/raw/E30u3H5K)\*. The second part can be proven by [structural induction](https://en.wikipedia.org/wiki/Structural_induction), though it's easier to prove a slightly stronger statement: Namely, for any expression formed by \$X\$-combinators there is a program that will leave that expression as a single expression on the stack: There are two ways of constructing such an \$X\$ expression, either it's \$X\$ itself or it's \$f\ g\$ for some expressions \$f\$ and \$g\$: The former one is trivial as `0` will leave \$X\$ on the stack as a single expression. Now we suppose that there are two programs (\$\texttt{F}\_1 \dots \texttt{F}\_N\$ and \$\texttt{G}\_1 … \texttt{G}\_K\$) that will leave \$f\$ and \$g\$ as a single expression on the stack and prove that the statement holds for \$f\ g\$ as well: The program \$\texttt{F}\_1 \dots \texttt{F}\_N\ \texttt{G}\_1 \dots \texttt{G}\_{K-1}\ (\texttt{G}\_K + 1)\$ will first generate \$f\$ on the stack and then it will generate \$g\$ but instead of only popping parts of \$g\$ it will also pop \$f\$ and apply it, such that it leaves the single expression \$f\ g\$ on the stack. ∎ ## Interpreter ### Inputs Since the untyped lambda calculus requires us to define our own data types for everything we want and this is cumbersome the interpreter is aware of [Church numerals](https://en.wikipedia.org/wiki/Church_encoding) - this means when you supply inputs it will automatically transform numbers to their corresponding Church numeral. As an example here's a program that multiplies two numbers: [Try it online!](https://tio.run/##lVn9bts4Ev9fTzHwBmtpa@uSdO8OCOqg2W5a5LZpjKZ7F8AxDFqmHWFlUpWoJL3rPdm9w71SbmZI6sNWip6B2BQ5HA7n8zfKnSj/kFn29PSv8Q/w/uzDu9/P3p3De7FdrsQbUUr4YfzvINjqVZVJuBSpgoc7WcggSLe5Lgy80coUOosvtRKr3sn42ggjQZRw/ckTXH8pjdzGSFfqTMbvpLnKzc7ixdXOxLm6TwuttlLVpJ/ko4mnoihl0jMVnz/mRWf@oxQrCAv8Pk8N3iMKgmA8hq/wqzACzJdcwloXUCkariBjNUAisqTKqjJYERUyhQn8XRRwoYzcyAK3o754/iuc5TmP7NNNALCSRXqfqg2cf3aHXah1@gg6l4UweBqduK5UYlKtQOR5liaCxkEYH0R4FLJEdavSCJVIuL7TD8zd2gGgpImQ5BFEzY@inifJxOuQxFrAIiKKwX//Ew7gxQtHSqNBNOjucHQtsnqdWAlYdnm2WEGL@XKXudu8u6W1w5PekAQ3A6cy8hRTVAn61l1VJHegqi2qLwvwd4kmODmprTE@JfX4BYVs6EZ8rXCts1XBNmKFHUUwo99jPGEBr8YwO4pjNZ9HkTt2KoyRhYKtMHjmLxqdVagyMJqGdCgZAg@8FF@Wktf9mkQRADlI8pYJOGkOAcX5W1UaeCuyUrYpjCZew9@GnuJTUVkCTZ76kGIsTuADPqAv9YrX1QxJ@aHa7gnp1ORWJ7DRcYkhkqXrL3gaOxXOOX3xl9UUm5kFO0Q6@@nS1Wo9juDR0iPBY03d5u607zgetWgazl1@SBsevYjg1cHpLtt6y6KloWemreI@ylWFsWTTHKAOtyVgalO62IpsrAuMWUoCaQaoe16HlZalGhrwysKQLcgwQT3RaJr8r552Vh6SkSWQA@ybtSEe1kagHSS93FM3RycNDmhKBHtKc0QcZktphLuu4Ojq0rpg5G3ELOKfZdQmlCxzPdPlSNJXSzjCkdgzNa1gTrNmbDFtPl8pQifMRjyz/Ap4mVgcwHJ81EvW1iYftkdVy0LaWTYqpPlQvUBvDFOVvC2kxDAl7T3PgbS1hKRWnF9ArvU4iXr3Y8Lk1HYT7C3705XP5s/qQ9TqEC@@Tx3iW6ft@JRfsUr55s5dD2qWRNR@6jG9X6zV4VMaVm4QxaaiOl@CUCsoNSY2OQJ5L7KKsERe6E1BQuNiXqTKQCHLKjNlUFTqukgoFDkLYyzOrg1SbOY0tkMaXVxBGHnqJZEiPiFlPSAu@Jhu7gyE/0zzf@DTJeQk04XKKwOzwzieI22EerpNaapEdhSzzb6tyC@hwRhI@YAZBdnzJpKdJFhpVkkmMaUYkfyBZxfyXtLtHV8sifJRJhY@MdcFq@CCSiHrAMvXvFYs15EmkxyALXbhOktzsk5kDX0ALvfyqfVuBDyofdYEfyZYVKhcDLCeGzpv4KrfAPk0Na5r167f7TLo1ifLh2pQzeZuWhk00XuFsmEGxi1vUyUyK@kJDJjI6iHcpY0JNAzbt8o9wYHngwehn5QIrU5aiIP0hmNUQFDnXhbYMHjweMYwUmlvVA24cfFNInwDIA33EdKwDZH6uOztbW/d2ZO9Zgsv2kb5ClkLXdwMHarqt5mzPN8u22H@6BceXaSe@2gU6HRqk5HfWoxG2LVxVAvNOPw@uV5ghsLMKQAbKlI1hwQ6RT5aahMRHivRl80ZGYLLvjQB29U5d9Zx7vqKEd42hxN0ZuNFtYG4FljQEWyvNKaUrWRAwIELdBUZNDFMpdzucSlDkPyhcKkDreIGrT3YOlCdtNvCVJ8XhS7iqpQFjyJclt0k51FhG/@PAXesuCdI9HaLGW6cpcrnhKCVilp6rdNaV2iCIa0NqiXee7k2ELNBI7DyxzbP2ZOm6KM8aLl7VIeHI0GHyEWC0obuImQkzMZTePX1lOJqikb8CaReB@0sNYVmJxb0Ks1W53VksmoKmM1sk4Tt0BTOylInJPEcU6/R22nNjZ@QGxqwmHZLDImA/VvPrHUUklUrebVGJ0IISo@o8CUmCuzJymh/G8KeBymx6CV3mECHIfqZG0Y0dBfiWzfXZfkpFaovR/bO8NMpJnpTIWynxs4T0gVcrfZarNfoGq4601poxcb27PZ2QOxYC61D2QQTLkG8wZ6@SjepaYicvOhFtln2ThNG1tn3Z3e35t6MJQmRk6nto/PyX9CyZoywuqVXdmzyM8Li7XmUYxa@QXWO0DjRvLM2gRmEw@vhiFUQt75tMXsJsatqNLAtQz0V7UKPEfL6rcPLUh73EV44Qs@sh@SmS0IHu1R0PWR5nhF6T7B5ENiNqAvShO8k7GRC2ka8E8Md2RUzIGqXQjlMJpMoRh@O2orewVOqVfwYNiVaIdgwKCqa2@OpcJ0WGAvHLfyVbrApkqsoEOX2e2EVkS646/LpZrda78HBsK7WMTZeFi/FVOtt7om9vDc0bfQNArC4jcsOfW5ixkTAzVOw03e6CrkHrRFWa8NwlKD1DZmNv6hLqpRrE3t2teFOIjinY7LbB@TWM4BUxHxDe0T03PgZFgvLQlI9gcGDpn70DlOMVIOeHdzn2B14D@@BODywSz1bXGPTK6fvPpedp6RP1gUxyIK@ht5BGmo1HZvlLp3gXpBnvVV4w9GuNV2jlBLDFP40AbXLqt3ckAQ9HY2l6opG/duPP9rRnnjWs/ntDC/V/vGckPevnZhBTy9HkjPoIpIwHR9928nun7@hf9HV3DP6xkWbll/5pn@vTePLEu57tDdtYpCvethjj64eDy1orSVa7gtEzd9MzfuV3OvoncTWwUjdrpE6K3p7g9AKa/cmVcGWXl8TbOIsxU8TApVXuYGpLLYVQlOdEwwrPd48KzYlnJ5O4JbCm@ApHlKOCrkdzeaMAgnCIoPSv1wMD1CbtrEcuZdOI37ZF5F8mLdwL/FZjBYjyoR8Y@oHU2zyUMOJMMAZskZbXiQqg1c8hoEcwGxAKX2AOPqj/IxyQikN4SgYnN9MP2J7NShzmVAraPvnvhQxqhkKYoiJm/h90I7dWblFNqYQqswIt7dqiNHfxXZJbKmr7PClIoKMEafIAjka0JWhLM4v4LERF9yIUrPZw7zxFSshqbIcscuFeAEet0m4YoVrnF8wDY0oejtErDiyIVpl6cj41SRzqynJSCWH6x6@pzdJ3KHdKsbMVSk2WJzW2o68FWtWdpZYDXh4Ao86LROYjQV693g5x5EEMiU@vr14f44TFx@mv3@6nt9SFNSAuvE/K7GkC4jSN3NrejFXtt4itjd4B6UXV@KEXmtM6P8S6m2aUS2jf5dc6pXkCLh7Jw39Y4cDjCYs532@C65TO58J627gQ5RvhKHwuUoRXeCFnp6exvLpEFPGMfjvIx793Hl@@Z2r9PfXmur4/9j1584u@vvL089PL/8H) You can also supply functions as arguments by using [De Bruijn indices](https://en.wikipedia.org/wiki/De_Bruijn_index), for example the `S` combinator `\\\(3 1 (2 1))` (or `λλλ(3 1 (2 1))`). However it also recognizes the `S`, `K`, `I` and of course `X` combinator. ### Output By default the interpreter checks if the output encodes an integer, if it does it will output the corresponding number (in addition to the result). For convenience there's the `-b` flag which tells the interpreter to try matching a boolean instead (see the last example). ### Assembler Of course any low-level language needs an assembler that converts a high-level language to it, you can simply use any input (see above) and translate it to a XOISC-program by using the `-a` flag, [try it online!](https://tio.run/##rVnvcts4Dv@up8B4M2tpY@vidD9l6kyzvbST3aTxNN27zDgeDy3TtmZlSpWo/LnrPdm@w75SDgBJ/bGVXD@c27EpEgBBAAR@UDai@EMmyfPzv4c/wOXZp4@/n308h0uxXSzFe1FI@GH4H8/bpssykXAlYgUPG5lLz4u3WZpreJ8qnadJeJUqseycDG@00BJEATdfHMHNU6HlNkS6Ik1k@FHq60zvLF5c70ycq/s4T9VWqor0i3zU4UTkhYw6psLzxyxvzX@WYgl@jt/nscZzBJ7nDYfwDf4utAD9lElYpTmUioZLSNgMEIkkKpOy8JZEhUJhDP8QOVwoLdcyR3a0F89/g7Ms45F5uvUAljKP72O1hvOvdrMLtYofIc1kLjTuRjuuShXpOFUgsiyJI0Fjzw8PAtwKRaK5VaGFiiTcbNIHlm78AFDQhE/6CKLmR1HNk2binU9qzWEeEEXvrz/9HhweWlIa9YJem8PSNciqdRIlYNGW2RAFDeGLXeGWeZelweFIb0mD2541GUWKzssIY2tT5tEGVLlF8yUe/i7QBScnlTeGp2Qet6BQDJ2Ij@Wv0mSZs4/YYKMApvR7jDvM4e0QpqMwVLNZENhtJ0JrmSvYCo17/pJisApVeDqlIW1KjsANr8TTQvK6W5OoAqAESdEyBqvNEaA6v5aFhg8iKWSTQqckq/9b31F8yUtDkFKkPsR4F8fwCR8wljrVa1uGtPxUbveUtGayq2NYp2GBVySJV0@4GwcVzll78ZexFLuZFTtCOvNp01VmPQ7g0dAjwWNF3ZRurW8ljho0teS2PKT1R4cBvD043RVbscwbFnph2hjus1yWeJdMmgO04bYATG0qzbciGaY53llKAnECaHteh2UqC9XX4IyFVzYnx3jVRG1pir9q2nq5T06WQAGw79aauF85gThIe7lnbr6dNDigKeHtGc0S8TVbSC3scQXfrjatvYzMRsIC/lkETULJOlczbYmkfbmAEY7EnqtpBXOacWNDaP35Rjd0zGLEC8tvgZdJxAEshqNOsqY1ebM9qkoXss6iNiHN@@oQo9GPVfQhlxKvKVnvZQlkrQVEleHcAkqtxlHQyY8Jk1Pbrbe37HZXLpu/aA9RmUMcfp85xGu77cSUWzFGeZVzN4LqJRE0nzpc7xYrc7iUhpUbRL4uqc4XINQSihQTmxyAvBdJSVgiy9N1TkrjYpbHSkMuizLRhZeX6iaP6CpyFsa7OL3RSLGe0dgMaXRxDX7gqBdEiviEjPWAuOBzvN5o8P8VZ//EpyvISKcLlZUapkdhOEPaAO10F9NUgeLoztZ8W5FdQY0xkPIBMwqKZybSnTRYpmySRGJK0SL6A/fO5b2k01u5WBLlo4wMfGKpczbBBZVCtgGWr1llWK4jdSY5AFPs/FUSZ@SdwDj6AGzu5V0rbgQ8aH22BH/GWFSoXPSwnmvar2erXw/l1DWu7dd23O0KaNcnI4dqUCVmMyk1uuhSoW6YgZHlQ6xEYjQ9gR4TGTv4u7QhgYZ@81SZIzhwcnAjjJMCodVJA3GQ3XCMBvCq3MsKawYPDs9oRipNRlWDG3u/SYVXAFJ/HyH1mxCpS8oeb5N1hyd5xx6eN53yDZIGurjtW1TV7TPreT5dsiP80S082pt67m6jwKBT64Ti1mA0wq51oBpoxtfvi@0FpqjMjC5gTUWm5iuBQZENFqkOCI8VGMv6jBzBZV9qj/1qgztpBXd1xABPm8EJBrN2qpqLuBJY0BFsL1NMKVvJgIAvLtBRpFffYSrlhsemDEH6@8KmDvSKHTR4sHWgOmnY/Dg9z/M0D8tC5jwKcFm2k5xDhU38PwTkWHJPEKXbLWa4YRIrlxO8Ripq2LVKa22lCYY0GFRDvUu50hCyQwMw@ocmz5mdJhijPGiEe1BdD0uCAZGJCLX17UHISZiNJ/D22yndqwk68SeQ6cprZqkJ1JxY0Ms4WZ5XN5NNk8N0apokbIcmcFYUaUQazzD16nQ7qaTxE0pDB@aTdokhFbB/65g1gUK6pkperzCIEILSIxp8gYkCe7Ii2GdD2PMgJRa9aIMJtO9jnNlhQEN7ID51fVzWn1KhehqZM8NPp5jodYmwnRo7R0gHsLXaWbFao2PY6kxrvlEb27O7ux6JYys0NmUXjLkEMYPZfRmvY10TWX0xikyz7ILGD0yw78/usmbOjQUpkZGrzaON8l/Qs3qIsLphVw5sijPC4s151GPqv0dzDtA5way1NoYp@P2b/oBNEDa@TTF7A6GtajQwLUM1FexCjwHK@q0ly1AedxFeWEInrIPktk1CG9tUdNNnfV5Qek@xmecZRrQFWcJ1EmYyImsj3glhQ37FDIjWpavsR@NxEGIMB01D7@Ap1Sh@DJuiVCHY0KgqutvhKX8V53gXjhv4K15jUySXgSeK7ffCKiKdc9fl0s1utd6Dg35VrUNsvAxeCqnWm9wTOn1vaVqntwjAwiYuO3K5iQUTATdP3k7faSvkHrRGWJ1qhqMErW/JbfxFXVKpbJvYwdWEO5HgnI7Jbh@Qm8gAMhHL9c0WwUvjF0TMjQhJ9QR6Dyn1oxtMMVL1Oji4zzEceA4XgTg8MEsdLLax6dTTdZ@L1lPUpeucBCReV0NvIQ21mlbMYpdOcC/Is84rzDDa9aZtlGISGMPfxqB2RTWbG9Kgo6MxVG3VqH/78Ucz2lPPRDa/neGlKj5eUvL@nVXT6@jlSHMGXUTix8PR60F2//IJ3Yuu@pzBKwetW37lmv69No0PS7jv0Zy0voN81KMOf7TteGRAa6XRYl8hav6matZt5M5AbyW2FkZqd43UWdHbG4RWWLvXsfK29PqaYBNnKX4aE6i8zjRMZL4tEZqmGcGwwuHNs3xdwOnpGO7oehM8xU2KQS63g@mMUSBBWBRQuJeL/gFa0zSWA/vSacAv@wLSD/MW8pKc@WA@oEzIJ6Z@MMYmDy0cCQ2cISu05VSiMnjNY@jJHkx7lNJ7iKM/y6@oJxRSE46C3vnt5DO2V70ikxG1gqZ/7koRg0qgIIGYuEnep9SKOyu2KEbnQhUJ4fZGDdHpd4ldkFjqKltyqYigYMQpMkeJGtJSUxbnF/DYiAtuRKnZ7BBex4rRkExZDDjkfDwAj5skXLH8Fc7PmYZGdHtbRGw48iF6ZWHJ@NUkS6soyUkFX9c9fE9vkrhDu1OMmctCrLE4rVIzcl6sRJlZEtXj4Qk8pnERwXQoMLqHixmOJJAr8fHDxeU5Tlx8mvz@5WZ2R7egAtR1/BmNJR1AFK6ZW9GLuaLxFrHJ4AKUXlyJE3qtMaa/S6gPcUK1jP5ccpUuJd@AzUep6Q87fMFowkjelzvnOrXzGbPteu6K8onwKnwtY0QXeKDn5@ehkM9//enj/2PwR4TcoDGmB/qHE3bwhge4ilM/8zotYZoZWQrzywL@F4uVjP9H1U6WHU0D/v9FL7fJG@jYptay3pcIv@e8AalxbM89AkeJzD/brSpFq0P@Fw)\*\* --- \* In case the link is down, there's a copy as HTML comment in this post. \*\* This results in a program that tests for primality, [try it online!](https://tio.run/##7Vn9btvIEf@fTzHQGSfyIrGW0yR3RmTElzqBe3EsxLnWgCwIK2olEUctGXJpO236ZH2HvpI7M7ukSJFy0jukzRURYGm5Ozs7O5@/oVci@0VG0d3d3/vfwKvj1y9/Pn55Aq/EejYXz0Um4Zv@PxxnHc/zSMKZCBXcrGQqHSdcJ3Gq4XmsdBpH/lmsxLx10r/QQksQGVy8LQgu3mdarn2ky@JI@i@lPk/01uLp@dbEiboO01itpSpJ38pb7Y9EmsmgZco/uU3S2vwbKebgpvh9Emq8h@c4Tr8PH@BPQgvQ7xMJiziFXNFwDhGrAQIRBXmUZ86cqJApDOEvIoVTpeVSprgd9cXzH@A4SXhkni4dgLlMw@tQLeHknT3sVC3CW4gTmQqNp9GJi1wFOowViCSJwkDQ2HH9PQ@PQpaobpVpoQIJF6v4hrkbOwBkNOGSPIKo@VGU8ySZeOaSWFOYekTR@dc/3Q48eGBJadTxOvUdlq5CVq4TKwGzOs8KK6gwn20zt5u3t1R2FKSXJMFlx6qMPEWneYC@tcrTYAUqX6P6Igd/Z2iCw8PSGv0jUk@xoJAN3Yiv5S7iaJ6yjVhhAw/G9HuAJ0zhaR/GA99Xk4nn2WNHQmuZKlgLjWf@GKOzCpU5OqYhHUqGwAPPxPuZ5PViTaIIgBwkecsQrDT7gOL8Oc80vBBRJqsUOiZe3Z@6BcXbNDcEMXnqTYixOITX@IC@1CpeXTMk5et83RDSqsmuDmEZ@xmGSBQu3uNp7FQ4Z/XFX0ZTbGYWbB/pzKdOV6r1wINbQ48EtyV1lbvVvuU4qNBsONf5Ia07eODB072jbbbllmlFQzumjeLeyHmOsWTSHKAO1xlgalNxuhZRP04xZikJhBGg7nkd5rHMVFdDoSwM2ZQM45QTG02T/5XT1spdMrIEcoCmWTfE3dIItIOklw11c3TSYI@mhNNQmiXiMJtJLex1BUdXndYGI28jZh7/zLwqoWSZy5k6R5I@n8EAR6JhalrBnGbMWGG6@XygCB0yG7Fj@SnwMrHYg1l/0EpW1SYf1qAqZSHtzDYqpHlXPUBvdEMVvEilxDAl7e3mQNqaQVAqrlhAruU48Fr3Y8Lk1HbpNJaL01WRzXfqQ5TqEA8@TR3ivtO2fKpYMUq5d@e2B22WhFd9ajF9sViqo0hpWLlBpMuc6nwGQs0hizGxyR7IaxHlhCWSNF6mJDQuJmmoNKQyyyOdOWmuLtKAQpGzMMbi@EIjxXJCYzOk0ek5uF5BPSNSxCekrBvEBW/C5UqD@7cw@Ss@nUFCMp2qJNcw3vf9CdJ6qKerkKYyZEcxu9m3FskZbDAGUt5gRkH2vIlkJwnmMaskkphStAh@wbNTeS3p9pYvlkR5KwMDn5jrlFVwSqWQdYDla1IqluvIJpPsgSl27iIKE7KOZwy9Bzb38qnlbgQ8qH3WBH@GWFSoXHSwnms6r2OrXwf5bGpc3a51v9tmUK9Phg/VoJLNapRrNNErhbJhBsYtL0IlIiPpIXSYyOjB3ab1CTR0q7dKCoK9gg8ehH6SIbQ6rCAO0huOUQFOmXtZYM3gocAzmpFKdaPagBsb3yTCPQCp20RI3SpEauPS2FvdurUnesYWnlaN8gGiCrq47FpU1W4za3m@XbTF/LZYuLWRelJEo0CnU8uI/NZgNMKuG0c10IzD763tBcYozIQCcENFquaQQKdIerNYe4THMvRlfUyG4LIvtcN2tc4d1Zy7vKKHt03gEJ1ZF6KaQFwILOgItucxppS1ZEDAgQt0FelsYphKudljU4Yg@V1hUwdaxQ4qe7B1oDpptrlhfJKmcernmUx55OGyrCe5AhVW8X8fcMece4IgXq8xw/WjUBU5wamkoopey7RWF5pgSGWDqoj3Si40@GxQD4z8vslz5qQR@igPKu7uleFhSdAhEhGgtK69CBkJs/EInn44orgaoRG/AxkvnGqWGsFmJxb0PIzmJ2VksmpSGI9Nk4Tt0AiOsywOSOIJpl4dr0clN35CbmjAdFQvMSQC9m8ts8ZRSNZYyfMFOhFCUHpEhc8wUWBPlnnNbQh7bqTEohesMIF2XfQzO/RoaC/Et95cl@WnVKjeD8yd4bsjTPQ6R9hOjV1BSBewtbrQYrlG17DVmdZcIza2Z1dXHWLHWqgcyiYYcgniDeb0ebgM9YbIyoteZJrlwmlczzh7c3Z7a1KYMSMhEjK1ebRe/iNaVvcRVlf0yo5NfkZYvDqPcozd56jOHhrHm9TWhjAGt3vR7bEK/Mq3KWYPwbdVjQamZSinvG3o0UNeP9V4GcqDNsJTS1gwayG5rJPQwTYVXXRZnh1CNwSbOI7ZiLogTRSdhJkMSNuId3xYkV0xA6J2KZTdYDj0fPRhr6roLTylKsWPYVMQKwQbGkVFcxd4yl2EKcbCQQV/hUtsiuTcc0S2/lRYRaRT7rqKdLNdrRtw0C2rtY@Nl8FLPtV6k3v8Qt5LmtbxJQIwv4rL9ovcxIyJgJsnZ6vvtBWyAa0RVsea4ShB60syG39Rl5Qr2ya27KrCnUBwTsdk1wTkxjOAVMR8XXOEt2u8g8XUsJBUT6BzE1M/usIUI1WnZQf3OWYH3qPwQBzumaWWLbaxaZWz6D5ntaegTdYpMYictobeQhpqNS2b2Tad4F6QZwur8IbBtjVtoxQSwxD@MAS1zara3JAELR2NoaqLRv3bt9@aUUM849n8doaXSv/YJeT1Myum09LLkeQMuojEDfuD@53sevcNixddm3t691x00/KroulvtGl8WcJ9t@ammxjkq@632KOux30DWkuJZk2BqPkbq0m7klsdvZbYahip3jVSZ0VvbxBaYe1ehspZ0@trgk2cpfhpSKDyPNEwkuk6R2gaJwTDsgJvHqfLDI6OhnBF4U3wFA/Jeqlc98YTRoEEYZFBVrxcdPdQm6ax7NmXTj1@2eeRfJi3cC/xmfamPcqEfGPqB0Ns8lDDgdDAGbJEW4VIVAbPeQwd2YFxh1J6B3H0G/kO5YRMasJR0Dm5HL3B9qqTJTKgVtD0z20polcyFMQQEzfxex1bdsfZGtnoVKgsItxeqSE6/iS2M2JLXWWNLxURZIw4RabIUUOca8ri/AIeG3HBjSg1my3MN75iJCRVZj12ORcvwOMqCVcsd4HzU6ahEUVvjYgVRzZEq8wsGb@aZG4lJRkp43Bt4Ht6k8Qd2pVizJxnYonFaRGbUWHFkpWZJVYdHh7CbRxmAYz7Ar27P5vgSAKZEh9fnL46wYnT16Of315MrigKSkC98T8jsaQLiKxo5hb0Yi6rvEWsbigclF5ciUN6rTGk/0uoF2FEtYz@XXIWzyVHwOql1PSPHQ4wmjCcm3ynXKe2PkPWXacIUb4RhsK7PER0gRe6u7vrz@TdPuaMA6h/D3j0x9rzw/KJ/h6VVAe1@TrV48/Od/CREz7XbF3yupyDT9hbHT3@1fT1lUe/UduDnVqlvycfPbVt16N7Th8U04N7iH6o0Azq25tTj7eIBztZ7Tru@5Z7NL@/Wvq/aukfPlHVD3cI9OuUVHWHpkxPPnKbweCz5Kj6Qe2e@jV7f83ev7fs/Z@H95MvRO/baaJyxf3PWI6q7vqbstOXo72vEft7w1vs4U34tRuQtW79Uqzwf5R5Dlqnv/@fYKjHd4/@DQ) [Answer] # Draw [Draw](https://github.com/0-zM/draw) is an OISC acting on a 2D grid, marking squares in a manner similar to the Wang B-machine. However, to keep the language as simple and OISC-y as possible, all instructions (of which there are a grand total of one) mark the square just stepped on, and, in order to be able to halt, stepping on a marked square terminates the program. The program consists of a sequence of lines containing a line identifier (arbitrary string not including # or whitespace), two integers (`x` and `y`) and two more line identifiers (`a` and `b`). The program runs as follows: Starting at the line identified as `start` with the pointer pointing to position (0, 0), move the pointer by the amount given by `x` and `y` and mark the square the pointer is now on (unless the square is already marked, in which case execution terminates). Then, jump to line `a` if at least one of the directly adjacent squares is also marked, and to line `b` otherwise. Interpreters are encouraged to output the final result of the grid as some sort of image, canvas, etc. ## Turing-Completeness Draw is Turing-complete as it is possible to compile a modified version (called Alternate) of a Minsky machine into the language. Alternate acts similarly to a two-counter Minsky machine, but there is a large restriction placed on the commands: commands must alternate between targeting the first and second counter. To get around this modification, an additional command has been added: `nop`. This command doesn't change the targeted counter at all, which makes it possible to "pad" consecutive changes to one counter, satisfying the restriction outlined above. This also means that the register that is to be modified doesn't have to be given and, for any given instruction, can be directly inferred from the instructions from which execution can jump to it. Example: this Minsky machine ``` 1 inc A 2 2 inc A 3 3 dec A 3 4 4 halt ``` turns into this Alternate program: ``` 1 inc 2 2 nop 3 3 inc 4 4 nop 5 5 dec 6 8 6 nop 5 7 halt 8 halt ``` This restriction is necessary due to the way that the eventual Draw program handles registers, which is to say that it doesn't differentiate between them at all. Instead, the Draw program simply copies the register that hasn't been changed by the preceding instruction, modifying it according to the instruction being executed. Then, the Alternate program is directly translated into Draw as follows: The program starts with this block. ``` start 0 0 a a a 3 0 b b b -3 1 c c c 3 0 d d d -3 2 e e e 3 0 f f f 3 -3 i1_a i1_a ``` `inc`, `dec` and `nop` are translated in almost the same way as each other. In all cases, there is no difference between changing the first or the second register (as explained above). Here is an increment, equivalent to `inc 2`: ``` i1_y 0 -2 i1_z i1_y i1_z 3 -1 i1_a i1_a i1_a -5 1 i1_b i1_b i1_b 0 2 i1_c i1_c i1_c 0 2 i1_d i1_e i1_d 0 2 i1_d i1_f i1_e 5 0 i2_z i2_y i1_f 5 0 i2_z i2_y ``` Change the numbers in the `i1_x` parts to the index of the current instruction, and in the `i2_x` parts to the index of the next instruction to be executed. The `nop` instruction can be translated as such: ``` i1_y 0 -2 i1_z i1_y i1_z 3 -1 i1_a i1_a i1_a -5 1 i1_b i1_b i1_b 0 2 i1_c i1_c i1_c 0 2 i1_d i1_e i1_d 0 2 i1_d i1_f i1_e 5 -2 i2_z i2_y i1_f 5 -2 i2_z i2_y ``` This is a decrement: ``` i1_y 0 -2 i1_z i1_y i1_z 3 -1 i1_a i1_a i1_a -5 1 i1_b i1_b i1_b 0 2 i1_c i1_c i1_c 0 2 i1_d i1_e i1_d 0 2 i1_d i1_f i1_e 5 -2 i3_z i3_y i1_f 5 -4 i2_z i2_y ``` `i3_x` refers to the instruction to be called if the counter is already 1. Halt: ``` i1_y 0 0 0 0 i1_z 0 0 0 0 ``` Change labels appropriately and simply chain everything together. Doing this for the example from above gives the Draw program in the repository from above. ## Interpreters There are currently two interpreters, both written in Python. They can be found on Draw's [GitHub repository](https://github.com/0-zM/draw). 1. **draw.py**: This interpreter is meant for the command line and takes the program source as an argument. After every step, it outputs the command that was executed and the location of the instruction pointer; after the program halts, it prints the number of marked cells. 2. **draw\_golly.py**: This version uses [Golly](http://golly.sourceforge.net/) for exactly the wrong purpose easier graphical output, taking the source via a popup box when starting the script. Golly can be a little finicky with Python, so make sure you have Python 2 installed (and don't mix 32-bit Golly with 64-bit Python or vice versa). Output is provided via Golly's builtin cell grid. The following image is an example for output from the second interpreter. Running the example program in the repository gives this (or similar): ![](https://raw.githubusercontent.com/0-zM/draw/master/images/draw_in_golly.png) [Answer] # -3 [Here's the gist.](https://gist.github.com/ConorOBrien-Foxx/2e4daf1b2e4686e593209edfb2aadee5) ## Memory Memory is a map of tapes, where the keys are strings and values are arbitrary-sized integers. Additionally, there is a set of labels, where the program can jump to. There is a stack, which contains the operands, which are strings. There is an offset, which controls where in the memory's tapes it can access. ## The One Instruction `-`. First, it pops a string `LABEL` off the stack. If that `LABEL` is undefined as a label, it defines the label, and clears the source of that label (i.e. where it was pushed from) and the current instruction. Otherwise, it performs the following calculation, using the top two values, `A` and `B`: ``` if mem[A] < mem[B]: jump to LABEL if mem[A] != mem[B]: mem[A]-- else: mem[B]++ ``` Note that if there are excess arguments or insufficient arguments, the program will error out, showing the program's state. The offset can be modified by accessing the value of `.`. ## Example code ``` X- i i X- i i X- i i X- i i X- i i X- i i X- i i X- ``` This sets variable `i` to `7`, by incrementing `7` times. ``` X- i i X- i i X- i i X- LOOP- a a X- a a X- j i LOOP- ``` This multiplies `i+1` by the constant `2`. ## Proof of Turing Completeness Disregarding C++'s int sizes (that is, assuming they are infinite), -3 is Turing Complete by reduction to [3-cell brainfuck](https://esolangs.org/wiki/Collatz_function#Reduction_to_3-cell_brainfuck). I can disregard this size because there can be written an interpreter for -3 on a computer with infinite memory that has arbitrarily-large cells. I also believe that any [BCT](https://esolangs.org/wiki/Bitwise_Cyclic_Tag) can be written as a -3 program. ]
[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/9037/edit). Closed 1 year ago. [Improve this question](/posts/9037/edit) Input: an integer N between 1 and 151 Output: the Nth Pokemon. ## Rules * You may use **one** data file. * You may not use any already made data decompression algorithms. This includes libraries and other programs. * Your program may not access files other than itself and your data file. ## Scoring Your score is the sum of the length of your code and data file. ## Helpful Stuff Here's a list of the first 151 pokemon separated by semicolons to help you generate your data file. Your output should exactly match the Nth entry of this line: ``` Bulbasaur;Ivysaur;Venusaur;Charmander;Charmeleon;Charizard;Squirtle;Wartortle;Blastoise;Caterpie;Metapod;Butterfree;Weedle;Kakuna;Beedrill;Pidgey;Pidgeotto;Pidgeot;Rattata;Raticate;Spearow;Fearow;Ekans;Arbok;Pikachu;Raichu;Sandshrew;Sandslash;Nidoran (f);Nidorina;Nidoqueen;Nidoran (m);Nidorino;Nidoking;Clefairy;Clefable;Vulpix;Ninetales;Jigglypuff;Wigglytuff;Zubat;Golbat;Oddish;Gloom;Vileplume;Paras;Parasect;Venonat;Venomoth;Diglett;Dugtrio;Meowth;Persian;Psyduck;Golduck;Mankey;Primeape;Growlith;Arcanine;Poliwag;Poliwhirl;Poliwrath;Abra;Kadabra;Alakazam;Machop;Machoke;Machamp;Bellsprout;Weepinbell;Victreebell;Tentacool;Tentacruel;Geodude;Graveler;Golem;Ponyta;Rapidash;Slowpoke;Slowbro;Magnemite;Magneton;Farfetch'd;Doduo;Dodrio;Seel;Dewgong;Grimer;Muk;Shellder;Cloyster;Gastly;Haunter;Gengar;Onix;Drowsee;Hypno;Krabby;Kingler;Voltorb;Electrode;Exeggute;Exeggutor;Cubone;Marowak;Hitmonlee;Hitmonchan;Lickitung;Koffing;Weezing;Rhyhorn;Rhydon;Chansey;Tangela;Kangaskhan;Horsea;Seadra;Goldeen;Seaking;Staryu;Starmie;Mr. Mime;Scyther;Jynx;Electabuzz;Magmar;Pinsir;Tauros;Magikarp;Gyarados;Lapras;Ditto;Eevee;Vaporeon;Jolteon;Flareon;Porygon;Omanyte;Omastar;Kabuto;Kabutops;Aerodactyl;Snorlax;Articuno;Zapdos;Moltres;Dratini;Dragonair;Dragonite;Mewtwo;Mew ``` [Answer] **Bash** *1182 chars* ``` read n;echo {Bulba,Ivy,Venu}saur Char{mander,meleon,izard} {Squi,Warto}rtle Blastoise Caterpie Metapod Butterfree Weedle Kakuna Beedrill Pidge{y,otto,ot} Rat{tata,icate} {Sp,F}earow Ekans Arbok {Pika,Rai}chu Sands{hrew,lash} Nido{ran%\(f\),rina,queen,ran%\(m\),rino,king} Clefa{iry,ble} Vulpix Ninetales {Jigglyp,Wigglyt}uff {Zu,Gol}bat Oddish Gloom Vileplume Paras{,ect} Veno{nat,moth} Diglett Dugtrio Meowth Persian {Psy,Gol}duck Mankey Primeape Growlith Arcanine Poliw{ag,hirl,rath} {A,Kada}bra Alakazam Mach{op,oke,amp} Bellsprout {Weepin,Victree}bell Tentac{ool,ruel} Geodude Graveler Golem Ponyta Rapidash Slow{poke,bro} Magne{mite,ton} Farfetch\'d Dod{uo,rio} Seel Dewgong Grimer Muk {Shelld,Cloyst}er Gastly Haunter Gengar Onix Drowsee Hypno Krabby Kingler Voltorb Electrode Exeggut{e,or} Cubone Marowak Hitmon{lee,chan} Lickitung {Koff,Weez}ing Rhy{horn,don} Chansey Tangela Kangaskhan Horsea Seadra Goldeen Seaking Star{yu,mie} Mr.%Mime Scyther Jynx Electabuzz Magmar Pinsir Tauros Magikarp Gyarados Lapras Ditto Eevee {Vapore,Jolte,Flare,Poryg}on Oma{nyte,star} Kabuto{,ps} Aerodactyl Snorlax Articuno Zapdos Moltres Dra{tini,gon{air,ite}} Mew{two,}|tr %\ \ \\n|sed $n!d ``` [Answer] ## PHP 919 (925) bytes As with [Peter Taylor's answer](https://codegolf.stackexchange.com/questions/9037/whos-that-pokemon/9050#9050), I also cannot post my solution directly, so instead i'll post a program that *generates* it: ``` <?php $data = <<<EOD PD9mb3IoJG89J5SWUHYPaY6dSs/pjsJBMS1pRDc1yZ3AUcQkNcnZsYIkJDXtpa4UB4mOMNH8zbDbcDhcKD VYu89cFyjRlBm8GSjMiFSxCNHitpn8Kdi43B+XUkX2gVjN8LQEmEkF5D2zE9gbTD3z6djUJQAVFXwlXV/o kVwnsV1rW5J9zpssN3JXdW5LjAS3DYTcBtV/YUdtoAfGC+ztsoc1LxQamD5lmQMaes37flJcGvg7CdkS+s 1bhZLjAQQtmL5tS3rN+2eS7LeROnX9nOCRRWhRQhFkBDSN0igwMUwem4BNYVrkxZuAzUEiRDG+KFODVqV0 KDAvpLM747wC0AwYUVkELsVsBA5vyThUQQtiKFRBK6EYnBC7oMiAkJtYbXOZk9scdPF3hTJEh7hhZ4yDEG FHzJ1vSfxkDVkd8fz+u6ConHVH7Y3SHFtgq20M22ALpO40xMC9vmictX6lf+2VfqV1EBctRRwZ38RceT3E G2l5PcTVTFahWEdGGYhjKSwy5lBYAn944VmhWNQRkvXDw5SAkpV/URm0SZPBOPweZUGwDlODERHEwt0VfK X9WG+kp9tbe+d8oLvu1uw9+6ExyFwZe6LogoTF7oG3RCiUm0GTcJsmcyxJmdRR68Oi7P4NmQ6ZlwxE8djR DtfANTjRZBOvWE281RLRDtPJY05E4k10BkvfCRwNLKssXh4GHB+SgBFEwsDbHsSxMdhmCBExsfvZKLzEEY uZ26SXfutBOR1rezc8/XmT6HkcHciTBwTSxD1cJ+XBcmyjis2S7ClZLZJMTG2bngTs7VtCN3VSaQUAcuPQ VR9yY0+ntSTcnhcdZ4n4JtzDwPHZJEl9pZJsONV96ad1jpV5eVhpldF8r7WcMeRd8hSxMXjVEcZEPZsdLg SSd+4kNY7L7Bkbdy10VDVuJdtfGOyG7yydwJux2SFcAiz7QSIEa8BxAoQIFUFCRJt+G6KkoZ3d8fzBPZhO xG2eaIwfvrGb54zZ7mgfGPA0Qp6I5NSund9SSw5MUD8M0wAmzywmSF2N/CZbw8V1JEZF42LIXJmLeIM5uU wnOzc4OD4kbjspJGY9c3BsaXQonywkeC49Y2hyKDMxJiR2PSsrJGklOCUzPzgqJHZeb3JkKCRvWyRuKytd KTokdj4+NSleiyk7ZWNob35zdHJ0cigkZlsrZmdldHMoU1RESU4pXXygLICEgYOCLNfY1tHfKTsNCg== EOD; print base64_decode($data); ?> ``` Sample I/O: ``` $ php generator.php > out.php $ echo 12 | php out.php Butterfree $ echo 32 | php out.php Nidoran (m) $ echo 83 | php out.php Farfetch'd $ echo 122 | php out.php Mr. mime $ echo 151 | php out.php Mew ``` How it works (spoiler): > > This code operates on the observation that there are only 32 unique characters, including a separator - if you're not counting capitals. This immediately implies a 5:8 encoding; only 5 bits are needed to represent each byte. > > > > I accomplish this in the following manner: > > > > ++$i%8%3 > > > > When this value is non-zero, a new byte is read, and when zero, the next byte is generated from the previously read bytes. The 3rd, 6th, and 8th byte are generated in this manner, and then the process repeats. > > > > The bit distribution follows accordingly. If for example you wanted to produce the string: > > > > abcdefgh > > > > The bits for each are distributed among the 5 source bytes in the following fashion: > > > > hccaaaaa|cccbbbbb|hffddddd|fffeeeee|hhhggggg > > > > After generating c, only the top most bit of h remains, after generating f, the top two bits of h remain, and after reading g, h remains in its entirety (I save a few shift operations by using xored values instead, for example the value I load for the second byte is the value I want xor a<<3, but that's the gist of it). > > > > This produces characters on the range of [0,31]. By xoring by any character on the range [96,127], all characters will be mapped to that range (I chose 116, because it resulted in the least amount of escape sequences). After that, it's a simple matter of translating the 5 characters that don't belong there with their appropriate replacements, and capitalizing the first letter. This code requires three bytes to do so: oring the (previously generated as such) bit inverted string with char 160, and then bit inverting back. A small caveat: the second m in 'Mr. mime' is not capitalized by this method. This could be repaired by replacing the method described above with the ucwords() function, at the cost of 6 bytes, resulting in a code length of 925, instead of 919. > > > [Answer] ## J (93 + 787 = 880) Edit: other capitalisation method that capitalizes 'Mr. Mime' correctly. Can probably be shortened, I've almost never written J before. It works on a similar principle as the PHP example. You need the 'p' file in the same directory as you run this, the file can be downloaded from: <http://frankenstein.d-n-s.org.uk/p>. It is 787 bytes. ``` u:p-32*96<p*|.!.1[32=p=.(}.p#~(".1!:1[1)=+/\31=p=.#._5>\,#:a.i.1!:1<'p'){(97+i.26),a.i.'.()'' ' ``` The file is encoded in a five-bit format, as follows: ``` 0-25: A-Z 26: . 27: ( 28: ) 29: ' 30: <space> 31: separator ``` The file also starts with a separator, to make the list 1-based. The J code works as follows: * `(97+i.26),a.i.'.()'' '`: a string where the index N is the ASCII character * `{`: select from this list the values generated by the expression below * `1!:1<'p'`: read the 'p' file * `,#:a.i.`: get the file as bits * `_5>\`: group the bits in groups of five * `p=.#.`: transform each group of bits into a number and assign to `p` * `+/\31=p`: a list of the size of `p` where each value N means the value at that position in `p` belongs to the N-th pokemon. * `(".1!:1[1)=`: read a number from the keyboard and see where in `p` the characters for that pokemon are. * `}.p#~`: look them up in `p`, and remove the first item (which is the separator). * `p-32*96<p*_1|.(!.1)32=p=.`: Assign the output to `p` again, and subtract 32 from `p` where `p` is bigger than 96 and to the right of a space. Which is cumbersome. According to the J documentation there should be a `capitalize` function but it's not there on my system. * `u:`: look them up as unicode. [Answer] ## GolfScript (1040 bytes) Unfortunately I can't directly post the program, so I'll provide a [link](http://cheddarmonk.org/codegolf/pokemon.gs) and the base64-encoded text: ``` fignACc1Nix7XFsxJF0nJysvXCdCdWxiNzYKSXZ5czY0dXM2CjJtMWQvMm0tZSsyaXozZCpxdSZ0 bCVXMyRydGwlQmw3JGlzJUMjMHBpImUhcB8KQnV0dDBmcmUlHmRsJUtha3VuYQpCZWVkHWxsG3kb b3QkG290GiN0I2EaI2ljIyVTcGUzGQpGZTMZCkVrMXMYcmJvaxxpa2EXdRphaRd1KjFkc2hyZXcq MWRzbDdoFWYpFnIUYRZxdWU1FW0pFnIUbxZrExEmeRFibCVWdWxwaXgKThRlIRJzCkoQcHVmZgpX EHR1ZmYKWnViIw8OYiMKT2RkaXNoD2xvb20KVmkScGx1bSVQMzccMzdlY3Q0LCM0b21vdGgNaWcS dHQNdWd0HW8MZRl0aBwwc2kxHHN5ZHVjaw8OZHVjawwxa2V5HB1tZQslR3IZbAloGHJjMRQlUAhh ZxwIaCZsHAgHdGgYYgcGYWRhYgcYbGFrYXphbQUXb3AFF29rImEXYW1wCkItbHNwcm91dAoecBRi LWwKVmljdHJlZWItbARvDgRydS0PZR91ZCVHB3YtL0cOZW0cLHkhGgtpZDdoKmwZcG9rJVNsGWJy bwVnbmVtCSJhZ25ldCtGM2ZldBdcJ2QNH3VvDR8dbyplLQ1ld2csZw8dbS9NdWsqaC1sZC9DbG95 c3QvRzd0bHkKSGF1bnQvRzVnMwpPbml4DXIZc2UlSHlwbm8GB2JieQYTbC9WDiRyYgpFEmN0ch8D dAMkcgpDdWIsIjMZYWsKSAltLBIlSAltLBcxCkxpY2sJdW5nBm9mZhMKHnoTGmh5aAJuGmh5ZCtD aDFzZXkKVDFnLWEGMWc3a2gxCkgCc2VhKmVhZAcPDmRlNSplYWsTKnQzeXUqdDNtaSJyLiBNaW0l U2N5dGgvSnlueApFEmMhYnV6egVnbTMcFHMmClQ2b3MFZ2lrM3APeTNhZG9zCkwLB3MNCSQKRWV2 ZSVWCwJlK0oOdGUrRmwzZSwcAnlnK09tMXl0JU9tN3QzAQFwcxgwH2FjdHlsKm4CbGF4GHJ0aWN1 bm8KWgtkb3MMDnRyZXMNB3QUaQ0HZyxhJg0HZywJImV3dHdvDGV3AAZhYnUkAG9yACVFeGVnZ3UA ClQ1IWMADGEACksAcmEADml3AGl0AAoAYXAACk0ACkQAb2wACkcAaWdnbHkACkMSZmEAbGUAFGcA aW4AFnIxICgACk5pZG8AY2gACkEAb3cAClIAHGlkZ2UAClAAcmkAV2VlAG9kACAAdGEAJU0AYXQA dG8AZQoAaXIAXCcAKAApAApTACwKAG9uAGVsAC4AMAoAZXIAYW4AQ2gzAGFyAApWNQBlbgBhdXIA YXMnJwAnLz0qfS9uLz0= ``` It uses a grammar-based approach with rules separated by NUL characters and a simple expansion approach, followed by splitting on newlines and selecting the desired line. Input is via stdin. No external file is used. ### In more detail I have written a Java program which applies several grammar-generating strategies and two grammar-to-GolfScript generation strategies and outputs a lot of GS programs to reconstruct a string. In this particular case the winning combination was a greedy grammar builder with a threshold of 2, and the remap engine. The greedy grammar builder starts with a grammar ``` <0> ::= "Bulbasaur\nIvysaur\nVenusaur\n..." ``` and repeatedly looks for the repeated sequence of terminals and non-terminals in the right hand sides which, when pulled out into a rule defining a new non-terminal, produces the greatest decrease in the total number of terminals and non-terminals in the grammar. The threshold is the cutoff point at which the decrease is considered no longer worth it. The non-terminals are topologically sorted and then numbered from 0 up. If they overlap any character values which are also terminals, the remap engine creates a new rule mapping to that terminal. (E.g. if there are rules 0 to 37 and the space character occurs, it will map 38 to the space character and then update the RHS of all rules to use 38 instead of 32). The right hand sides of the rules are then concatenated, separated by NULs, and a small piece of hand-written GolfScript to expand the grammar is appended. [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 9337 bytes Pretty sure I will find a shorter solution ^^ ``` --->->>>>->>->>>-->->>>>->>>-->->>>>>->>>-->->>->>>->>>>>-->->>->>>>>>>>-->->>->>>>->>>-->->>>>>>>>-->->->>>>>>>>-->->>->>>>>>>-->->->>>>>>>-->->>>->>>>-->->>>>>>>>>>-->->>>>>>-->->->>>>->-->->>>>>>>>-->->>>>>>-->->>>>>>>>>-->->>>>>>>-->->->>>->>->-->->->>>>->>>-->->>>->>>>-->->>->>>>-->->>->>>-->->>>>>-->->>>->>>>-->->->>>>>-->->->>>>>>>>-->->->>>>>->>>-->->>>>>->>-->-->>-->-->->>>>>>>->-->->>>>>>>>>-->->>>>>->>-->-->>-->-->->>>>>>>>-->->>>>>>>>-->->>>>->>>>-->->>>>->>>>-->->>>>>>-->->>>>>->>>>-->->>>>>>>>>>-->->>>>>>>>>>-->->>>->>-->->>>>->>-->->>>>>>-->->>>>>-->->>>>>>>>>-->->->>->>-->->->>->>>>>-->->>>>>->>-->->>>>>>>>-->->>>>>>>-->->>>>>>>-->->>>>>>-->->>>>>->>-->->>>>>>>-->->>>>>>>-->->->>>>>-->->>>>>->>>-->->>>>>>>>-->->>>->>>>>-->->>>>>->>-->->>>>>>>>>-->->>>>>>->>>-->->>>->-->->->>->>>->-->->>->>->>->>-->->->>>>>-->->->>>>>>-->->->>>->>>-->->>>>>>>>>>-->->>>>>>>>>>-->->>>>>>>>>>>-->->>>>->>>>>-->->>>>->>>>>>-->->>>>>>>-->->>->>>>>>-->->>>>>-->->>>>>->-->->->>>>->>>-->->>>>>>>>-->->>>>>>>-->->->>>>>>>>-->->->>>>>>>-->->->>>>>>>-->>-->->>>>>-->->>>>>>-->->>>>-->->>>>>>>-->->>>>>>-->->>>-->->>>>>>>>-->->>>>>>>>-->->->>>>>-->->->>>>>>-->->>>>->>-->->>>>-->->>>>>>>-->->>>>>-->->>->>>>-->->>>>>>>-->->>>>>>>-->->>>>>>>>>-->->>>>>>>>-->->>>>>>>>>-->->>>>>>-->->->>>>->>-->->>>>>>>>>-->->>>>>>>>->>-->->>>>>>>>>-->->>>>>>>-->->>>>>>>-->->>>>>>>-->->>>>>>-->->>->>>>>-->->->>>>>->-->->->>>->>>>->>-->->>>>>->-->->>->>>->-->->>>>>>>-->->>->>>>>-->->>->>>>-->->>->>>>>-->->>-->-->->>>>-->->>>>>>>-->->>>>-->->>>>>->>>>>-->->->>>->>-->->>>>>>-->->->>>>>-->->->>>>->>>-->->>->>->>>>-->->->>>->>-->->>>>>-->->>>>>-->->->>>>>>>-->->>>>>>>-->->>->>>>>-->->>>>>>>-->->>->>>>>-->->>->>>->>-->->->>>>>-->->->>>>>>>-->->>>>>->>>>>-->->>>>>->>-->->>>>>>>>-->->->>>>>-->->>>>>>>-->->>->>>>>-->->>->>>>->>>-->->>->>>>>>>-->->>>>>>-->->>>+[-[>+++++++<-]<+++]>---->->->-->--->+++>->+++>->->--->>->>->+++>->->--->++>--->-->->->+++>->->--->->--->+++>->-->+++>-->--->--->->--->->--->+++>->-->--->-->--->-->-->--->->--->+++>->-->>+++>->--->--->+>->->-->->->-->--->--->++>+++>->->-->->->-->--->--->->-->+++>->->-->-->->--->--->->+++>->--->->->-->--->--->+>--->->+++>->-->--->--->->->->->--->->--->->--->--->--->++>--->--->--->-->--->--->>+++>-->->-->+++>--->->--->--->--->->-->-->-->--->+>-->--->--->--->>--->+>-->--->--->--->-->->->-->--->+>-->--->--->--->-->->--->+>+++>->->+++>->+++>--->+>+++>->-->--->+++>->--->--->+>->--->+++>->-->>--->>--->+++>->-->>--->->-->+++>-->->--->->->--->-->-->--->+>-->-->+++>--->--->->--->+>+++>-->--->--->->--->+>+++>-->--->->--->->--->>--->+>+++>-->--->->-->+++>->--->--->+>-->--->-->->+++>-->+>++>--->++>--->+>-->--->-->->-->-->+++>--->+>-->--->-->->->--->--->-->--->+>-->--->-->->+++>-->+>++>-->++>--->+>-->--->-->->-->-->-->--->+>-->--->-->-->-->-->--->--->->-->--->--->+++>-->->>--->->-->--->--->+++>--->-->--->--->++>->-->->-->>--->+>-->-->--->->+++>-->--->->--->>-->--->--->-->>->->--->--->--->++>-->--->--->-->>->->--->--->--->++>->--->+++>->--->>-->-->--->+++>->--->+>--->--->-->->--->--->>-->-->-->-->--->++>-->-->--->->-->->-->--->--->+>+++>->+++>->--->+>+++>->+++>->--->--->->--->++>--->-->-->-->+++>->--->++>--->-->-->-->-->->--->--->->-->--->-->--->->->--->->->--->->->-->-->--->+>--->-->>->--->--->+>--->->->-->+++>-->--->+>->>--->->--->-->--->>-->-->--->->--->-->--->+>+++>-->-->--->>--->+>->-->-->--->+++>->--->--->>->-->>-->-->->--->--->->->--->+++>-->-->-->--->--->+>-->-->-->>+++>--->--->+>-->-->-->>--->-->->-->--->+>-->-->-->>->+++>->--->--->->--->->+++>--->>+++>--->+++>--->->+++>--->->-->+++>-->+++>>+++>-->--->+>+++>--->--->-->->--->+>+++>--->--->-->-->--->--->+>+++>--->--->+++>-->->--->->--->-->-->->->->-->->->--->++>--->--->->-->-->--->--->-->-->--->++>-->--->->->--->--->--->--->-->-->--->++>--->-->->+++>--->-->-->-->--->++>--->-->->+++>--->->->--->-->--->>--->-->--->->--->--->--->>->+++>->--->-->--->->--->>-->-->--->-->--->+>-->-->>->+++>--->+>+++>->-->--->+++>->--->--->+>-->-->>->-->-->--->--->+>-->-->>--->->-->--->+>+++>--->-->--->-->-->->--->--->+>+++>--->-->--->->-->-->--->>+++>->--->--->->--->--->++>--->--->->-->--->->-->--->->-->--->->-->-->--->+>--->--->-->--->->--->>--->-->-->--->--->>->-->-->--->->--->+>->-->--->+>--->--->-->-->--->--->->--->->-->-->>->->--->->--->>+++>->->-->>--->>+++>->-->->--->->--->>--->-->--->+++>->--->+>-->-->>--->->->-->>->--->--->--->>>->-->-->--->>->+++>--->--->>--->>-->-->--->-->--->->--->++>-->-->->-->->--->--->->-->--->--->->->-->--->--->--->->>--->--->--->->->--->--->->>--->--->--->->->-->->--->->->--->-->-->--->--->+>+++>->-->>+++>-->--->>-->->-->-->-->-->--->--->--->>-->->-->-->-->--->--->+++>-->--->>-->--->-->-->->->-->--->--->>-->--->--->-->-->--->--->++>--->--->>-->-->--->--->+>--->>--->-->->-->--->+>--->>--->-->-->--->->--->+++>-->->--->>--->++>+++>-->--->--->-->+++>--->>+++>-->--->+++>->-->--->+++>-->--->>-->->->--->+++>--->+>--->+++>--->->+++>--->>-->-->--->--->--->-->--->+>--->+++>-->-->-->--->--->+>->+++>->>->--->+>->+++>->-->-->--->--->+>->+++>+>+>-->-->--->--->+>--->>->--->--->->--->>>-->>--->->-->--->--->->+++>--->->>>--->+>+++>--->-->+++>->--->+>-->-->->-->->--->++>+++>->->-->->--->+>+++>--->-->-->+++>->->--->>>+++>->+++>--->-->->--->>+++>->->+++>->--->->-->->->-->--->->--->->--->--->--->++>+++>->-->->--->-->-->--->>-->-->->--->-->-->--->>-->+++>->--->-->-->--->+>-->->>--->-->-->--->+>-->+++>-->>->--->--->+>-->+++>->->+++>->--->>+++>--->->->-->--->>+++>--->->->-->->->--->->--->->-->--->+++>--->->>-->--->+>-->-->->-->+++>>--->->->->-->--->->-->-->--->++>+++>->--->-->->--->+>-->-->->->--->->--->->->+++>->-->-->-->--->->->+++>--->-->-->+++>-->->--->->->+++>--->-->-->-->->--->--->+>--->>->>-->--->+>--->>+[-[>+++++++<-]<++++]>---->>++>>--->+++>>+++>++>->--->>+++>->>+++>++>->--->->>++>++>>+++>++>->--->+>+++>+++>->+>+++>++>->>->--->+>+++>+++>->+>>>>+++>++>--->+>+++>+++>->--->>+++>->->--->+++>-->++>--->->+>>>--->>+++>->+>+++>->+>>>--->>>+++>>+>+++>--->>>--->+>+++>+>>->--->--->>--->--->>+>+++>--->+++>->--->>++>+>+>>->+>->>>--->>>>->>>--->++>+++>->++>++>+++>--->>>>->->--->>>--->>--->->++>>->--->>--->->++>>+++>+>+>+++>--->>--->->++>>+++>+>--->++>+++>+>+>+++>+>+++>--->++>+++>+>--->-->+++>+>>--->+++>--->>+++>->+++>--->--->--->>+++>->+++>--->--->+++>->+++>++>>--->->->--->+++>->--->>--->->+++>-->+++>++>--->++>+++>--->-->+++>++>--->+++>+++>++>->>+++>->>--->--->+++>+++>++>->>>+++>>+++>--->-->--->->+++>->+++>++>+>++>+>+++>--->-->--->->+++>->--->++>+++>--->-->--->->+++>-->++>>>++>--->-->--->->+++>->+++>++>+>++>+>+++>--->-->--->->+++>->--->++>+++>--->-->--->->+++>->--->++>++>--->+>>>+>+++>--->->->--->+>>>+>+++>--->>>--->->++>>--->--->-->--->-->--->++>>+>+++>>>>--->+>--->++>++>>->--->++>+>+>--->>--->++>++>>->+>++>+>+>--->+++>++>--->+++>+>--->-->+++>>--->+++>+>--->->->->--->>+++>--->-->>+++>+++>+>--->->--->>>--->>++>+>>--->>+++>->+++>>--->>+++>->+++>>>-->+>--->->>++>+++>++>+++>+>--->->>++>+++>+>+++>+>+++>--->++>--->++>>>+>+>--->++>++>++>+>->--->+++>--->--->>+++>--->+>+++>--->>>->>--->+++>++>--->>>->->++>-->->--->-->+++>>->++>-->->--->--->+++>++>->>->--->>->--->+>>+++>--->>--->-->->+++>--->>--->+>+++>--->->->-->+++>++>--->++>>--->>+++>>--->--->+++>++>--->>+++>>--->--->+++>--->->>--->>+++>>--->--->->+++>+>+++>--->->--->->+++>--->++>+++>->+++>--->->+++>--->->>+++>->+++>>+++>+>--->--->+++>-->+++>+++>--->--->--->+++>-->+++>+++>->>--->--->+++>-->+++>+++>+>--->--->>>>>>--->->+++>++>+>--->>>>--->--->++>--->>>>--->->--->-->+>->>>--->>>>--->--->>++>+>+++>-->+++>+++>>--->--->>++>+>+++>-->->++>>>--->-->>+++>->++>->>--->-->->+++>+++>>>>->--->-->+++>>>+>--->>+++>++>->+>+++>--->++>+++>--->--->->+++>>+++>--->+++>>+++>--->--->+++>->>--->+++>>+++>--->--->->+++>--->--->+++>++>++>>+>--->+>>--->--->+++>++>++>>+>+++>++>--->--->+++>->+>>+>-->+++>+>->--->++>+++>->++>+++>--->++>+++>->->--->+++>--->+++>>>>--->++>>--->++>+++>++>++>--->-->->--->+>>->--->--->++>->--->+++>+++>>>>->>->--->+>>+++>->>+>>->--->-->+++>>+>>->--->->+++>++>++>+>>->--->-->>++>++>+++>->--->->++>--->-->--->++>->+++>--->>>>--->->->--->++>+++>--->++>->+++>--->--->->--->++>--->++>++>>>->--->->+++>>+>+++>->--->--->+++>>>-->+>->+++>->>--->+++>-->>++>++>++>+>>--->+++>-->>++>++>++>+>+++>->--->+>++>--->+++>++>>--->--->+++>->+++>--->+++>->--->->--->+>+>+++>++>>>>--->->--->+>+>+++>++>-->+++>+++>++>--->+++>--->-->->--->+>++>++>++>--->++>+++>+>+>--->++>++>--->>>>>--->++>++>--->++>+++>->+++>+++>->++>--->++>+++>->->+++>++>--->+>+++>+++>++>>>->--->--->+++>++>++>>>+++>--->++>+++>++>++>+++>>->+++>+++>++>--->->+++>->>>+++>--->+++>>+++>->->+++>--->-->+++>>->>>++>--->+++>>+++>->--->++>++>--->+++>+>+++>->->++>--->+++>+>+++>->+>--->>--->--->->+>+>--->--->+>>--->+++>-->->+>+++>>->--->+>->++>-->--->+++>>>-->+>+++>--->++>>>--->--->+++>++>+>+++>->--->>--->++>>--->->--->--->+++>++>->+++>>--->--->+++>++>--->->+++>->--->--->-->->+++>->+++>->+++>>--->+++>+++>--->->+++>>--->++>--->+>+>+++>--->+++>>+++>>>--->->+++>--->+++>->>+++>++>--->+>+++>>+>>+++>++>--->--->>+++>->>+++>++>--->>+++>->->++>+++>++>--->->+>+++>++>->+>>--->->+>+++>>+>+++>->--->++>+++>--->++>+>+++>--->++>+++>--->++>+>+++>--->>--->->>->+++>->+++>-->+>->>--->+++>++>+++>->>+++>-->--->->->+>--->-->++>++>+++>--->+++>+++>--->->+++>>--->--->+++>>+>->>>--->++>->+++>+>--->++>--->--->++>->+++>++>+++>++>+++>--->->--->++>->+++>++>+++>++>--->+>>--->--->>--->+>--->+++>--->--->>--->+[-<++++]<<<,[>[>+<-]>[<++++++++++>-]<<<++++++++[>------<-]>[>+<-],]>-[>>[>]+[<]<-]>>[>]>[.>] ``` [Try it online!](https://tio.run/##tVnLjhw3DPwgmTkEyG1QPzKYQxLAgGHABwP5/s1MT0usKlK9ziELY7db1IOPYpFq//Xzz28/vv7z9/ePj4hA4PkTxz/Q63qmlzjf@N1fZel87ia67FwUsA34LRdEPQRlZUQ9KtZaVzfcknC31Jmxs9Fdd558HH3@WaptlN7Nb59j@2KR3PpW7WNgNBsVhSOnBnxWYKd/@7hZ10WzhWnF01YVPpXXsCGRSFArLfIMsV/xchtCe6v2b0OxQfWF69oMpJcu3ku9i8BdYnXjN0Nds3vJzAss7XXYkMnF4k845VMcRyUFQYqcEMK0m@C3HLWe48qLSgXKio1jWkiFE2CLlI7be40v7NsnW2vJjmt@8TSrdC22xz3uGO@fWzxuzz@Pp@w85nB@vOSYv98j7z155PUYCwos4T3mwymJzZy50/zTzVlP5/hSmLc49EplXJgKYZ1EQjrBNrUJvKHZTTL2ktk4zWGVyuJ0xlJC5P2ohbIXH5LpCAo3j6v/yesSlVREhiT05NLGoLTedYvLYfrdS6vu5IJz7pghWtarn1g/k3lUr/a/2r5bLnkQBeJjkWUr8oTI48TvwYqKM9k0tJj@dIaBhw1NcUWlzIWdSPZqdgphtSNMKOplWjWq/7sIKJydMcQyoJKIs@LgSK4dChFGyQEhgdbBMTVAZ4@AqfDdbN45O3lcUWyy1vMJz0ypMUzE3nn9UU8JVTgtlAJSZE5IHGdIXhslwUncM8Gpu84TXugA7hMKHgogVoDZ2yWTG47Cf@D7hHGHEM2NUQlIUVcnMJRb0LTBuHhomEXrhNXhpuXAbp@mi1ECFDuyPg4m4aqMcyI71kjkWKhe0wK6CbwT6Zbcas9EpaZDeyfalnwDHCd3KYne66AR@XpNaC8prTaj1h2OfctzFUmVXqQbldONBWsrXL0iZLmjzsZtovOO6s/D4QP9xKH9A3nEsgOVH5zqUUmhZgIzvTf3lVL02mK9bU1RafkVNn0776lcCnYzbPRM1qEbPePkNFxVtlrRj6FhLIlBNO4@Km9IYXSGHWaWb6KnGqR0WGNXVvUN2ciLqQw0N9x5xcW0ajUW5kobfK8oc8f5eiArRa0UudZkVimo6ZlpAqkevGdim@DPyTQAuye@d9LGa26Pc8FYKbk@JlCg32bkaeBEX5k@1tE0MHmDmEpFdNBYJqSuNCtiGVio1PrAdjhHBOJ@WeEr3OBLolEVuTOBMPmUjkwhd7V@DZvT1q92UtXE9D0O@X@2T@mJNgZVskDFZaS/a1e6cAxIvSI0rcrDlRVnXmCA45CPHCofRRQaXQRAkxLgCTtyZ3kHXfWQkec9CeoO9FgBFCe8F9sVn@9R7G24K3ByqdSncbpvGK0anWVINXmt8YgCA8ub1Lcc1Qqot1RhmNO8qxjDs573o0AxQCzZh1V9FWEnocAAzCJLBnjjCbv7KweHcLSe1ktP@DCcA6w1aAcYHEDR4KLjjBAIpTHjtGBHFVkl5FllJ9RaGcGFiBzZHDl5sc7SOYbqDcEop6w3N9h841rOtGwBr5n1WhA7wZGzuM4mcypbhpRh/WzBZNJ9WhVuhUbTb//EZx5R1lSrsYzrNzkOalOR7fvDXLZWoB@3EhtNvz8gIaVWQ@sZuOmpdJLZpJBqWzz2r2K5dDYr4iimLMc3uaYN8rkeaOaZSUO@/pfBoW1jQIgSetddiuclERU/g2ubu8RbL@rMvCrtCkj54mj/sWEdgKzS7/@jOhqlxMhdYRmIAWepZi57Xi1g3pUxTSRltY6hR9Ns23/0YFijQIry/SzRpQe0Tkyv8fUhtMkP5zFtkpSqbILVh@5zyBq@x/vud7vdvtzxvBM@b4O438b6Qbxk8@1@3BEjjlnH5C/Pa@Mdz5fHuN8er/HXM@6/4fHx8fsf/wI "brainfuck – Try It Online") [Answer] # [q/kdb](http://kx.com/download/), 789+77 = 866 bytes **Solution:** ``` / encoding pokemon.txt into 'q' text file (not added to byte count, not golfed) `:q 0:enlist "c"$2 sv'8 cut (raze 3_'0b vs'4h$(asc distinct p)?p:lower first read0`:pokemon.txt),000000b / checking length of q file (note: file is written with trailing newline \r\n, so could/should be 787 bytes) hcount `:q 789 / decoding q and look-up of value @[;0;upper](";"vs(" '().;",.Q.a)2 sv'5 cut -6_(,/)0b vs'4h$"\n"sv(0:)`:q)@-1+ ``` **Examples:** ``` q)@[;0;upper](";"vs(" '().;",.Q.a)2 sv'5 cut -6_(,/)0b vs'4h$"\n"sv(0:)`:q)@-1+45 "Vileplume" q)@[;0;upper](";"vs(" '().;",.Q.a)2 sv'5 cut -6_(,/)0b vs'4h$"\n"sv(0:)`:q)@-1+151 "Mew" q)@[;0;upper](";"vs(" '().;",.Q.a)2 sv'5 cut -6_(,/)0b vs'4h$"\n"sv(0:)`:q)@-1+1 "Bulbasaur" ``` **Explanation:** The strategy (like other solutions) is to encode each 8 bit character in 5 bits, this is done by creating a smaller alphabet of 32 characters, finding the indices of each letter in the input list (0..31) and then encoding these as 5-bit numbers (which need to be joined and converted to 8-bit chars to be written down in Q). The decoding is just doing the opposite of this, the alphabet is known to be `" '().;abcdefghijklmnopqrstuvwxyz"`, so split the input into batches of 5 bits and convert back into integers, index into the alphabet. Split this on `;` and then index into it with user input (subtract 1 due to 0-indexing), and (re)capitalise the first letter. ``` @[;0;upper] (";" vs " '().;abcdefghijklmnopqrstuvwxyz"2 sv'5 cut -6_raze 0b vs'4h$ "\n" sv read0 `:q)@-1+ / ungolfed decoder -1+ / same as doing 'x-1', subtract 1 from input @ / index in to item on the left ( ) / do all this together read0 `:q / read text file 'q' "\n" sv / join back newlines (as q breaks text files on newlines) 4h$ / cast char array to bytes 0b vs' / convert each byte to binary (boolean list) raze / flatten list -6_ / drop the 6 padding bits added to align 5/8-bits 5 cut / chop into lists of 5-bit lengths 2 sv' / convert each boolean list back to an integer " '().;abcdefghijklmnopqrstuvwxyz" / index into our lookup table at each index ";" vs / break this string up at semicolons @[;0;upper] / apply 'upper' to each first character in the result ``` **Notes:** An extra 13 bytes (879) if we need to capitalise the second `M` of `Mr. Mime`: ``` {@[x;0,1+x ss" ";upper]}(";"vs(" '().;",.Q.a)2 sv'5 cut -6_(,/)0b vs'4h$"\n"sv(0:)`:q)@-1+ ``` [Answer] # Pure [Bash](https://www.gnu.org/software/bash/) (no coreutils), 1173 bytes ``` read n;set {Bulba,Ivy,Venu}saur Char{mander,meleon,izard} {Squi,Warto}rtle Blastoise Caterpie Metapod Butterfree Weedle Kakuna Beedrill Pidge{y,otto,ot} Rat{tata,icate} {Sp,F}earow Ekans Arbok {Pika,Rai}chu Sands{hrew,lash} Nido{ran\ \(f\),rina,queen,ran\ \(m\),rino,king} Clefa{iry,ble} Vulpix Ninetales {Jigglyp,Wigglyt}uff {Zu,Gol}bat Oddish Gloom Vileplume Paras{,ect} Veno{nat,moth} Diglett Dugtrio Meowth Persian {Psy,Gol}duck Mankey Primeape Growlith Arcanine Poliw{ag,hirl,rath} {A,Kada}bra Alakazam Mach{op,oke,amp} Bellsprout {Weepin,Victree}bell Tentac{ool,ruel} Geodude Graveler Golem Ponyta Rapidash Slow{poke,bro} Magne{mite,ton} Farfetch\'d Dod{uo,rio} Seel Dewgong Grimer Muk {Shelld,Cloyst}er Gastly Haunter Gengar Onix Drowsee Hypno Krabby Kingler Voltorb Electrode Exeggut{e,or} Cubone Marowak Hitmon{lee,chan} Lickitung {Koff,Weez}ing Rhy{horn,don} Chansey Tangela Kangaskhan Horsea Seadra Goldeen Seaking Star{yu,mie} Mr.\ Mime Scyther Jynx Electabuzz Magmar Pinsir Tauros Magikarp Gyarados Lapras Ditto Eevee {Vapore,Jolte,Flare,Poryg}on Oma{nyte,star} Kabuto{,ps} Aerodactyl Snorlax Articuno Zapdos Moltres Dra{tini,gon{air,ite}} Mew{two,};echo ${!n} ``` [Try it online!](https://tio.run/##LVPbbuM2EH3fr5gCBdoCRLdJ0Yc2QIEkzqXJujHihQMs8jISxxJhiqOlyDgKwW9Pj3b7IMscETPnNg1P/fuxd17orzOy@h6FLYWzSRKVi@wbNv@8zGYnIdeJc6TLnmMZOFiJZhAvGox742grle3X7MwTx6Q1JjS88DwldZPQJSeJoxNaS@JRLV3khMo@itCTiMXlez7kwHSBU3Te08bZTspsNCXFT6VHTiVxYuNadFvGjea6Ckc90tWBw0TnsdEDlY07sHlkV9s@0xZIp9JHORqg6Sv966yWyOGZnn/eP/9iogtsvmaRYP6vDt@rag4udJUuvey5uDibxmPsLvvRvaJNABUvE5U713V@Hs3Tt3eqeb@n8iWbG/W14UQP1rqppxuvOtAOSo8@D0IbjjwVIy24QV4tgZMZNAHjynVeUqJV7lJ0CtX0mHraSJwcBzCc5m/dbW4PtOZwkJk20Q3Co9ANBPEO189jywEwaaPeHQt3pnfRg@Uyopybe7Zcm8h07vnAbzygVdsXHY0exPAwVrjh/TRGzQgDfBpdMDvXJthWG3yizxISt0UVbbP4SjeiNtsFBL8gHJEAUwYgCHNiWDg6Cxdo6/VYxmVME7VibhekDC6JSRoqXXPcS2r7558srdSWrDAE97YinlZy7DR0GAHCkdYZlm97oLHm0us8pbqMRfL8TLecQ1qOEjqO9BDg3Ar6TMjd7TwGpfvITTPTPaxe4O7UJ40NXXn4EhVMrl6l63IqYjQiDLlRKLpeUscHunVp0FC8iGl7BvJPrj24lAGv3Ot@byDaW0Vveuzn0msMxi4EsURhgmmfOXTiGeEHvumAKt1qnIRBlS2sgXwW0VyOSxppm7B9czaDQxTX8ddnWkMF2rZz6gH/bg6v37Fzk9/eFmEH8N64MLmIaTnqtBSxIXGkmxkRtKh84hFZROywa3QlL1Cn7LCnUcwdBBFz7Rn/Nxrnrmqgh4ELDBUzAU4F@iYnLWacKp0LVOM2zZ62QaPnV@QwuTZD6y88LtPWaBmxOKvIJbngDOws7KKB/xWs5FjSUU09k7ZX@rH8EOq7XVQ//Zs@Wnn5GLL37ycfTv/88Pvph5NTPH/8hufkPw "Bash – Try It Online") Uses brace expansion like [this answer](https://codegolf.stackexchange.com/a/9042/58834), but uses only bash builtins `read`, `set`, and `echo`. `set` sets the command line arguments to those given, so that, for instance, `$1` is `Bulbasaur`. `${!n}` is an indirect expansion, which expands into the variable of the variable with the name of `$n`. [Answer] # Python 3, 178+1253=1431 bytes ``` import re def f(l,N,p='',n=0,w=''): for s in open(l,'r',1,'utf-8').read().split('\0'):t=re.match('\d*',s)[0];n=int(t or n);w=w[:n]+s[len(t):];p+=w[:-1]*(ord(w[-1])==N) return p ``` Credit to [wizzwizz4](https://codegolf.stackexchange.com/users/43394/wizzwizz4) for their Bookworm decompression function: [Parse the Bookworm dictionary format](https://codegolf.stackexchange.com/a/177806/73368) Must pass the filename and the desired Pokemon number to the function. Returns a string containing the Pokemon. Ex.: `f('pokemans', 1')` returns 'Bulbasaur'. The file uses BookWorm compression, but since the Pokemon must be in alphabetical order for this to work, they all end with a character whose ordinal matches their number (Ex. Nidorino appears as "7o!", "7o" being the compressed string "Nidorino" and "!" being \33). Items are delineated by the null byte \0, since Pokemon chars start at \1. Due to the complexity of decompressing BookWorm, this is actually worse than taking the basic hard-coded list, then splitting and indexing it. But it's a novel answer, so I thought I'd post it anyway. **Hex dump of 'pokemans' file:** > > 41 62 72 61 3f 00 31 65 72 6f 64 61 63 74 79 6c > c2 8e 00 6c 61 6b 61 7a 61 6d 41 00 72 62 6f 6b > 18 00 32 63 61 6e 69 6e 65 3b 00 74 69 63 75 6e > 6f c2 90 00 30 42 65 65 64 72 69 6c 6c 0f 00 32 > 6c 6c 73 70 72 6f 75 74 45 00 31 6c 61 73 74 6f > 69 73 65 09 00 75 6c 62 61 73 61 75 72 01 00 32 > 74 74 65 72 66 72 65 65 0c 00 30 43 61 74 65 72 > 70 69 65 0a 00 31 68 61 6e 73 65 79 71 00 33 72 > 69 7a 61 72 64 06 00 34 6d 61 6e 64 65 72 04 00 > 35 65 6c 65 6f 6e 05 00 31 6c 65 66 61 62 6c 65 > 24 00 35 69 72 79 23 00 32 6f 79 73 74 65 72 5b > 00 31 75 62 6f 6e 65 68 00 30 44 65 77 67 6f 6e > 67 57 00 44 69 67 6c 65 74 74 32 00 32 74 74 6f > c2 84 00 30 44 6f 64 72 69 6f 55 00 33 75 6f 54 > 00 31 72 61 67 6f 6e 61 69 72 c2 94 00 36 69 74 > 65 c2 95 00 33 74 69 6e 69 c2 93 00 32 6f 77 73 > 65 65 60 00 31 75 67 74 72 69 6f 33 00 30 45 65 > 76 65 65 c2 85 00 31 6b 61 6e 73 17 00 6c 65 63 > 74 61 62 75 7a 7a 7d 00 35 72 6f 64 65 65 00 31 > 78 65 67 67 75 74 65 66 00 37 6f 72 67 00 30 46 > 61 72 66 65 74 63 68 27 64 53 00 31 65 61 72 6f > 77 16 00 6c 61 72 65 6f 6e c2 88 00 30 47 61 73 > 74 6c 79 5c 00 31 65 6e 67 61 72 5e 00 32 6f 64 > 75 64 65 4a 00 31 6c 6f 6f 6d 2c 00 6f 6c 62 61 > 74 2a 00 33 64 65 65 6e 76 00 34 75 63 6b 37 00 > 33 65 6d 4c 00 31 72 61 76 65 6c 65 72 4b 00 32 > 69 6d 65 72 58 00 32 6f 77 6c 69 74 68 3a 00 31 > 79 61 72 61 64 6f 73 c2 82 00 30 48 61 75 6e 74 > 65 72 5d 00 31 69 74 6d 6f 6e 63 68 61 6e 6b 00 > 36 6c 65 65 6a 00 31 6f 72 73 65 61 74 00 79 70 > 6e 6f 61 00 30 49 76 79 73 61 75 72 02 00 4a 69 > 67 67 6c 79 70 75 66 66 27 00 31 6f 6c 74 65 6f > 6e c2 87 00 79 6e 78 7c 00 30 4b 61 62 75 74 6f > c2 8c 00 36 70 73 c2 8d 00 32 64 61 62 72 61 40 > 00 32 6b 75 6e 61 0e 00 32 6e 67 61 73 6b 68 61 > 6e 73 00 31 69 6e 67 6c 65 72 63 00 6f 66 66 69 > 6e 67 6d 00 72 61 62 62 79 62 00 30 4c 61 70 72 > 61 73 c2 83 00 4c 69 63 6b 69 74 75 6e 67 6c 00 > 4d 61 63 68 61 6d 70 44 00 34 6f 6b 65 43 00 35 > 70 42 00 32 67 69 6b 61 72 70 c2 81 00 33 6d 61 > 72 7e 00 6e 65 6d 69 74 65 51 00 35 74 6f 6e 52 > 00 32 6e 6b 65 79 38 00 72 6f 77 61 6b 69 00 31 > 65 6f 77 74 68 34 00 32 74 61 70 6f 64 0b 00 77 > c2 97 00 33 74 77 6f c2 96 00 31 6f 6c 74 72 65 > 73 c2 92 00 72 2e 20 4d 69 6d 65 7a 00 75 6b 59 > 00 30 4e 69 64 6f 6b 69 6e 67 22 00 34 71 75 65 > 65 6e 1f 00 72 61 6e 20 28 66 29 1d 00 39 6d 29 > 20 00 35 69 6e 61 1e 00 37 6f 21 00 32 6e 65 74 > 61 6c 65 73 26 00 30 4f 64 64 69 73 68 2b 00 31 > 6d 61 6e 79 74 65 c2 8a 00 33 73 74 61 72 c2 8b > 00 31 6e 69 78 5f 00 30 50 61 72 61 73 2e 00 35 > 65 63 74 2f 00 31 65 72 73 69 61 6e 35 00 69 64 > 67 65 6f 74 12 00 35 6f 74 74 6f 11 00 79 10 00 > 32 6b 61 63 68 75 19 00 6e 73 69 72 7f 00 31 6f > 6c 69 77 61 67 3c 00 35 68 69 72 6c 3d 00 72 61 > 74 68 3e 00 32 6e 79 74 61 4d 00 72 79 67 6f 6e > c2 89 00 31 72 69 6d 65 61 70 65 39 00 73 79 64 > 75 63 6b 36 00 30 52 61 69 63 68 75 1a 00 32 70 > 69 64 61 73 68 4e 00 74 69 63 61 74 65 14 00 33 > 74 61 74 61 13 00 31 68 79 64 6f 6e 70 00 33 68 > 6f 72 6e 6f 00 30 53 61 6e 64 73 68 72 65 77 1b > 00 35 6c 61 73 68 1c 00 31 63 79 74 68 65 72 7b > 00 65 61 64 72 61 75 00 33 6b 69 6e 67 77 00 32 > 65 6c 56 00 31 68 65 6c 6c 64 65 72 5a 00 6c 6f > 77 62 72 6f 50 00 34 70 6f 6b 65 4f 00 31 6e 6f > 72 6c 61 78 c2 8f 00 70 65 61 72 6f 77 15 00 71 > 75 69 72 74 6c 65 07 00 74 61 72 6d 69 65 79 00 > 34 79 75 78 00 30 54 61 6e 67 65 6c 61 72 00 32 > 75 72 6f 73 c2 80 00 31 65 6e 74 61 63 6f 6f 6c > 48 00 36 72 75 65 6c 49 00 30 56 61 70 6f 72 65 > 6f 6e c2 86 00 31 65 6e 6f 6d 6f 74 68 31 00 34 > 6e 61 74 30 00 33 75 73 61 75 72 03 00 31 69 63 > 74 72 65 65 62 65 6c 6c 47 00 32 6c 65 70 6c 75 > 6d 65 2d 00 31 6f 6c 74 6f 72 62 64 00 75 6c 70 > 69 78 25 00 30 57 61 72 74 6f 72 74 6c 65 08 00 > 31 65 65 64 6c 65 0d 00 33 70 69 6e 62 65 6c 6c > 46 00 7a 69 6e 67 6e 00 31 69 67 67 6c 79 74 75 > 66 66 28 00 30 5a 61 70 64 6f 73 c2 91 00 31 75 > 62 61 74 29 00 > > > [Answer] # JavaScript, ~~1277~~ 1276 bytes ``` n=>";Bulbasaur;Ivysaur;Venusaur;Charmander;Charmeleon;Charizard;Squirtle;Wartortle;Blastoise;Caterpie;Metapod;Butterfree;Weedle;Kakuna;Beedrill;Pidgey;Pidgeotto;Pidgeot;Rattata;Raticate;Spearow;Fearow;Ekans;Arbok;Pikachu;Raichu;Sandshrew;Sandslash;Nidoran (f);Nidorina;Nidoqueen;Nidoran (m);Nidorino;Nidoking;Clefairy;Clefable;Vulpix;Ninetales;Jigglypuff;Wigglytuff;Zubat;Golbat;Oddish;Gloom;Vileplume;Paras;Parasect;Venonat;Venomoth;Diglett;Dugtrio;Meowth;Persian;Psyduck;Golduck;Mankey;Primeape;Growlith;Arcanine;Poliwag;Poliwhirl;Poliwrath;Abra;Kadabra;Alakazam;Machop;Machoke;Machamp;Bellsprout;Weepinbell;Victreebell;Tentacool;Tentacruel;Geodude;Graveler;Golem;Ponyta;Rapidash;Slowpoke;Slowbro;Magnemite;Magneton;Farfetch'd;Doduo;Dodrio;Seel;Dewgong;Grimer;Muk;Shellder;Cloyster;Gastly;Haunter;Gengar;Onix;Drowsee;Hypno;Krabby;Kingler;Voltorb;Electrode;Exeggute;Exeggutor;Cubone;Marowak;Hitmonlee;Hitmonchan;Lickitung;Koffing;Weezing;Rhyhorn;Rhydon;Chansey;Tangela;Kangaskhan;Horsea;Seadra;Goldeen;Seaking;Staryu;Starmie;Mr. Mime;Scyther;Jynx;Electabuzz;Magmar;Pinsir;Tauros;Magikarp;Gyarados;Lapras;Ditto;Eevee;Vaporeon;Jolteon;Flareon;Porygon;Omanyte;Omastar;Kabuto;Kabutops;Aerodactyl;Snorlax;Articuno;Zapdos;Moltres;Dratini;Dragonair;Dragonite;Mewtwo;Mew".split`;`[n] ``` [Try it online!](https://tio.run/##RVTRbtw2EPyVIC@1H2qg7eMiBWyffa6dqw@54AKkCJCVtCexorjKkvRZ9/POUHKSF82Qopa7s7P6n5841ubG9HvQRl743Ut49/dbusq@4sjZ6J@naca9hDyT645t4NDIKxUvGmbqTmwN7b5lZ8kLfWJLOrMrzzGpi0LXnMRGJ7SRxKM2uChh52CC8yINDj9wnwPTFVbmvKeta1qZFtCU9AejD5wSJy7oasSl3ShseqTbBW56DpEurdIe3/RcdxlnXYEd8o@dyXFhSK@jf12jxuHN2eF84Q5ZFPIti4Rfr4efr3UmvQstXXs5sLNpIRXK2Gc/umecCKjUS6R717Z@GvPhQJ9mmgr9nCtOtFZf4LFpHDJZe9WB9s7L6PMgtGXjuDylTqUTGnjBQVNHK9d6SYlWuU3mFNrqEdtbseg40DZOTa77csmMGw59EdTcIDwKrSGWd/jg0moOyJe26t2R2wU7Z35hxuVQZYweNVzw0nPPJx4Qs@50XKCXGXkY0UTv42iaU@nu6EKFDVRWJzR85h8lJK5VfzDL4mkt2uSmZMZPsJeV1GVAEmGa@z26pnRs5/U4lusKqQyFcxtkcEkWluDLW7aDpLr7raEVgmp5Fo12gntWcmwV3VsXKYw2uaddh6xmb3udYip3w7t@ojvOYV5KaNnoMaC5KygX4dy7aYQZHoyraqIH@KHkvFcP@1d049E0w3DRzbO0bU4/ieKWXGko6SIS93Tn0qDBl5Azg4qB3ru6dykjzwc9HIrboOWp4Idu6tRCwWaZwRDR2Y8cWvGlS0g19iXGnVoURtXcoG3FCcXTWM7u3SW2Kc8wlNm0izcbKEK7ekodSrmfwvNSB1f5dCrqDtBg60J0huuyaSybGDIbaT3BqQ123vNYjLtyZWpv5All7TH0Vv4X91Cn4K3neb1Vm9ALesSvZYJEwIh0UEMFoV5hxDgLpOQ6TZ52Qc3zM2yL@c9owGcey7UbhDYM3Ap@dcEVRGRM5yub/SHHdCyTcnx7EUe4/yt9/S98eaFaQ4TZLry2Z3z2x19/np/Ty3c "JavaScript – Try It Online") Node.Js because there's no plain JS ]
[Question] [ A cannonball is fired so that in the first eyeblink of its flight it ascends by `N` treetops, during the second eyeblink by `N-1` treetops, etc until it reaches the highest point of its trajectory. Then it starts falling by 1, 2, etc treetops per eyeblink until it hits the ground. At the same time the cannonball is moving horizontally with a constant velocity of 1 treetop/eyeblink. Your task is to draw the trajectory with consecutive letters from the English alphabet. If you run out of letters, start again from `'A'`. Write a function or a program. The input is an integer `N` (`1≤N≤15`). The output can be a character matrix in any reasonable form, for instance a newline-separated string or a list of strings. Letters can be all lowercase or all uppercase. Extra leading and trailing spaces are allowed. Standard loopholes are forbidden. Shorter code is better. ``` in: 5 out: OP N Q M R L S K T J U I V H W G X F Y E Z D A C B B C A D in: 1 out: AB ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~33~~ ~~32~~ ~~29~~ 28 bytes ``` >*As∍2ä`R)ζRIL£vyε`N·úJ])˜.c ``` [Try it online!](https://tio.run/##ATAAz/8wNWFiMWX//z4qQXPiiI0yw6RgUinOtlJJTMKjdnnOtWBOwrfDukpdKcucLmP//zU "05AB1E – Try It Online") **Explanation** ``` >* # push input*(input+1) As∍ # take that many characters from the alphabet (with wrap) 2ä # split in 2 parts `R) # reverse the second part ζ # zip (gives a list of pairs) R # reverse IL£ # split into parts of sizes equal to [1,2...] vy # for each (part y, index N) ε # for each pair in that part `N·úJ # insert N*2 spaces between the characters ] # end loops )˜ # wrap in a flattened list .c # format as lines padded to equal length ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 29 24 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ╦'♫ΓqπL⌂δ@╚n>DI∙Q┴òkεwö╔ ``` [Run and debug it online](https://staxlang.xyz/#c=%E2%95%A6%27%E2%99%AB%CE%93q%CF%80L%E2%8C%82%CE%B4%40%E2%95%9An%3EDI%E2%88%99Q%E2%94%B4%C3%B2k%CE%B5w%C3%B6%E2%95%94&i=5%0A1%0A8&a=1&m=2) The corresponding ascii representation of the same program is this. ``` VA*xRr:m|/xH({rix/|1*_%:T)mMm VA* repeat alphabet input times xRr:m [x ... 1, 1 ... x] where x=input |/xH( get consecutive substrings of specified sizes { m map substrings using block ix<|1* reverse string if index<x _%:T) left-pad to appropriate triangular number Mm transpose and output ``` [Answer] # R, ~~169~~ ~~163~~ ~~161~~ ~~153~~ ~~150~~ ~~110~~ 109 bytes This approach fills in a matrix and then prints the matrix. **Golfed** ``` function(n)write(`[<-`(matrix(" ",M<-2*n,k<-sum(1:n)),cbind(rep(1:M,c(n:1,1:n)),c(k:1,1:k)),LETTERS),1,M,,"") ``` Thanks @Giuseppe for 153. Thanks @JDL for 150. See @Giuseppe's comment for 112, and some edits for 110 now 109. Rip original code. ``` function(n){a=matrix(" ",M<-2*n,k<-sum(1:n)) Map(function(x,y,z)a[x,y]<<-z,rep(1:M,c(n:1,1:n)),c(k:1,1:k),head(LETTERS,2*k)) cat(rbind(a," "),sep="")} ``` If plotting a valid output then 73 bytes ``` function(n,k=sum(1:n))plot(rep(1:(2*n),c(n:1,1:n)),c(1:k,k:1),pc=LETTERS) ``` [![enter image description here](https://i.stack.imgur.com/BLY8f.png)](https://i.stack.imgur.com/BLY8f.png) [Answer] # [Python 2](https://docs.python.org/2/), ~~140~~ ~~135~~ 133 bytes ``` lambda n:[' '*(n-j)+chr(~-i%26+65)+' '*j+chr((n*-~n-i)%26+65)for i,j in zip(range(n*-~n/2,0,-1),sum([-~i*[i]for i in range(n)],[]))] ``` [Try it online!](https://tio.run/##XcpNDoIwEEDhvaeYjWmHtiokEoPxJKUL/EGmkYFUXOiCq1dFVm7f@/rn0HScxfpQxlvVHs8VcGEFiESy8ahOTZCjoWWWq3yLSsDn@KlKTszIhnB@dReAtAdieFEvQ8XXy8@sM73RJkV9f7TSmpESS27iXzxDdNo6RBf/Rqp3WCygD8QDiJLFynfEspaEuJ9qfAM "Python 2 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 29 bytes ``` ,G:tPY"tf1Y2y@?tn+P])Z?]Pv1X! ``` [Try it online!](https://tio.run/##y00syfn/X8fdqiQgUqkkzTDSqNLBviRPOyBWM8o@NqDMMELx/39TAA "MATL – Try It Online") ### How it works ``` , % Do twice G: % Push [1 2 ... n], where n is the input tP % Duplicate, flip: pushes [n n-1 ... 1] Y" % Run-length decoding: gives vector with n ones, n-1 twos ... (*) tf % Duplicate, find: gives [1 2 3 ... n*(n-1)/2] (**) 1Y2 % Push string 'ABC...Z' y % Duplicate from below: pushes [1 2 3 ... n*(n-1)/2] again @? % If we are in the second iteration tn % Duplicate, length: pushes n*(n-1)/2 + % Add: gives [n*(n-1)/2+1 n*(n-1)/2+2 ... n*(n-1)*2] P % Flip: gives [n*(n-1)/2 n*(n-1)/2-1 ... n*(n-1)/2+1] ] % End if ) % Index (1-based, modular) into the string. Gives a substring % with the letters of one half of the parabola (***) Z? % Sparse: creates a char matrix with the substring (***) written % at specified row (*) and column (**) positions. The remaining % positions contain char(0), which will be displayed as space ] % End do twice. We now have the two halves of the parabola, but % oriented horizontally instead of vertically P % Flip the second half of the parabola vertically, so that the % vertex matches in the two halves v % Concatenate the two halves vertically 1X! % Rotate 90 degrees, so that the parabola is oriented vertically. % Implicitly display ``` [Answer] # C, 184 bytes ``` i,j,k,l,m,h,o;f(n){char L[o=n*n][n*3];for(i=o;i--;)for(L[i][j=n*2]=h=k=0;j--;)L[i][j]=32;for(m=n;!h|~i;m-=1-h*2)for(h+(l=m)?++j:++h;l--;)L[h?i--:++i][j]=65+k++%26;for(;o--;)puts(L+o);} ``` [Try it online!](https://tio.run/##JY5LDoIwEIb3nKIuTFqmTRQjC8eJF@AGpAtDoi3QqfGx8nF1LGV28/2P/J25dt00ed3rQY86aKcjXiSrd@fOd9G0kbhk23K5s3iJd@kpojcG1fw0rbdtnxyVJUcDbbCfpQVb2lU5Eohx5T4/j8HQ1riyymEHcqSgTgD9AcDhuETdKdUnsFTUexgA1lWdmzDOntvr@ZANRIXfyfNThLNnqYp3IdIlm5Az5bRG8HGPKvOsSQBWWHynPw) **Unrolled:** ``` i, j, k, l, m, h, o; f(n) { char L[o=n*n][n*3]; for (i=o; i--;) for (L[i][j=n*2]=h=k=0; j--;) L[i][j] = 32; for (m=n; !h|~i; m-=1-h*2) for (h+(l=m)?++j:++h; l--;) L[h?i--:++i][j] = 65 + k++%26; for (; o--;) puts(L+o); } ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 121 bytes ``` n->{for(int l=n*++n/2,r=l,i=1,j=0;l>0;j=j-->0?j:i++)System.out.printf("%"+(n-i)+"c%"+(2*i-1)+"c%n",--l%26+65,r++%26+65);} ``` [Try it online!](https://tio.run/##bY8xb4MwEIX3/IoTEhLEmCZIyQAiHTp16JQxyuAaEp1rzsiYVBXit1OTpKrUZjjd83un@85KXAQ3bU2q@piwaY11oLyX9g51uiwW/7xTT9KhoTmUWnQdvAmkYQHQ9u8aJXROON8uBitofBTtnUU6H44g7LmLYR4FeCX3Yqjrm9qCFESGoJyI74aTsRGSA13SkjF6yhJb6gTLdaLKVaF3q0KVivPd6lnlyFi8/@pc3aSmd2nrOe4UBWHAIuIYs0DOMlsiX18fFCSc6zDbsu0msYzdVFyMU3E9yrPhCqccqP4ELw/HYZPAevy5G@ABECkPKaxC8mY@U4Di4j5@@1wqpKxbF/36f9doiu7ZuJhrnL4B "Java (OpenJDK 8) – Try It Online") ## Explanation ``` n->{ // int-accepting consumer for( // loop int l=n*++n/2, // declare l (left) is the first character to print. // Oh, and n is increased to reduce byte count later. r=l, // r (right) is the second character to print. i=1, // i is the "outer-loop" index j=0; // j is the "inner-loop" index l>0; // while there are characters to print j=j-->0?j:i++) // simulate two loops in one, // where j starts from 0 and always decreases until it reaches 0 // at which point j is reset to i and i is increased System.out.printf( // Print... "%"+(n-i)+"c%"+(2*i-1)+"c%n", // 2 characters // - the first with n-i-1 whitespaces (remember, n was increased) // - the second characters with 2*i-2 whitespaces --l%26+65, // the first character to print is the left one, we decrease it. r++%26+65 // the second character to print is the right one, we increase it. ); // // end loop } // end consumer ``` [Answer] # Clojure, 417 319 bytes ``` (defn cannon[n](let[a(map #(char(+ 65 %))(iterate #(if(> % 24)0(inc %))0))m1(reverse(reduce #(concat %(repeat %2(- n %2)))[](range 0(inc n))))p1(map-indexed #(str(apply str(repeat %2 " "))(nth a %))m1)m2(reverse(reduce #(concat %(repeat %2(-(* 2 %2)2)))[](reverse(range 0(inc n)))))p2(reverse(map-indexed #(str(apply str (repeat %2 " "))(nth a(+(count p1)%)))m2))](doseq[x(reverse(map #(str % %2)p1 p2))](println x)))) ``` At some point I got tangled up in `reverse` calls and gave up on the idea to make it as short as possible. I just wanted to have a working solution. Here you go... ### Sort of ungolfed ``` (defn cannon [n] (let [a (map #(char (+ 65 %)) (iterate #(if (> % 24) 0 (inc %)) 0)) m1 (reverse (reduce #(concat % (repeat %2 (- n %2))) [] (range 0 (inc n)))) p1 (map-indexed #(str (apply str (repeat %2 " ")) (nth a %)) m1) m2 (reverse (reduce #(concat % (repeat %2 (- (* 2 %2) 2))) [] (reverse (range 0 (inc n))))) p2 (reverse (map-indexed #(str (apply str (repeat %2 " ")) (nth a (+ (count p1) %))) m2))] (doseq [x (reverse (map #(str % %2) p1 p2))] (println x)))) ``` ## Update Motivated by Olivier's comment, I managed to cut multiple `reverse` calls and apply some general golfing tricks to cut characters. Also I created aliases for `reverse`, `map-indexed`, `concat`, `repeat` and `str` because I used them multiple times each. ``` (defn c[n](let[a(map #(char(+ 65 %))(iterate #(if(> % 24)0(inc %))0))k #(reduce %[](range 0(inc n)))r #(apply str(repeat % " "))rv reverse m map-indexed c concat t repeat s str p(m #(s(r %2)(nth a %))(rv(k #(c %(t %2(- n %2))))))](rv(map #(s % %2)p(rv(m #(s(r %2)(nth a(+(count p)%)))(k #(c %(t %2(-(* 2 %2)2)))))))))) ``` ### Ungolfed ``` (defn c [n] (let [a (map #(char (+ 65 %)) (iterate #(if (> % 24) 0 (inc %)) 0)) k #(reduce % [] (range 0 (inc n))) r #(apply str (repeat % " ")) rv reverse m map-indexed c concat t repeat s str p (m #(s (r %2) (nth a %)) (rv (k #(c % (t %2 (- n %2))))))] (rv (map #(s % %2) p (rv (m #(s (r %2) (nth a (+ (count p) %))) (k #(c % (t %2 (- (* 2 %2) 2)))))))))) ``` Creates the function `c` which accepts the value n and returns a list of lines. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~33~~ 31 bytes ``` ≔⁰ηF…±N⊕θ«¿ι→↓F↔ι«P§αη≦⊕η¿›ι⁰↓↑ ``` [Try it online!](https://tio.run/##TY69CoMwFEbn@BQZ7wULLl3aSSgUBx2EPkDUqwZiYmO0heKzp/4Nrh@c75yyFbY0QnkfD4NsNEQhb/Ee1MZyyIVuCDJqhCNIdD@6bOwKsoAY8kSXljrSjip4IyL/BUzWHCTy1EwEt1w2rUNOaqBjeZiPXr7Zdh4Xg1Hjcix3lqWjcrK3UjuIXaIr@oJYY1aCpaI/Ak/ePZVt2qelpdKCDHmEeBaeC179CszB7P3VXyb1Bw "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 2 bytes thanks to @ASCII-only. Explanation: ``` ≔⁰η ``` Initialise the current letter as an index into the uppercase alphabet to 0. ``` F…±N⊕θ« ``` Make a loop from the negation of the input to the input inclusive. ``` ¿ι→↓ ``` Normally each column is to the right of the previous. However, there is no column for zero. Instead, a correction is needed to ensure that the left and right sides align. ``` F↔ι« ``` Loop for each letter in the column. ``` P§αη ``` Print the current letter. ``` ≦⊕η ``` Increment the letter index. ``` ¿›ι⁰↓↑ ``` Move up or down depending on which side of the trajectory we're on. [Answer] # [Perl 5](https://www.perl.org/), -n ~~112~~ ~~92~~ ~~90~~ 88 bytes For once the terribly long `printf` seems to win. ``` #!/usr/bin/perl -n $p=$q=$_*($%=$_+1)/2;map{printf"%$%c%$.c ",--$p%26+65,$q++%26+65for--$%..$';$.+=2}//..$_ ``` [Try it online!](https://tio.run/##JYhLCoMwEED3PUWRGVqNmWggbkLOIkUUhDYZo10Vr95poKv34Tk/nbz3@eqo76jzAhxgCzA2d8AC1dfG@teDP5zXeCwVAk4INF2qVmtgtIMaXAubUn9dUi4fieDmgVSwpzElRhH3TXysKe6i4w8 "Perl 5 – Try It Online") [Answer] # Python3 + numpy, ~~124~~ 115 ``` from pylab import* def i(N): x=zeros((N,2*N),'U');x[r_[N-1:-1:-1,0:N],r_[:2*N]]=map(chr,r_[0:2*N]%26+65) return x ``` This creates an appropriately sized array, finds the indices for the trajectory and assigns the appropriate character to them. ~~The most complex part is generating the characters A-Z, which relies on a very hackish cast of numbers to a string type.~~ The returned object is a unicode array. **Edit**: Saved 9 bytes replacing numpy code that generated the characters A-Z (`(r_[0:2*N]%26+65).view('U1')[::2]`) with `map`, as suggested [here](https://codegolf.stackexchange.com/a/25836/77481). [Answer] # [Python 3](https://docs.python.org/3/), ~~139~~ 136 bytes ``` f=lambda n,o=0:n and'\n'.join([f(n-1,o+n).replace('\n','\n ')]+[chr(65+(n+o+~i)%26)+' '*~-n+chr(65+(n*n+o+i)%26)for i in range(n)])or'' ``` [Try it online!](https://tio.run/##XckxDoJAEEDR3lNMY2aGASIaKEg4CVKswMoanCUbGhuuvkpMLGx@8d/yWievlxhtM5vnbTCgqW9OtYLRAa@K@cM7pdaSZkXqRTkP4zKbfqRd008AuZO2nwJVpZCKl83x8VyxIAAmW6byw2Tnr1ofwIFTCEbvIyl37ANi/PtFyfUBYAlOV7LkmOMb "Python 3 – Try It Online") Generates each layer recursively, given the size and offset. -3 bytes thanks to Jo King [Answer] # [J](http://jsoftware.com/), ~~78~~ 75 bytes ``` (26{.65|.a.)($~#)`(;/@])`(' '$~1+{:@])}i.@+:(,.~(|.,])@i.@-:@#)@#~1+i.@-,i. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NYzMqvXMTGv0EvU0NVTqlDUTNKz1HWKBlLqCukqdoXa1FZBXm6nnoG2loaNXp1GjpxOr6QDk61o5KGs6KAOVgDg6mXr/Nbm4UpMz8hXSFIwgDHV1mIDpfwA "J – Try It Online") *-3 thanks to ngn* [Answer] # [Python 2](https://docs.python.org/2/), 182 bytes ``` I=input() S=list('ZYXWVUTSRQPONMLKJIHGFEDCBA'*I) R=range print zip(*[(' '*(sum(R(abs(i))))+eval('S.pop()+'*abs(i)+"''")[::[-1,1][i>0]]).ljust(sum(range(I+1)))for i in R(-I,I+1)if i]) ``` [Try it online!](https://tio.run/##Jc1JC8IwFATge39F8JKXbljBi1DB3bibupceKrg8qWnoIuifr63OcQa@Ue/sHstGUXAXpcozYJrnRphmQE/Hw3633XhivVou5rPphI9Hw0G/1@1QnTNNuEkobxdNJSgz8kEFug@UUB3S/AkCwnMKyMoYl1cYAfVsFStgBtX/i1GjtMb8Vsu3HNMJfGzXg4DZ0SMvzyvixwM3nNK4xglBgpIIsLhZdXglGLCiaH4B) Returns list of lists of chars. [Primitive verification here](https://tio.run/##lc7LCgIhFIDhvU9xdo4wtGgZtJhL93t2j7aRLXSQgejpbcJgGlPMzQ/Hcz6weJY3wdtKUejCOcKAYzCzeGdpWQAmMfyYeXNc/WNmzXHtMVPrZ6pQt5m4zMZtxi6ztZqR67zOzjRDv9mbZuA3B9P0/eb4ZXr@8zonbfIQk2iThZhUmzTEZNokISbH5ILQVUiQ4gGMA@0gKCTjJWDcugvGo2pBPm9IqRc) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 35 bytes ``` ṪṚṭ r1m0RØAṁs⁸U2¦Ç⁶ṁ$;¥\€ÇzZ¥€⁶ẎUZY ``` [Try it online!](https://tio.run/##y0rNyan8///hzlUPd856uHMtV5FhrkHQ4RmOD3c2Fj9q3BFqdGjZ4fZHjduAfBXrQ0tjHjWtOdxeFXVoKZABEt7VFxoV@f//f1MA "Jelly – Try It Online") [Answer] # [Yabasic](http://www.yabasic.de), 125 bytes An [basic](/questions/tagged/basic "show questions tagged 'basic'") solution that uses graphics mode to print the characters at the correct column and row of the screen. ``` Input""n Clear Screen For i=-n To n For j=1To Abs(i) k=i>0 ?@(i+n-k,(i^2-i)/2+j-2*j^(!k)+k)Chr$(c+65) c=Mod(c+1,26) Next Next ``` Because this solution uses graphics mode, it cannot be executed on TIO. ### Output *Below is the output for input `7`* [![Program Output (n=7)](https://i.stack.imgur.com/N7eo7.png)](https://i.stack.imgur.com/N7eo7.png) [Answer] # [Ruby](https://www.ruby-lang.org/), ~~106~~ 103 bytes ``` ->n,f=2*s=-~n*n/2-1{l=*?A..?Z;(1..n).map{|i|i.times{puts' '*(n-i)+l[(f-s)%26]+' '*~-i*2+l[(s+=1)%26]}}} ``` [Try it online!](https://tio.run/##HchLCoMwEADQq3RTzKczJYF2U6biNSouWmggoIM4uigxXj1i3/JNy@dXAhV48iWQN0KwseGrB5d6MnWDWL8eyiGyxuE9pjWuEec4fCWNyyzVqTKKIWrbtyqA6LO/d/bYDaLxx4ol9@@ccwntrSs7 "Ruby – Try It Online") [Answer] # [QBasic 1.1](https://archive.org/details/msdos_qbasic_megapack), 124 bytes Takes input and shoots a cannon. Due to screen size limitations, \$n\$ must be \$\leq 6\$. ``` INPUT n CLS FOR i=-n TO n FOR j=1TO ABS(i) k=i>0 LOCATE(i^2-i)/2+j-2*j^-(k=0)-k+1,i+n+k+1 ?CHR$(c+65) c=(c+1)MOD 26 NEXT j,i ``` [Answer] # [Python 3](https://docs.python.org/3/), 190 bytes ``` j,r,c,s=int(input()),range,[],[];a=(j+1)*j;b=a//2 for i in r(j):k=i+1;c.extend([j-k]*k) for i in r(a):s+=chr(ord('A')+(i%26)) for i in r(b):print(' '*c[i]+s[b-i-1]+' '*(2*(j-c[i]-1))+s[b+i]) ``` [Try it online!](https://tio.run/##VY69DoIwFEZ3n6KL4d7@SMDoAOngc5AOpaDckhRSMNGnr3bT5JvOd4azvvdpCeeUvIzSyU1T2IHC@twBUUYbHqPszHet1eBFhdy3vbZlWR/uS2TEKLAIHptZk6hadxpf@xgG6LyaDZ/x17LYbEK7KcISByhuBQqgY33FP6vHZo25omAFdx0ZsXW9IlUZkQnUHLzKXFWI@RNkMKXLBw "Python 3 – Try It Online") I tried my best. Let me know if any optimisations are possible. [Answer] # k4, ~~76~~ 71 bytes ``` {+|:'p$(-k,|k:+\l)$(x#b),|:'x_b:(i:-1_0,+\l,|l)_a:(2*p:+/l:|1+!x)#.Q.a} ``` some rearranging+assignments to save 5 bytes --- ``` {+|:'(+/l)$(-k,|k:+\l)$(x#i_a),|:'((-x)#i:-1_0,+\l,|l)_a:(2*+/l:|1+!x)#.Q.a} ``` half-hour effort with some effort to shave off a few bytes, but there's probably much more that can be done here. will come back to it. fun challenge! ]
[Question] [ While doodling around with numbers, I found an interesting permutation you can generate from a list of numbers. If you repeat this same permutation enough times, you will always end up back at the original array. Let's use the following list: ``` [1, 2, 3, 4, 5] ``` as an example 1. **Reverse** the array. Now our array is ``` [5, 4, 3, 2, 1] ``` 2. **Reorder** (swap) each pair. Our list has 2 pairs: `[5, 4]`, and `[3, 2]`. Unfortunately, we can't group the `1` into a pair, so we'll just leave it on it's own. After swapping each pair, the new array is: ``` [4, 5, 2, 3, 1] ``` 3. **Repeat** steps 1 and 2 until we return to the original array. Here are the next 4 steps: ``` Step 2: Start: [4, 5, 2, 3, 1] Reversed: [1, 3, 2, 5, 4] Pairs Swapped: [3, 1, 5, 2, 4] Step 3: Start: [3, 1, 5, 2, 4] Reversed: [4, 2, 5, 1, 3] Pairs Swapped: [2, 4, 1, 5, 3] Step 4: Start: [2, 4, 1, 5, 3] Reversed: [3, 5, 1, 4, 2] Pairs Swapped: [5, 3, 4, 1, 2] Step 5: Start: [5, 3, 4, 1, 2] Reversed: [2, 1, 4, 3, 5] Pairs Swapped: [1, 2, 3, 4, 5] # No more steps needed because we are back to the original array ``` If the length of the list, **n** is odd, it will always take exactly **n** steps to return to the original array. If **n** is even, it will always take 2 steps to return to the original array, *unless* n is 2, in which case it will take 1 step (because reversing and swapping is the same thing). Your task for today (should you choose to accept it) is to visualize this set of steps for lists of arbitrary lengths. You must write a program or function that takes a single positive integer *n* as input, and does this set of steps for the list `[1, n]`. You must output each intermediate step along the way, whether that means printing each step, or returning them all as a list of steps. I'm not very picky about the output format, as long as it's clear that you are generating every step. This means (for example) any of these: * Outputting every step as a list to STDOUT * Returning a list of lists * Returning a list of string representations of each step * Returning/outputting a matrix would be acceptable. You must also output the original array, whether that comes at the end or at the beginning is up to you. (technically, both are correct) *You will have to handle the edge case of 2 taking 1 step instead of 2*, so please make sure your solution works with an input of 2 (and 1 is another potential edge case). As usual, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so standard loopholes apply, and try to make your solution shorter than any other in the language of your choice (or even try to beat another language that is typically shorter than yours if you're feeling up for a challenge). # Test IO ``` 1: [1] 2: [1, 2] 3: [2, 3, 1] [3, 1, 2] [1, 2, 3] 4: [3, 4, 1, 2] [1, 2, 3, 4] 5: [4, 5, 2, 3, 1] [3, 1, 5, 2, 4] [2, 4, 1, 5, 3] [5, 3, 4, 1, 2] [1, 2, 3, 4, 5] 7: [6, 7, 4, 5, 2, 3, 1] [3, 1, 5, 2, 7, 4, 6] [4, 6, 2, 7, 1, 5, 3] [5, 3, 7, 1, 6, 2, 4] [2, 4, 1, 6, 3, 7, 5] [7, 5, 6, 3, 4, 1, 2] [1, 2, 3, 4, 5, 6, 7] 9: [8, 9, 6, 7, 4, 5, 2, 3, 1] [3, 1, 5, 2, 7, 4, 9, 6, 8] [6, 8, 4, 9, 2, 7, 1, 5, 3] [5, 3, 7, 1, 9, 2, 8, 4, 6] [4, 6, 2, 8, 1, 9, 3, 7, 5] [7, 5, 9, 3, 8, 1, 6, 2, 4] [2, 4, 1, 6, 3, 8, 5, 9, 7] [9, 7, 8, 5, 6, 3, 4, 1, 2] [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` And for good measure, here's one giant test case: ``` 27: [26, 27, 24, 25, 22, 23, 20, 21, 18, 19, 16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 1] [3, 1, 5, 2, 7, 4, 9, 6, 11, 8, 13, 10, 15, 12, 17, 14, 19, 16, 21, 18, 23, 20, 25, 22, 27, 24, 26] [24, 26, 22, 27, 20, 25, 18, 23, 16, 21, 14, 19, 12, 17, 10, 15, 8, 13, 6, 11, 4, 9, 2, 7, 1, 5, 3] [5, 3, 7, 1, 9, 2, 11, 4, 13, 6, 15, 8, 17, 10, 19, 12, 21, 14, 23, 16, 25, 18, 27, 20, 26, 22, 24] [22, 24, 20, 26, 18, 27, 16, 25, 14, 23, 12, 21, 10, 19, 8, 17, 6, 15, 4, 13, 2, 11, 1, 9, 3, 7, 5] [7, 5, 9, 3, 11, 1, 13, 2, 15, 4, 17, 6, 19, 8, 21, 10, 23, 12, 25, 14, 27, 16, 26, 18, 24, 20, 22] [20, 22, 18, 24, 16, 26, 14, 27, 12, 25, 10, 23, 8, 21, 6, 19, 4, 17, 2, 15, 1, 13, 3, 11, 5, 9, 7] [9, 7, 11, 5, 13, 3, 15, 1, 17, 2, 19, 4, 21, 6, 23, 8, 25, 10, 27, 12, 26, 14, 24, 16, 22, 18, 20] [18, 20, 16, 22, 14, 24, 12, 26, 10, 27, 8, 25, 6, 23, 4, 21, 2, 19, 1, 17, 3, 15, 5, 13, 7, 11, 9] [11, 9, 13, 7, 15, 5, 17, 3, 19, 1, 21, 2, 23, 4, 25, 6, 27, 8, 26, 10, 24, 12, 22, 14, 20, 16, 18] [16, 18, 14, 20, 12, 22, 10, 24, 8, 26, 6, 27, 4, 25, 2, 23, 1, 21, 3, 19, 5, 17, 7, 15, 9, 13, 11] [13, 11, 15, 9, 17, 7, 19, 5, 21, 3, 23, 1, 25, 2, 27, 4, 26, 6, 24, 8, 22, 10, 20, 12, 18, 14, 16] [14, 16, 12, 18, 10, 20, 8, 22, 6, 24, 4, 26, 2, 27, 1, 25, 3, 23, 5, 21, 7, 19, 9, 17, 11, 15, 13] [15, 13, 17, 11, 19, 9, 21, 7, 23, 5, 25, 3, 27, 1, 26, 2, 24, 4, 22, 6, 20, 8, 18, 10, 16, 12, 14] [12, 14, 10, 16, 8, 18, 6, 20, 4, 22, 2, 24, 1, 26, 3, 27, 5, 25, 7, 23, 9, 21, 11, 19, 13, 17, 15] [17, 15, 19, 13, 21, 11, 23, 9, 25, 7, 27, 5, 26, 3, 24, 1, 22, 2, 20, 4, 18, 6, 16, 8, 14, 10, 12] [10, 12, 8, 14, 6, 16, 4, 18, 2, 20, 1, 22, 3, 24, 5, 26, 7, 27, 9, 25, 11, 23, 13, 21, 15, 19, 17] [19, 17, 21, 15, 23, 13, 25, 11, 27, 9, 26, 7, 24, 5, 22, 3, 20, 1, 18, 2, 16, 4, 14, 6, 12, 8, 10] [8, 10, 6, 12, 4, 14, 2, 16, 1, 18, 3, 20, 5, 22, 7, 24, 9, 26, 11, 27, 13, 25, 15, 23, 17, 21, 19] [21, 19, 23, 17, 25, 15, 27, 13, 26, 11, 24, 9, 22, 7, 20, 5, 18, 3, 16, 1, 14, 2, 12, 4, 10, 6, 8] [6, 8, 4, 10, 2, 12, 1, 14, 3, 16, 5, 18, 7, 20, 9, 22, 11, 24, 13, 26, 15, 27, 17, 25, 19, 23, 21] [23, 21, 25, 19, 27, 17, 26, 15, 24, 13, 22, 11, 20, 9, 18, 7, 16, 5, 14, 3, 12, 1, 10, 2, 8, 4, 6] [4, 6, 2, 8, 1, 10, 3, 12, 5, 14, 7, 16, 9, 18, 11, 20, 13, 22, 15, 24, 17, 26, 19, 27, 21, 25, 23] [25, 23, 27, 21, 26, 19, 24, 17, 22, 15, 20, 13, 18, 11, 16, 9, 14, 7, 12, 5, 10, 3, 8, 1, 6, 2, 4] [2, 4, 1, 6, 3, 8, 5, 10, 7, 12, 9, 14, 11, 16, 13, 18, 15, 20, 17, 22, 19, 24, 21, 26, 23, 27, 25] [27, 25, 26, 23, 24, 21, 22, 19, 20, 17, 18, 15, 16, 13, 14, 11, 12, 9, 10, 7, 8, 5, 6, 3, 4, 1, 2] [1, 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] ``` Have fun golfing! [Answer] # TI-Basic (83 series), ~~58~~ ~~57~~ 54 bytes (104 characters) ``` :seq(I,I,1,Ans→A :Ans→B :Repeat prod(Ans=ᶫB :ᶫB→C :int(⁻Ans/2→D :SortD(ᶫC,ᶫA :SortD(ᶫD,ᶫA :Pause ᶫA :End ``` ### Explanation Takes input in `Ans` (e.g., write `5:prgmNAME` to use lists of size five). Creates three auxiliary lists of the given size (which are recreated from `ᶫB` at each step): `ᶫB = ᶫC = {1,2,3,4,5,...}` and `ᶫD = {-1,-1,-2,-2,-3,...}`. At each step, sorts `ᶫC` and `ᶫD` in descending order, applying the same permutation to `ᶫA`. In the case of `ᶫC`, this reverses `ᶫA`, and in the case of `ᶫD`, this swaps adjacent pairs because TI-Basic uses a **really stupid selection sort implementation** for `SortD(` which reorders as many identical elements as it possibly can. When `ᶫA` is equal to `ᶫB` again, we stop. No, seriously, their built-in sorting algorithm is my second-biggest complaint with the TI-Basic interpreter. (My biggest complaint is how lots of nested loops slow down the interpreter, since the loop data is stored in a stack, but the stack is grown from the wrong end, so the calculator has to *move the entire stack* every time an element is pushed or popped.) But this time, it's convenient. --- -1 byte: `Pause` stores the value it's printing to `Ans`, which is shorter to reference than `ᶫA`. -3 bytes: take input in `Ans` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` RµUs2UFµÐĿ ``` [Try it online!](https://tio.run/##y0rNyan8/z/o0NbQYqNQt0NbD084sv////@mAA "Jelly – Try It Online") # Explanation ``` RµUs2UFµÐĿ Main link R Generate the range ÐĿ While the results are unique (collecting results) µUs2UFµ Reverse and reorder U Reverse s Slice non-overlapping into length 2 2 U Reverse (automatically vectorizes to depth 1) F Flatten ``` # Note If the original range *needs* to be at the end, append `ṙ1` to the code for 12 bytes. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 11 bytes ``` LIGÂ2ôí˜})Ù ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fx9P9cJPR4S2H156eU6t5eOb//6YA "05AB1E – Try It Online") **Explanation** ``` L # range [1 ... input] IG # input-1 times do:  # bifurcate 2ô # split into pieces of 2 í # reverse each ˜ # flatten } # end loop ) # wrap stack in a list Ù # remove duplicates ``` [Answer] # JavaScript (ES6), ~~89~~ 85 *Edit* 4 bytes saved thx @JustinMariner Using the fact that when any element is at the right place, all elements are. ``` n=>{for(l=[];n;l[n-1]=n--);while(alert(l=l.reverse().map((x,i)=>l[i^1]||x)),l[0]-1);} ``` *Less golfed* ``` n => { for(l=[], i=0; i<n; l[i] = ++i); while( alert(l=l.reverse().map( (x,i) => l[i^1] || x)), l[0]-1); } ``` **Test** ``` var F= n=>{for(l=[];n;l[n-1]=n--);while(alert(l=l.reverse().map((x,i)=>l[i^1]||x)),l[0]-1);} alert=x=>console.log(x+'') // to avoid popup stress function update() { F(+I.value); } update() ``` ``` <input type=number id=I value=1 min=1 oninput='update()'> ``` [Answer] # R, ~~109~~ ~~95~~ ~~94~~ ~~79~~ ~~74~~ 62 bytes If the fact that the code throws warnings on top of the actual solution (no warnings if `n` is 1, 3 warnings if `n` is even and `n` warnings if `n` is odd) is not an issue, then the following works similarly to the previous solution, thanks to vector recycling: ``` n=scan();m=1:n;w=0:n+2*1:0;while(print(m<-rev(m)[w[w<=n]])-1)n ``` [Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTOtfW0CrPutzWwCpP20jL0MrAujwjMydVo6AoM69EI9dGtyi1TCNXM7o8utzGNi82VlPXUDPvv8l/AA "R – Try It Online") Thanks again to [@Giuseppe](https://codegolf.stackexchange.com/users/67312) for an extra 12 bytes off! **Previous, warning-less solution at 94 bytes:** ``` n=scan();m=s=1:n;while(any(print(m<-rev(m)[c(if(n>1)2:1+rep(seq(0,n-2,2),e=2),n[n%%2])])!=s))n ``` [Try it online!](https://tio.run/##DcRBCoMwEAXQq9SF8IdGMKEr7fQi4kJkxEDzsYm09PRp3@LlWi/Usi6EjEmL@oHjZ49Pw8Ivjhx5It27bG8kmVbEDXx4CYO/ZjtQ7IXesQsuiDP9x4ltG2aZpdEiwnqrPw "R – Try It Online") **Original solution at 109 bytes**: ``` n=scan();m=s=1:n;repeat{cat(m<-rev(m)[c(t(embed(s,min(n,2))[!!s[-n]%%2,]),n[n%%2])],"\n");if(all(m==s))break} ``` [Try it online!](https://tio.run/##DcbBCsIwDADQb9lgkEB2sBfBmi@pPWQ1wnAJ0hYv4rdX3@nVMZxbEQeMxo1PF49VXyr9U6SDXdeqbzBMBTqobXqHRrY7OAXENE0trZ6XJVBG8uT/Zcw033zGuD9AjgOMuSFuVeX5HeE8fg "R – Try It Online") [Answer] # Mathematica, 142 bytes ``` (h=Range@#;W={};For[i=1,i<=#,i++,s=Reverse@h;AppendTo[W,h=Join[f=Flatten[Reverse/@Partition[s,{2}]],s~Complement~f]];s=h];DeleteDuplicates@W)& ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` U¡ȯṁ↔C2↔ḣ ``` [Try it online!](https://tio.run/##yygtzv7/P/TQwhPrH@5sfNQ2xdkISDzcsfj///@mAA "Husk – Try It Online") ``` -- implicit input N | 3 ḣ -- list [1..N] | [1,2,3] ¡( ) -- iterate the following function, | [[1,2,3],[2,3,1],[3,1,2],[1,2,3],... U -- until the first repetition: | [[1,2,3],[2,3,1],[3,1,2]] ↔ -- reverse | [3,2,1] C2 -- cut into two | [[3,2],[1]] ṁ↔ -- reverse each pair & flatten | [2,3,1] ``` [Answer] # JavaScript (ES6), 79 bytes ``` f=(n,a=[...Array(n)],b=a.map((x,i)=>n-((x?x-1:i)^1)||1))=>b[0]>1?b+` `+f(n,b):b ``` Outputs a list for each step. Note that we don't need to initialize the array to get the ball rolling. If uninitialized (`x` is undefined), we can use the array's indices (parameter `i`) to do the first step: ``` b=a.map((x,i)=>n-((x?x-1:i)^1)||1) ``` **Test Cases:** ``` f=(n,a=[...Array(n)],b=a.map((x,i)=>n-((x?x-1:i)^1)||1))=>b[0]>1?b+` `+f(n,b):b console.log(f(1)); console.log(f(2)); console.log(f(3)); console.log(f(4)); console.log(f(5)); console.log(f(7)); console.log(f(27)); ``` [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~20~~ ~~18~~ ~~15~~ 12 bytes ``` õ £=ò2n)ÔcÃâ ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=9QqjPfIybinUY8Pi&input=OQotUg==) (`-R` flag for visualisation purposes only) 1 byte saved thanks to ETHproductions. ``` :Implicit input of integer U õ :Range [1,U] \n :Reassign to U £ :Map ò : Partitions 2 : Of length 2 n : Starting from the end ) : End partition Ô : Reverse c : Flatten = : Reassign to U à :End map â :Deduplicate ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~64 57 52~~ 50 bytes ``` ->x{(s=*w=1..x).map{s=w.map{|y|s[-y^1]||s[0]}}|[]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf166iWqPYVqvc1lBPr0JTLzexoLrYthxM11TWFEfrVsYZxtYAGQaxtbU10bG1/zWAKg0NIEprKmoKFCp00qIrgBIA "Ruby – Try It Online") ### How it works: First create the range, then repeat the permutation x times: use a negative index, but flip the last bit, so we get the sequence -2, -1, -4, -3... if x is even, this will end well, if not we will add the remaining element at the end. Last step: filter out repeated arrays (so we cover all cases: x=1, x=2, odd and even numbers) [Answer] ## Haskell, ~~75~~ 74 bytes ``` g(a:b:c)=b:a:g c g x=x h=g.reverse 0!x|x<[2]=[x]|1<2=x:0!h x p n=0!h[1..n] ``` [Try it online!](https://tio.run/##FckxCoQwEADAPq9YO22C2rm4T7gXhHCsEhI5DSHKsUX@HrUbmMDnz@17rb5lXHDtaEFGD6vyICQqkNfZ/V0@neobKTKb0ZIRW4Z5JMG@CSAqQaRHZtA62nrwFoHg4PT5QpvyFi@dOnh3slBv "Haskell – Try It Online") `g` does the pair-wise swaps, `h` a single step (reverse + reorder), `!` repeatedly applies `h` (and collects the intermediate results) until the order is restored. Note: `!` takes the additional but unused extra parameter `0` just to make it an infix operator. The main function `p` starts it up. Edit: Thanks to @Angs for a byte. [Answer] # [Stax](https://github.com/tomtheisen/stax), 17 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` âΩÄ─g╫B♥C╛♠ƒ?|πcD ``` [Run and debug it](http://stax.tomtheisen.com/#p=83ea8ec467d7420343be069f3f7ce36344&i=1%0A2%0A3%0A4%0A7%0A9%0A27&m=2) **Explanation** ``` RX~Wr2/{r+}Fc|uPcx=C # Full program, unpacked, implicit input RX~ # Create range, save to X register, pop back to input stack W # Start while loop until truthy value r # reverse array 2/ # Split into groups of 2 {r+}F # Loop through each set and reverse each c # Copy top value |u # Convert to string representation of array P # Pop top value off cx= # Copy top value, get value of x register, compare to top value C # If top value is truthy, cancel block and end ``` Suprised it works as fast as it does, tested up to 399 before I didn't want to temp my browser anymore. [Answer] # Java 8, ~~215~~ 214 bytes ``` import java.util.*;n->{Stack a=new Stack(),t;int i=0;for(;i<n;a.add(++i));t=(Stack)a.clone();Collections x=null;for(i=0;i<1|!a.equals(t);System.out.println(t))for(x.reverse(t),i=0;i<n;i++)if(i<n-1)x.swap(t,i,++i);} ``` I tried to golf it using actual arrays instead of a List, but both reversing and swapping will take up too many bytes.. Maybe it can be combined in one loop (instead of first reversing, then swapping), but I've yet to figure this out. This can definitely be golfed some more, though. **Explanation:** [Try it here.](https://tio.run/##jZJNb8MgDIbv@RXeDZaErvtQNdHssvOqST1OO7iEbLQUsuD0Q11/e0bSHneIBJJ5eYz9Wqxxh7mvtVuXm85sa98QrKMmWjJW3EoAmEzgHaPsK6BvDasj6Vz51lGSKIshwBsad0oAjCPdVKg0LPojwM6bEhSLOjguo3SOO65ASEbBAhwU0Ln85bQkVBvAwuk9DDHjGck@0RR3svINk2buJAosS5amhnNJBRtIjkJZ7zTj8tVbqxUZ7wIcCtdaO6T2T5j59PcGhf5p0QZGXC6PgfRW@JZE3cRC1kWV9/hBNHqnm6CjkF1ynTRpyk3FYphP@UGEPdaMMpP1vchzJ5Noq25XNtq6uhvMb@NoYpuxwNfHJyC/zMUJxabDQAD@6eN601P3o6iHUdTjKOppFDUbRT2P8zi7/o1z9wc) ``` import java.util.*; // Required import for Stack and Collections n->{ // Method with integer parameter and no return-type Stack a=new Stack(), // Original List t; // Copy-List int i=0; // Index-integer, starting at 0 for(;i<n;a.add(++i)); // Fill the original list with the integers t=(Stack)a.clone(); // Make a copy of the List Collections x=null; // Static `Collections` to reduce bytes for(i=0; // Reset index `i` to 0 i<1 // Loop (1) as long as `i` is 0 (the first iteration), |!a.equals(t); // or the input array is not equal to the copy System.out.println(t)) // After every iteration: print the modified List for(x.reverse(t), // Reverse the copied List i=0; // Reset `i` to 0 i<n; // Inner loop (2) over the List i++) // After every iteration: increase `i` by 1 again if(i<n-1) // Unless it's the last item in the List: x.swap(t,i,++i); // Swap the items at indexes `i` and `i+1` // (by increasing `i` by 1 first with `++i`) // End of inner loop (2) (implicit / single-line body) // End of loop (1) (implicit / single-line body) } // End of method ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~257~~ ~~245~~ ~~243~~ ~~226~~ ~~206~~ 205 bytes ``` n->{int i=0,k,t[]=new int[n];while(i<n)t[i]=++i;do{for(i=0;i<n/2;t[i]=t[n+~i],t[n+~i++]=k)k=t[i];for(k=1;k<n;t[k]=t[--k],t[k]=i,k+=3)i=t[k];System.out.println(java.util.Arrays.toString(t));}while(t[0]>1);} ``` [Try it online!](https://tio.run/##RZAxb8IwEIX3/AqPcZO4QIcOxkhVpw6dGCMPbjD0cGJH9gWEEP3r6bkg9Zbzvfss3XtHczJNGK0/7twMwxgisiNpYkLoxX7yHULw4kkWxTh99dCxrjcpsU8Dnl0LRpXQIOnvwadpsHH94dEebNywyBSbfbO5gkcGalG7GlutvD0zUlqv5fkbelvC2nNsQauqArkL132IJeGS9OeV/NsQXf2Aru@9qrRy3Km8kpl2aind2hPrMts0LqP0htpV6oWDypPcXhLaQYQJxRjphN6X/17fYjSXJDBskXaHEjmXt/uB2C70ZknjnP1SFLk94ni4PwXYsYFCKe/fW81MPCT@yChXFKbr7Ijl6pXLP/VW3OZf "Java (OpenJDK 8) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 17 bytes ``` :`tP2ePXz!tG:-a]x ``` [Try it online!](https://tio.run/##y00syfn/3yqhJMAoNSCiSrHE3Uo3Mbbi/39TAA "MATL – Try It Online") ### Explanation ``` : % Implicit input: n. Push [1 2 ... n] ` % Do...while t % Duplicate P % Reverse 2e % Reshape into a 2-row matrix. A final 0 is added if needed P % Reverse each column Xz % Nonzero entries (i.e. remove final 0 if present). Gives a column vector ! % Transpose into a row t % Duplicate G: % Push [1 2 ... n] again - % Subtract element-wise a % Any. Gives true if there is at least a nonzero value ] % End. Go to next iteration if top of the stack is true. So the loop ends % when [1 2 ... n] has been found again x % Delete top of the stack (which is [1 2 ... n]). Implicit display ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~165~~ ~~159~~ ~~138~~ 81 bytes ``` x=input()+1 b=a=range(1,x) while b:b=[b[x-min(x,i+1^1)]for i in a];print b;b*=a<b ``` [Try it online!](https://tio.run/##JcyxCsMgFIXh3ae4S4nGhuKFLhafRBwMmNamGFEL9umtkuEs34E//srrCNhaVT7Eb6GMWJVseDoqrpULRrKq4DeoFwT3yQ5woVUpZGQ7ErzBhwmmOUur9AqD9k5wFuoN2aB1kNVSLsJonHfZx9GcYHh/et08YvKhgG3t/gc "Python 2 – Try It Online") *-20 bytes thanks to @ChasBrown*. (Sigh, I made a whole challenge about extended slicing syntax) Whoa! GolfStorm (-57 bytes)! Thanks to Ian Gödel, tsh, and Jonathan Frech. [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 33 bytes Nope, I can't simplify the algorithm. ``` ~),1>:a{-1%2/{-1%}%{+}*.p.a=!}do; ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v05Tx9DOKrFa11DVSB9E1qpWa9dq6RXoJdoq1qbkW///bwoA "GolfScript – Try It Online") ## Explanation ``` ~ # Dump the input ), # Generate inclusive range: 0 -> input 1>:a # Set [1 2 ... input-1 input] to a without popping { }do # Do ... While .a=! # The current item does not equal to a -1% # Reverse the item 2/ # Split into equal parts of 2 {-1%}% # For each equal part, reverse {+}* # Flatten the list .p # Print the list ; # We don't need to implicit output the # extra value left on the stack ``` [Answer] # [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3) `j`, 8 bytes ``` ɾᶨλṚ2ẆVf ``` [Try it Online!](https://vyxal.github.io/latest.html#WyJqIiwiIiwiyb7htqjOu+G5mjLhuoZWZiIsIiIsIjUiLCIzLjMuMCJd) [Answer] ## JavaScript (ES6), 122 bytes ``` f=(n,a=[...Array(n)].map((_,i)=>i+1),r=[],b=a.map((_,i)=>a[n+~(i^1)]||a[0]))=>b.some((e,i)=>e>b[i+1],r.push(b))?f(n,b,r):r ``` `r.push(a)` could be used instead of `r.push(b)` to put the original permutation at the front. [Answer] # [Haskell](https://www.haskell.org/), 97 bytes This feels a bit long :( ``` f n|x<-[1..n]=x:takeWhile(/=x)(tail$iterate((r=<<).g.r)x) r=reverse g[]=[] g x=take 2x:g(drop 2x) ``` [Try it online!](https://tio.run/##FYyxCsIwEED3fsUNDslgRMGl9CZnZ4dS5KDXNDRNy@WQDP57rMODt7w3U144xlonSN/Snfurc2nA0iot/JpDZHPBYo1SiKegLKRsjGDXWeed2GIbQeEPS@bG9wP2Q@Oh4D@HW2m9GWXbD7N1pZAAYaX9@YZdQlJwMB0I0wjHETzrY0vKSXO9/wA "Haskell – Try It Online") ### Explanation/Ungolfed ``` -- starting with x, accumulate the results of repeatedly -- applying the function permute f n = x : takeWhile (/=x) (tail $ iterate permute x) where x = [1..n] -- reverse, cut2, reverse each pair & flatten permute = concatMap reverse . cut2 . reverse -- recursively transform a list into groups of 2 cut2 [] = [] cut2 xs = take 2 xs : g (drop 2 xs) ``` [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 42 bytes ``` [~>[rev 2#<$revflatmap]periodsteps behead] ``` [Try it online!](https://tio.run/##Ky5JTM5OTfn/P7rOLrootUzBSNlGBUin5SSW5CYWxBakFmXmpxSXpBYUKySlZqQmpsT@d7BK4@IyVEhTSMksLuAygjGMYQwTGMMUxjCHMSzhumBC/wE "Stacked – Try It Online") Performs the given transformation using the `periodsteps` builtin. However, this builtin returns all of the elements, which includes the input's range as its first and last elements. We therefore behead the list, returning all but the first element. [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 123 bytes Not very tight, but this is the best I could come up with. ``` {for(N=$1;N>$i=++i;);for(;n++<(i%2?i:i>2?2:1);){for(k=0;k++<i;)K[k]=(z=i-k+(k-1)%2*2)?$z:$1;for(k=0;k++<N;){$k=K[k]}print}} ``` [Try it online!](https://tio.run/##TcxBCsIwEAXQy6SQcSg4s8w4zQGEXKC4cCMMA1WKIFRy9pi66vb/9//94619H881Fg0kZQqmiCYgeyYL4iXawNmSTZw5EQj8uetZvLedXme/adzURsfoI8HAJ4YcttQfj7b0bXDdfX2ttrxrbY3oBw "AWK – Try It Online") [Answer] # JavaScript, 136 bytes ``` (n)=>{for(a=[],i=0;i<n;a[i]=++i);for(j=0;j<(n&1?n:2);j++){a.reverse();for(i=0;i<a.length-1;i += 2)m=a[i],a[i]=a[i+1],a[i+1]=m;alert(a)}} ``` [Answer] # [TypeScript](https://typescriptlang.org/)’s type system, ~~203~~ ~~193~~ ~~190~~ 183 bytes ``` //@ts-ignore type F<N,A=[],E=A,O=N,G=[...N,...A]>=N extends[1,...infer D]?F<D,[N,...A]>:A extends[...infer R,infer X,infer Y]?F<[...N,X,Y],R,E,O>:E extends O[any]?O:F<[],G,E,[...O,G]> ``` [Try it at the TS playground](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwLAChwE8AHdAAgDEAeAOQBoBBAXgG0BdagUXtuoHl6aBxJgDoRNEUNrMAfH2LoAHuHSIAJpEYBGauNiIAZulTEAIswD8FY9UZiRkqQC5acxcrWMd+w8QBK1XQZGABr+XkYAmuYUHqLUIZHUfmw8jmwuSqqQxNyMAIaIeObcDtGs-OzW4tzU-NI4OPhExFn0ZOSa1FpdnXXYDYQkucSt6gAMzDggxNMAemb9TQBGw82aE9hTs-O4A8QAxivqAEzrm8RzCyQqh4wAzKfA0+fbjSQkI4wALA9PF9hAA) This is a generic type `F`, which takes input as a tuple type of 1s representing a unary number, and outputs a list of unary numbers in the same format. I can’t believe I got this all to fit in a single type. This is definitely one of the coolest TS types submissions I’ve posted. ## Explanation The `//@ts-ignore` comment on the first line tells the compiler to suppress any warnings from the following line. The beginning of the type describes its arguments: ``` type F<N,A=[],E=A,O=N,G=[...N,...A]> ``` What the arguments do is explained later, but you should know that `G` is an alias for N with A appended to it; it comes in handy later. The type has three “stages”, which are entered at different times in the evaluation of the type. * The first stage converts the unary number to the range of unary numbers between 1 and the input. (At this stage, the input is in N, and A is the empty tuple.) ``` N extends[1,...infer D] ``` Is the first item of N a one? If so, remove it and call the rest D, and… ``` F<D,[N,...A]> ``` …recurse, with N set to D, and with N prepended to A. By the end of stage 1, A will contain the range from 1 to the input, E will be set equal to A, and N and O will both be the empty tuple. (E is the initial step; this will be how the type knows to terminate. O will be the list of intermediate results, which will be the final return value.) * If the first stage was not entered, because N is either empty or contains elements that aren’t ones, then the second stage is entered, to reverse and reorder the elements of A. ``` A extends[...infer R,infer X,infer Y] ``` If A has two or more items, call the last two X and Y respectively, and the rest R. ``` F<[...N,X,Y],R,E,O> ``` Recurse, appending X and Y to N, setting A to R, and keeping the values of E and O as they already are. By the end of this stage, N will contain the reversed and reordered items of A. A will be empty if it originally had an even number of items, but if its length was odd then it will contain the last item to be appended to N. This is a minor pain point of the solution, adding 14 bytes to alias G to N with A appended. * The third stage does the “repeat” step. ``` E extends O[any]?O ``` If E (the initial result) is contained in O (the list of intermediate results), then the program is finished; return O. ``` F<[],G,E,[...O,G]> ``` Otherwise, recurse with N set to the empty tuple (skipping stage 1 and going straight to stage 2), A set to G (the alias for N with A appended), E left unchanged, and O with G appended. [Answer] # [Perl 5](https://www.perl.org/) `-p`, 89 bytes ``` $_=$;=join$",1..$_;do{$_=join$",reverse/\d+/g;s/(\d+) (\d+)/$2 $1/g;$\+=say}until$;eq$_}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lbF2jYrPzNPRUnHUE9PJd46Jb8aKAoVKkotSy0qTtWPSdHWT7cu1tcAMjQVwKS@ipGCiiFQVCVG27Y4sbK2NK8kM0fFOrVQJb62@v9/k3/5BSWZ@XnF/3V9TfUMDA3@6xbkAAA "Perl 5 – Try It Online") ]
[Question] [ In the game of Flood Paint, the goal of the game is to get the entire board to be the same colour in as few turns as possible. The game starts with a board that looks something like this: ``` 3 3 5 4 1 3 4 1 5 5 1 3 4 1 1 5 2 1 6 5 2 3 4 3 3 4 3 4 4 4 5 5 5 4 1 4 6 2 5 3[3]1 1 6 6 5 5 1 2 5 2 6 6 3 6 1 1 5 3 6 2 3 6 1 2 2 4 5 3 5 1 2 3 6 6 1 5 1 3 2 4 ``` Currently, the number (representing a colour) at the center of the board is 3. Each turn, the square at the center will change colour, and all the squares of the same colour that are reachable from the center by moving horizontally or vertically (i.e. in the flood region of the center square) will change colours with it. So if the center square changes colour to 5: ``` 3 3 5 4 1 3 4 1 5 5 1 3 4 1 1 5 2 1 6 5 2 3 4 3 3 4 3 4 4 4 5 5 5 4 1 4 6 2 5 5[5]1 1 6 6 5 5 1 2 5 2 6 6 3 6 1 1 5 3 6 2 3 6 1 2 2 4 5 3 5 1 2 3 6 6 1 5 1 3 2 4 ``` then the 3 that was to the left of the center 3 will also change colour. Now there are a total of seven 5's reachable from the center one, and so if we then change colour to 4: ``` 3 3 5 4 1 3 4 1 5 5 1 3 4 1 1 5 2 1 6 5 2 3 4 3 3 4 3 4 4 4 4 4 4 4 1 4 6 2 4 4[4]1 1 6 6 5 5 1 2 4 2 6 6 3 6 1 1 5 3 6 2 3 6 1 2 2 4 5 3 5 1 2 3 6 6 1 5 1 3 2 4 ``` the painted region again increases in size dramatically. Your task is to create a program that will take a 19-by-19 grid of colours from 1 to 6 as input, in whatever form you choose: ``` 4 5 1 1 2 2 1 6 2 6 3 4 2 3 2 3 1 6 3 4 2 6 3 4 4 5 6 4 4 5 3 3 3 3 5 4 3 4 2 3 5 2 2 5 5 1 2 6 2 6 6 2 1 6 6 1 2 4 6 5 5 5 5 4 1 6 6 3 2 6 4 2 6 3 6 6 1 6 4 4 4 4 6 4 2 5 5 3 2 2 4 1 5 2 5 1 6 2 1 5 1 6 4 4 1 5 1 3 4 5 2 3 4 1 3 3 5 3 2 2 2 4 2 1 6 6 6 6 1 4 5 2 5 1 6 1 3 2 4 1 3 3 4 6 5 1 5 5 3 4 3 3 4 4 1 5 5 1 4 6 3 3 4 5 5 6 1 6 2 6 4 1 4 2 5 6 5 5 3 2 5 5 5 3 6 1 4 4 6 6 4 6 6 2 6 6 2 4 2 6 1 5 6 2 3 3 4 3 6 6 1 3 6 3 5 5 3 6 1 3 4 4 5 1 2 6 4 3 2 6 1 3 2 4 2 6 1 1 5 2 6 6 6 6 3 3 3 3 4 5 4 6 6 3 3 4 1 1 6 4 5 1 3 4 1 2 4 2 6 4 1 5 3 6 4 3 4 5 4 2 1 1 4 1 1 4 2 4 1 5 2 2 3 6 6 6 5 2 5 4 5 4 5 1 5 6 2 3 4 6 5 4 1 3 2 3 2 1 3 6 2 2 4 6 5 4 1 3 2 2 1 1 1 6 1 2 6 2 5 6 4 5 5 1 1 4 2 6 2 5 6 1 3 3 4 1 6 1 2 1 2 ``` and return a sequence of colours that the center square will change to each turn, again in the format of your choosing: ``` 263142421236425431645152623645465646213545631465 ``` At the end of each sequence of moves, the squares in the 19-by-19 grid must all be the same colour. Your program must be entirely deterministic; pseudorandom solutions are allowed, but the program must generate the same output for the same test case every time. The winning program will take the fewest total number of steps to solve all 100,000 test cases found in [this file](https://github.com/joezeng/pcg-se-files/raw/master/floodtest.tar.gz) (zipped text file, 14.23 MB). If two solutions take the same number of steps (e.g. if they both found the optimal strategy), the shorter program will win. --- BurntPizza has written a program in Java to verify the test results. To use this program, run your submission and pipe the output to a file called `steps.txt`. Then, run this program with `steps.txt` and the `floodtest` file in the same directory. If your entry is valid and produces correct solutions for all the files, it should pass all the tests and return `All boards solved successfully.` ``` import java.io.*; import java.util.*; public class PainterVerifier { public static void main(String[] args) throws FileNotFoundException { char[] board = new char[361]; Scanner s = new Scanner(new File("steps.txt")); Scanner b = new Scanner(new File("floodtest")); int lineNum = 0; caseloop: while (b.hasNextLine()) { for (int l = 0; l < 19; l++) { String lineb = b.nextLine(); if (lineb.isEmpty()) continue caseloop; System.arraycopy(lineb.toCharArray(), 0, board, l * 19, 19); } String line = s.nextLine(); if (line.isEmpty()) continue; char[] steps = line.toCharArray(); Stack<Integer> nodes = new Stack<Integer>(); for (char c : steps) { char targetColor = board[180]; char replacementColor = c; nodes.push(180); while (!nodes.empty()) { int n = nodes.pop(); if (n < 0 || n > 360) continue; if (board[n] == targetColor) { board[n] = replacementColor; if (n % 19 > 0) nodes.push(n - 1); if (n % 19 < 18) nodes.push(n + 1); if (n / 19 > 0) nodes.push(n - 19); if (n / 19 < 18) nodes.push(n + 19); } } } char center = board[180]; for (char c : board) if (c != center) { s.close(); b.close(); System.out.println("\nIncomplete board found!\n\tOn line " + lineNum + " of steps.txt"); System.exit(0); } if (lineNum % 5000 == 0) System.out.printf("Verification %d%c complete...\n", lineNum * 100 / 100000, '%'); lineNum++; } s.close(); b.close(); System.out.println("All boards solved successfully."); } } ``` --- Also, a scoreboard, since the results aren't actually sorted by score and here it actually matters a lot: 1. [1,985,078](https://codegolf.stackexchange.com/a/158273/7110) - smack42, Java 2. [2,075,452](https://codegolf.stackexchange.com/a/114172/18957) - user1502040, C 3. [2,098,382](https://codegolf.stackexchange.com/a/26917/7110) - tigrou, C# 4. [2,155,834](https://codegolf.stackexchange.com/a/26608/7110) - CoderTao, C# 5. [2,201,995](https://codegolf.stackexchange.com/a/26368/7110) - MrBackend, Java 6. [2,383,569](https://codegolf.stackexchange.com/a/26455/7110) - CoderTao, C# 7. [2,384,020](https://codegolf.stackexchange.com/a/26373/7110) - Herjan, C 8. [2,403,189](https://codegolf.stackexchange.com/a/26534/7110) - Origineil, Java 9. [2,445,761](https://codegolf.stackexchange.com/a/26373/7110) - Herjan, C 10. [2,475,056](https://codegolf.stackexchange.com/a/26341/7110) - Jeremy List, Haskell 11. [2,480,714](https://codegolf.stackexchange.com/a/26255/7110) - SteelTermite, C (2,395 bytes) 12. [2,480,714](https://codegolf.stackexchange.com/a/26244/7110) - Herjan, Java (4,702 bytes) 13. [2,588,847](https://codegolf.stackexchange.com/a/26331/7110) - BurntPizza, Java (2,748 bytes) 14. [2,588,847](https://codegolf.stackexchange.com/a/26795/7110) - Gero3, node.js (4,641 bytes) 15. [2,979,145](https://codegolf.stackexchange.com/a/26813/7110) - Teun Pronk, Delphi XE3 16. [4,780,841](https://codegolf.stackexchange.com/a/26313/7110) - BurntPizza, Java 17. [10,800,000](https://codegolf.stackexchange.com/a/26233/7110) - Joe Z., Python [Answer] # C# - 2,098,382 steps I try many things, most of them fail and just didn't work at all, until recently. I got something interesting enough to post an answer. There is certainly ways to improve this further more. I think going under the 2M steps might be possible. It took approx `7 hours` to generate results. Here is a txt file with all solutions, in case someone want to check them : [results.zip](https://anonfiles.com/file/25e29d3ec19b03fac9c1f8997a5596fc) ``` using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace FloodPaintAI { class Node { public byte Value; //1-6 public int Index; //unique identifier, used for easily deepcopying the graph public List<Node> Neighbours; public List<Tuple<int, int>> NeighboursPositions; //used by BuildGraph() public int Depth; //used by GetSumDistances() public bool Checked; // public Node(byte value, int index) { Value = value; Index = index; } public Node(Node node) { Value = node.Value; Index = node.Index; } } class Board { private const int SIZE = 19; private const int STARTPOSITION = 9; public Node Root; //root of graph. each node is a set of contiguous, same color square public List<Node> Nodes; //all nodes in the graph, used for deep copying public int EstimatedCost; //estimated cost, used by A* Pathfinding public List<byte> Solution; public Board(StreamReader input) { byte[,] board = new byte[SIZE, SIZE]; for(int j = 0 ; j < SIZE ; j++) { string line = input.ReadLine(); for(int i = 0 ; i < SIZE ; i++) { board[j, i] = byte.Parse(line[i].ToString()); } } Solution = new List<byte>(); BuildGraph(board); } public Board(Board boardToCopy) { //copy the graph Nodes = new List<Node>(boardToCopy.Nodes.Count); foreach(Node nodeToCopy in boardToCopy.Nodes) { Node node = new Node(nodeToCopy); Nodes.Add(node); } //copy "Neighbours" property for(int i = 0 ; i < boardToCopy.Nodes.Count ; i++) { Node node = Nodes[i]; Node nodeToCopy = boardToCopy.Nodes[i]; node.Neighbours = new List<Node>(nodeToCopy.Neighbours.Count); foreach(Node neighbour in nodeToCopy.Neighbours) { node.Neighbours.Add(Nodes[neighbour.Index]); } } Root = Nodes[boardToCopy.Root.Index]; EstimatedCost = boardToCopy.EstimatedCost; Solution = new List<byte>(boardToCopy.Solution); } private void BuildGraph(byte[,] board) { int[,] nodeIndexes = new int[SIZE, SIZE]; Nodes = new List<Node>(); //check how much sets we have (1st pass) for(int j = 0 ; j < SIZE ; j++) { for(int i = 0 ; i < SIZE ; i++) { if(nodeIndexes[j, i] == 0) //not already visited { Node newNode = new Node(board[j, i], Nodes.Count); newNode.NeighboursPositions = new List<Tuple<int, int>>(); Nodes.Add(newNode); BuildGraphFloodFill(board, nodeIndexes, newNode, i, j, board[j, i]); } } } //set neighbours and root (2nd pass) foreach(Node node in Nodes) { node.Neighbours = new List<Node>(); node.Neighbours.AddRange(node.NeighboursPositions.Select(x => nodeIndexes[x.Item2, x.Item1]).Distinct().Select(x => Nodes[x - 1])); node.NeighboursPositions = null; } Root = Nodes[nodeIndexes[STARTPOSITION, STARTPOSITION] - 1]; } private void BuildGraphFloodFill(byte[,] board, int[,] nodeIndexes, Node node, int startx, int starty, byte floodvalue) { Queue<Tuple<int, int>> queue = new Queue<Tuple<int, int>>(); queue.Enqueue(new Tuple<int, int>(startx, starty)); while(queue.Count > 0) { Tuple<int, int> position = queue.Dequeue(); int x = position.Item1; int y = position.Item2; if(x >= 0 && x < SIZE && y >= 0 && y < SIZE) { if(nodeIndexes[y, x] == 0 && board[y, x] == floodvalue) { nodeIndexes[y, x] = node.Index + 1; queue.Enqueue(new Tuple<int, int>(x + 1, y)); queue.Enqueue(new Tuple<int, int>(x - 1, y)); queue.Enqueue(new Tuple<int, int>(x, y + 1)); queue.Enqueue(new Tuple<int, int>(x, y - 1)); } if(board[y, x] != floodvalue) node.NeighboursPositions.Add(position); } } } public int GetEstimatedCost() { Board current = this; //copy current board and play the best color until the end. //number of moves required to go the end is the heuristic //estimated cost = current cost + heuristic while(!current.IsSolved()) { int minSumDistance = int.MaxValue; Board minBoard = null; //find color which give the minimum sum of distance from root to each other node foreach(byte i in current.Root.Neighbours.Select(x => x.Value).Distinct()) { Board copy = new Board(current); copy.Play(i); int distance = copy.GetSumDistances(); if(distance < minSumDistance) { minSumDistance = distance; minBoard = copy; } } current = minBoard; } return current.Solution.Count; } public int GetSumDistances() { //get sum of distances from root to each other node, using BFS int sumDistances = 0; //reset marker foreach(Node n in Nodes) { n.Checked = false; } Queue<Node> queue = new Queue<Node>(); Root.Checked = true; Root.Depth = 0; queue.Enqueue(Root); while(queue.Count > 0) { Node current = queue.Dequeue(); foreach(Node n in current.Neighbours) { if(!n.Checked) { n.Checked = true; n.Depth = current.Depth + 1; sumDistances += n.Depth; queue.Enqueue(n); } } } return sumDistances; } public void Play(byte value) { //merge root node with other neighbours nodes, if color is matching Root.Value = value; List<Node> neighboursToRemove = Root.Neighbours.Where(x => x.Value == value).ToList(); List<Node> neighboursToAdd = neighboursToRemove.SelectMany(x => x.Neighbours).Except((new Node[] { Root }).Concat(Root.Neighbours)).ToList(); foreach(Node n in neighboursToRemove) { foreach(Node m in n.Neighbours) { m.Neighbours.Remove(n); } Nodes.Remove(n); } foreach(Node n in neighboursToAdd) { Root.Neighbours.Add(n); n.Neighbours.Add(Root); } //re-synchronize node index for(int i = 0 ; i < Nodes.Count ; i++) { Nodes[i].Index = i; } Solution.Add(value); } public bool IsSolved() { //return Nodes.Count == 1; return Root.Neighbours.Count == 0; } } class Program { public static List<byte> Solve(Board input) { //A* Pathfinding LinkedList<Board> open = new LinkedList<Board>(); input.EstimatedCost = input.GetEstimatedCost(); open.AddLast(input); while(open.Count > 0) { Board current = open.First.Value; open.RemoveFirst(); if(current.IsSolved()) { return current.Solution; } else { //play all neighbours nodes colors foreach(byte i in current.Root.Neighbours.Select(x => x.Value).Distinct()) { Board newBoard = new Board(current); newBoard.Play(i); newBoard.EstimatedCost = newBoard.GetEstimatedCost(); //insert board to open list bool inserted = false; for(LinkedListNode<Board> node = open.First ; node != null ; node = node.Next) { if(node.Value.EstimatedCost > newBoard.EstimatedCost) { open.AddBefore(node, newBoard); inserted = true; break; } } if(!inserted) open.AddLast(newBoard); } } } throw new Exception(); //no solution found, impossible } public static void Main(string[] args) { using (StreamReader sr = new StreamReader("floodtest")) { while(!sr.EndOfStream) { List<Board> boards = new List<Board>(); while(!sr.EndOfStream && boards.Count < 100) { Board board = new Board(sr); sr.ReadLine(); //skip empty line boards.Add(board); } List<byte>[] solutions = new List<byte>[boards.Count]; Parallel.For(0, boards.Count, i => { solutions[i] = Solve(boards[i]); }); foreach(List<byte> solution in solutions) { Console.WriteLine(string.Join(string.Empty, solution)); } } } } } } ``` More details about how it works : It use [A\* Pathfinding](http://en.wikipedia.org/wiki/A*_search_algorithm) algorithm. What is difficult is to find a good `heuristic`. If the `heuristic` it underestimate the cost, it will perform like almost like [Dijkstra](http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm) algorithm and because of complexity of a 19x19 board with 6 colors it will run forever. If it overestimate the cost it will converge quickly to a solution but won't give good ones at all (something like 26 moves were 19 was possible). Finding the perfect `heuristic` that give the exact remaining amount of steps to reach solution would be the best (it would be fast and would give best possible solution). It is (unless i'm wrong) impossible. It actually require to solve the board itself first, while this is what you are actually trying to do (chicken and egg problem) I tried many things, here is what worked for the `heuristic`: * I build a [graph](http://en.wikipedia.org/wiki/Graph_%28data_structure%29) of current board to evaluate. Each `node` represent a set of contiguous, same colored squares. Using that `graph`, I can easily calculate the exact minimal distance from center to any other node. For example distance from center to top left would be 10, because at minimum 10 colors separate them. * For calculating `heuristic` : I play the current board until the end. For each step, I choose the color which will minimize the sum of distances from root to all other nodes. * Number of moves needed to reach that end is the `heuristic`. * `Estimated cost` (used by A\*) = `moves so far` + `heuristic` It is not perfect as it slightly overestimate the cost (thus non optimal solution is found). Anyway it is fast to calculate and give good results. I was able to get huge speed improvment by using graph to perform all operations. At begining I had a `2-dimension` array. I flood it and recalculate graph when needed (eg : to calculate the heuristic). Now everything is done using the graph, which calculated only at the beginning. To simulate steps, flood fill is no more needed, I merge nodes instead. This is a lot faster. [Answer] # Python – 10,800,000 steps As a last-place reference solution, consider this sequence: ``` print "123456" * 18 ``` Cycling through all the colours `n` times means that every square `n` steps away will be guaranteed to be of the same colour as the center square. Every square is at most 18 steps away from the center, so 18 cycles will guarantee all the squares being the same colour. Most likely it will finish in less than that, but the program is not required to stop as soon as all squares are the same colour; it's just much more beneficial to do so. This constant procedure is 108 steps per test case, for a total of 10,800,000. [Answer] # Java - 2,480,714 steps I made a little mistake before (I put one crucial sentence before a loop instead of in the loop: ``` import java.io.*; public class HerjanPaintAI { BufferedReader r; String[] map = new String[19]; char[][] colors = new char[19][19]; boolean[][] reached = new boolean[19][19], checked = new boolean[19][19]; int[] colorCounter = new int[6]; String answer = ""; int mapCount = 0, moveCount = 0; public HerjanPaintAI(){ nextMap(); while(true){ int bestMove = nextRound(); answer += bestMove; char t = Character.forDigit(bestMove, 10); for(int x = 0; x < 19; x++){ for(int y = 0; y < 19; y++){ if(reached[x][y]){ colors[x][y] = t; }else if(checked[x][y]){ if(colors[x][y] == t){ reached[x][y] = true; } } } } boolean gameOver = true; for(int x = 0; x < 19; x++){ for(int y = 0; y < 19; y++){ if(!reached[x][y]){ gameOver = false; break; } } } for(int x = 0; x < 19; x++){ for(int y = 0; y < 19; y++){ checked[x][y] = false; } } for(int i = 0; i < 6; i++) colorCounter[i] = 0; if(gameOver) nextMap(); } } int nextRound(){ for(int x = 0; x < 19; x++){ for(int y = 0; y < 19; y++){ if(reached[x][y]){//check what numbers are next to the reached numbers... check(x, y); } } } int[] totalColorCount = new int[6]; for(int x = 0; x < 19; x++){ for(int y = 0; y < 19; y++){ totalColorCount[Character.getNumericValue(colors[x][y])-1]++; } } for(int i = 0; i < 6; i++){ if(totalColorCount[i] != 0 && totalColorCount[i] == colorCounter[i]){//all of this color can be reached return i+1; } } int index = -1, number = 0; for(int i = 0; i < 6; i++){ if(colorCounter[i] > number){ index = i; number = colorCounter[i]; } } return index+1; } void check(int x, int y){ if(x<18) handle(x+1, y, x, y); if(x>0) handle(x-1, y, x, y); if(y<18) handle(x, y+1, x, y); if(y>0) handle(x, y-1, x, y); } void handle(int x2, int y2, int x, int y){ if(!reached[x2][y2] && !checked[x2][y2]){ checked[x2][y2] = true; if(colors[x2][y2] == colors[x][y]){ reached[x2][y2] = true; check(x2, y2); }else{ colorCounter[Character.getNumericValue(colors[x2][y2])-1]++; checkAround(x2, y2); } } } void checkAround(int x2, int y2){ if(x2<18) handleAround(x2+1, y2, x2, y2); if(x2>0) handleAround(x2-1, y2, x2, y2); if(y2<18) handleAround(x2, y2+1, x2, y2); if(y2>0) handleAround(x2, y2-1, x2, y2); } void handleAround(int x2, int y2, int x, int y){ if(!reached[x2][y2] && !checked[x2][y2]){ if(colors[x2][y2] == colors[x][y]){ checked[x2][y2] = true; colorCounter[Character.getNumericValue(colors[x2][y2])-1]++; checkAround(x2, y2); } } } void nextMap(){ moveCount += answer.length(); System.out.println(answer); answer = ""; for(int x = 0; x < 19; x++){ for(int y = 0; y < 19; y++){ reached[x][y] = false; } } reached[9][9] = true; try { if(r == null) r = new BufferedReader(new FileReader("floodtest")); for(int i = 0; i < 19; i++){ map[i] = r.readLine(); } r.readLine();//empty line if(map[0] == null){ System.out.println("Maps solved: " + mapCount + " Steps: " + moveCount); r.close(); System.exit(0); } } catch (Exception e) {e.printStackTrace();} mapCount++; for(int x = 0; x < 19; x++){ colors[x] = map[x].toCharArray(); } } public static void main(String[] a){ new HerjanPaintAI(); } } ``` [Answer] # Java - 1,985,078 steps <https://github.com/smack42/ColorFill> Another late entry. The result file containing the 1,985,078 steps can be found [here](https://github.com/smack42/ColorFill/raw/master/codegolf26232/steps.txt). **Some background info:** I discovered this challenge some years ago, when I started programming my own clone of the game Flood-it. **"best-of incomplete" DFS and A\* algorithm** From the beginning, I wanted to create a good solver algorithm for this game. Over time, I could improve my solver by including several strategies that did different incomplete searches (similar to the ones used in the other programs here) and by using the best result of those strategies for each solution. I even re-implemented [tigrou's A\* algorithm](https://codegolf.stackexchange.com/a/26917/7110) in Java and added it to my solver to achieve overall better solutions than tigrou's result. **exhaustive DFS algorithm** Then I focused on an algorithm that always finds the optimal solutions. I spent a lot of effort to optimize my exhaustive depth-first search strategy. To speed up the search, I included a hashmap that stores all explored states, so that the search can avoid exploring them again. While this algorithm works fine and solves all 14x14 puzzles quickly enough, it uses too much memory and runs very slowly with the 19x19 puzzles in this code challenge. **Puchert A\* algorithm** A few months ago I was contacted to look at the [Flood-It solver by Aaron and Simon Puchert](https://github.com/aaronpuchert/floodit). That program uses an A\*-type algorithm with an admissible heuristic (in contrast to tigrou's) and move pruning similar to Jump-Point Search. I quickly noticed that this program is **very fast** and finds the **optimal solutions**! Of course, I had to re-implement this great algorithm and added it to my program. I made an effort to optimize my Java program to run about as fast as the original C++ program by the Puchert brothers. Then I decided to make an attempt at the 100,000 test cases of this challenge. On my machine the program ran for more than 120 hours to find the 1,985,078 steps, using my implementation of the **Puchert A\* algorithm**. This is to be the **best possible solution** to this challenge, unless there are some bugs in the program that would result in sub-optimal solutions. Any feedback is welcome! edit: added relevant parts of the code here: class *AStarPuchertStrategy* ``` /** * a specific strategy for the AStar (A*) solver. * <p> * the idea is taken from the program "floodit" by Aaron and Simon Puchert, * which can be found at <a>https://github.com/aaronpuchert/floodit</a> */ public class AStarPuchertStrategy implements AStarStrategy { private final Board board; private final ColorAreaSet visited; private ColorAreaSet current, next; private final short[] numCaNotFilledInitial; private final short[] numCaNotFilled; public AStarPuchertStrategy(final Board board) { this.board = board; this.visited = new ColorAreaSet(board); this.current = new ColorAreaSet(board); this.next = new ColorAreaSet(board); this.numCaNotFilledInitial = new short[board.getNumColors()]; for (final ColorArea ca : board.getColorAreasArray()) { ++this.numCaNotFilledInitial[ca.getColor()]; } this.numCaNotFilled = new short[board.getNumColors()]; } /* (non-Javadoc) * @see colorfill.solver.AStarStrategy#setEstimatedCost(colorfill.solver.AStarNode) */ @Override public void setEstimatedCost(final AStarNode node) { // quote from floodit.cpp: int State::computeValuation() // (in branch "performance") // // We compute an admissible heuristic recursively: If there are no nodes // left, return 0. Furthermore, if a color can be eliminated in one move // from the current position, that move is an optimal move and we can // simply use it. Otherwise, all moves fill a subset of the neighbors of // the filled nodes. Thus, filling that layer gets us at least one step // closer to the end. node.copyFloodedTo(this.visited); System.arraycopy(this.numCaNotFilledInitial, 0, this.numCaNotFilled, 0, this.numCaNotFilledInitial.length); { final ColorAreaSet.FastIteratorColorAreaId iter = this.visited.fastIteratorColorAreaId(); int nextId; while ((nextId = iter.nextOrNegative()) >= 0) { --this.numCaNotFilled[this.board.getColor4Id(nextId)]; } } // visit the first layer of neighbors, which is never empty, i.e. the puzzle is not solved yet node.copyNeighborsTo(this.current); this.visited.addAll(this.current); int completedColors = 0; { final ColorAreaSet.FastIteratorColorAreaId iter = this.current.fastIteratorColorAreaId(); int nextId; while ((nextId = iter.nextOrNegative()) >= 0) { final byte nextColor = this.board.getColor4Id(nextId); if (--this.numCaNotFilled[nextColor] == 0) { completedColors |= 1 << nextColor; } } } int distance = 1; while(!this.current.isEmpty()) { this.next.clear(); final ColorAreaSet.FastIteratorColorAreaId iter = this.current.fastIteratorColorAreaId(); int thisCaId; if (0 != completedColors) { // We can eliminate colors. Do just that. // We also combine all these elimination moves. distance += Integer.bitCount(completedColors); final int prevCompletedColors = completedColors; completedColors = 0; while ((thisCaId = iter.nextOrNegative()) >= 0) { final ColorArea thisCa = this.board.getColorArea4Id(thisCaId); if ((prevCompletedColors & (1 << thisCa.getColor())) != 0) { // completed color // expandNode() for (final int nextCaId : thisCa.getNeighborsIdArray()) { if (!this.visited.contains(nextCaId)) { this.visited.add(nextCaId); this.next.add(nextCaId); final byte nextColor = this.board.getColor4Id(nextCaId); if (--this.numCaNotFilled[nextColor] == 0) { completedColors |= 1 << nextColor; } } } } else { // non-completed color // move node to next layer this.next.add(thisCaId); } } } else { // Nothing found, do the color-blind pseudo-move // Expand current layer of nodes. ++distance; while ((thisCaId = iter.nextOrNegative()) >= 0) { final ColorArea thisCa = this.board.getColorArea4Id(thisCaId); // expandNode() for (final int nextCaId : thisCa.getNeighborsIdArray()) { if (!this.visited.contains(nextCaId)) { this.visited.add(nextCaId); this.next.add(nextCaId); final byte nextColor = this.board.getColor4Id(nextCaId); if (--this.numCaNotFilled[nextColor] == 0) { completedColors |= 1 << nextColor; } } } } } // Move the next layer into the current. final ColorAreaSet tmp = this.current; this.current = this.next; this.next = tmp; } node.setEstimatedCost(node.getSolutionSize() + distance); } } ``` part of class *AStarSolver* ``` private void executeInternalPuchert(final ColorArea startCa) throws InterruptedException { final Queue<AStarNode> open = new PriorityQueue<AStarNode>(AStarNode.strongerComparator()); open.offer(new AStarNode(this.board, startCa)); AStarNode recycleNode = null; while (open.size() > 0) { if (Thread.interrupted()) { throw new InterruptedException(); } final AStarNode currentNode = open.poll(); if (currentNode.isSolved()) { this.addSolution(currentNode.getSolution()); return; } else { // play all possible colors int nextColors = currentNode.getNeighborColors(this.board); while (0 != nextColors) { final int l1b = nextColors & -nextColors; // Integer.lowestOneBit() final int clz = Integer.numberOfLeadingZeros(l1b); // hopefully an intrinsic function using instruction BSR / LZCNT / CLZ nextColors ^= l1b; // clear lowest one bit final byte color = (byte)(31 - clz); final AStarNode nextNode = currentNode.copyAndPlay(color, recycleNode, this.board); if (null != nextNode) { recycleNode = null; this.strategy.setEstimatedCost(nextNode); open.offer(nextNode); } } } recycleNode = currentNode; } } ``` part of class *AStarNode* ``` /** * check if this color can be played. (avoid duplicate moves) * the idea is taken from the program "floodit" by Aaron and Simon Puchert, * which can be found at <a>https://github.com/aaronpuchert/floodit</a> * @param nextColor * @return */ private boolean canPlay(final byte nextColor, final List<ColorArea> nextColorNeighbors) { final byte currColor = this.solution[this.solutionSize]; // did the previous move add any new "nextColor" neighbors? boolean newNext = false; next: for (final ColorArea nextColorNeighbor : nextColorNeighbors) { for (final ColorArea prevNeighbor : nextColorNeighbor.getNeighborsArray()) { if ((prevNeighbor.getColor() != currColor) && this.flooded.contains(prevNeighbor)) { continue next; } } newNext = true; break next; } if (!newNext) { if (nextColor < currColor) { return false; } else { // should nextColor have been played before currColor? for (final ColorArea nextColorNeighbor : nextColorNeighbors) { for (final ColorArea prevNeighbor : nextColorNeighbor.getNeighborsArray()) { if ((prevNeighbor.getColor() == currColor) && !this.flooded.contains(prevNeighbor)) { return false; } } } return true; } } else { return true; } } /** * try to re-use the given node or create a new one * and then play the given color in the result node. * @param nextColor * @param recycleNode * @return */ public AStarNode copyAndPlay(final byte nextColor, final AStarNode recycleNode, final Board board) { final List<ColorArea> nextColorNeighbors = new ArrayList<ColorArea>(128); // constant, arbitrary initial capacity final ColorAreaSet.FastIteratorColorAreaId iter = this.neighbors.fastIteratorColorAreaId(); int nextId; while ((nextId = iter.nextOrNegative()) >= 0) { final ColorArea nextColorNeighbor = board.getColorArea4Id(nextId); if (nextColorNeighbor.getColor() == nextColor) { nextColorNeighbors.add(nextColorNeighbor); } } if (!this.canPlay(nextColor, nextColorNeighbors)) { return null; } else { final AStarNode result; if (null == recycleNode) { result = new AStarNode(this); } else { // copy - compare copy constructor result = recycleNode; result.flooded.copyFrom(this.flooded); result.neighbors.copyFrom(this.neighbors); System.arraycopy(this.solution, 0, result.solution, 0, this.solutionSize + 1); result.solutionSize = this.solutionSize; //result.estimatedCost = this.estimatedCost; // not necessary to copy } // play - compare method play() for (final ColorArea nextColorNeighbor : nextColorNeighbors) { result.flooded.add(nextColorNeighbor); result.neighbors.addAll(nextColorNeighbor.getNeighborsIdArray()); } result.neighbors.removeAll(result.flooded); result.solution[++result.solutionSize] = nextColor; return result; } } ``` [Answer] **C - 2,075,452** I know I'm extremely late to the party, but I saw this challenge and wanted to have a go. ``` #include <assert.h> #include <math.h> #include <stdio.h> #include <stdint.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> uint64_t rand_state; uint64_t rand_u64(void) { return (rand_state = rand_state * 6364136223846793005ULL + 1442695040888963407ULL); } uint64_t better_rand_u64(void) { uint64_t r = rand_u64(); r ^= ((r >> 32) >> (r >> 60)); return r + 1442695040888963407ULL; } uint32_t rand_u32(void) {return rand_u64() >> 32;} float normal(float mu, float sigma) { uint64_t t = 0; for (int i = 0; i < 6; i++) { uint64_t r = rand_u64(); uint32_t a = r; uint32_t b = r >> 32; t += a; t += b; } return ((float)t / (float)UINT32_MAX - 6) * sigma + mu; } typedef struct { uint8_t x; uint8_t y; } Position; #define ncolors 6 #define len 19 #define cells (len * len) #define max_steps (len * (ncolors - 1)) #define center_x 9 #define center_y 9 #define center ((Position){center_x, center_y}) uint64_t zobrist_table[len][len]; void init_zobrist() { for (int y = 0; y < len; y++) { for (int x = 0; x < len; x++) { zobrist_table[y][x] = better_rand_u64(); } } } typedef struct { uint64_t hash; uint8_t grid[len][len]; bool interior[len][len]; int boundary_size; Position boundary[cells]; } Grid; void transition(Grid* grid, uint8_t color, int* surrounding_counts) { int i = 0; while (i < grid->boundary_size) { Position p = grid->boundary[i]; uint8_t x = p.x; uint8_t y = p.y; bool still_boundary = false; for (int dx = -1; dx <= 1; dx++) { for (int dy = -1; dy <= 1; dy++) { if (!(dx == 0 || dy == 0)) { continue; } int8_t x1 = x + dx; if (!(0 <= x1 && x1 < len)) { continue; } int8_t y1 = y + dy; if (!(0 <= y1 && y1 < len)) { continue; } if (grid->interior[y1][x1]) { continue; } uint8_t color1 = grid->grid[y1][x1]; if (color1 == color) { grid->boundary[grid->boundary_size++] = (Position){x1, y1}; grid->interior[y1][x1] = true; grid->hash ^= zobrist_table[y1][x1]; } else { surrounding_counts[color1]++; still_boundary = true; } } } if (still_boundary) { i += 1; } else { grid->boundary[i] = grid->boundary[--grid->boundary_size]; } } } void reset_grid(Grid* grid, int* surrounding_counts) { grid->hash = 0; memset(surrounding_counts, 0, ncolors * sizeof(int)); memset(&grid->interior, 0, sizeof(grid->interior)); grid->interior[center_y][center_x] = true; grid->boundary_size = 0; grid->boundary[grid->boundary_size++] = center; transition(grid, grid->grid[center_y][center_x], surrounding_counts); } bool load_grid(FILE* fp, Grid* grid) { memset(grid, 0, sizeof(*grid)); char buf[19 + 2]; size_t row = 0; while ((fgets(buf, sizeof(buf), fp)) && row < 19) { if (strlen(buf) != 20) { break; } for (int i = 0; i < 19; i++) { if (!('1' <= buf[i] && buf[i] <= '6')) { return false; } grid->grid[row][i] = buf[i] - '1'; } row++; } return row == 19; } typedef struct Node Node; struct Node { uint64_t hash; float visit_counts[ncolors]; float mean_cost[ncolors]; float sse[ncolors]; }; #define iters 15000 #define pool_size 32768 #define pool_nodes (pool_size + 100) #define pool_mask (pool_size - 1) Node pool[pool_nodes]; void init_node(Node* node, uint64_t hash, int* surrounding_counts) { node->hash = hash; for (int i = 0; i < ncolors; i++) { if (surrounding_counts[i]) { node->visit_counts[i] = 1; node->mean_cost[i] = 20; node->sse[i] = 400; } } } Node* lookup_node(uint64_t hash) { size_t index = hash & pool_mask; for (int i = index;; i++) { uint64_t h = pool[i].hash; if (h == hash || !h) { return pool + i; } } } int rollout(Grid* grid, int* surrounding_counts, char* solution) { for (int i = 0;; i++) { int nonzero = 0; uint8_t colors[6]; for (int i = 0; i < ncolors; i++) { if (surrounding_counts[i]) { colors[nonzero++] = i; } } if (!nonzero) { return i; } uint8_t color = colors[rand_u32() % nonzero]; *(solution++) = color; assert(grid->boundary_size); memset(surrounding_counts, 0, 6 * sizeof(int)); transition(grid, color, surrounding_counts); } } int simulate(Node* node, Grid* grid, int depth, char* solution) { float best_cost = INFINITY; uint8_t best_color = 255; for (int color = 0; color < ncolors; color++) { float n = node->visit_counts[color]; if (node->visit_counts[color] == 0) { continue; } float sigma = sqrt(node->sse[color] / (n * n)); float cost = node->mean_cost[color]; cost = normal(cost, sigma); if (cost < best_cost) { best_color = color; best_cost = cost; } } if (best_color == 255) { return 0; } *solution++ = best_color; int score; int surrounding_counts[ncolors] = {0}; transition(grid, best_color, surrounding_counts); Node* child = lookup_node(grid->hash); if (!child->hash) { init_node(child, grid->hash, surrounding_counts); score = rollout(grid, surrounding_counts, solution); } else { score = simulate(child, grid, depth + 1, solution); } score++; float n1 = ++node->visit_counts[best_color]; float u0 = node->mean_cost[best_color]; float u1 = node->mean_cost[best_color] = u0 + (score - u0) / n1; node->sse[best_color] += (score - u0) * (score - u1); return score; } int main(void) { FILE* fp; if (!(fp = fopen("floodtest", "r"))) { return 1; } Grid grid; init_zobrist(); while (load_grid(fp, &grid)) { memset(pool, 0, sizeof(pool)); int surrounding_counts[ncolors] = {0}; reset_grid(&grid, surrounding_counts); Node root = {0}; init_node(&root, grid.hash, surrounding_counts); char solution[max_steps] = {0}; char best_solution[max_steps] = {0}; int min_score = INT_MAX; uint64_t prev_hash = 0; uint64_t hash = 0; int same_count = 0; for (int iter = 0; iter < iters; iter++) { reset_grid(&grid, surrounding_counts); int score = simulate(&root, &grid, 1, solution); if (score < min_score) { min_score = score; memcpy(best_solution, solution, score); } hash = 0; for (int i = 0; i < score; i++) { hash ^= zobrist_table[i%len][(int)solution[i]]; } if (hash == prev_hash) { same_count++; if (same_count >= 10) { break; } } else { same_count = 0; prev_hash = hash; } } int i; for (i = 0; i < min_score; i++) { best_solution[i] += '1'; } best_solution[i++] = '\n'; best_solution[i++] = '\0'; printf(best_solution); fflush(stdout); } return 0; } ``` The algorithm is based on Monte-Carlo Tree Search with Thompson sampling, and a transposition table to reduce the search space. It takes about 12 hours on my machine. If you want to check the results, you can find them at <https://dropfile.to/pvjYDMV>. [Answer] # Java - 2,434,108 2,588,847 steps Currently winning (~46K ahead of Herjan) as of 4/26 Welp, so not only did MrBackend beat me, but I found a bug which produced a deceptively good score. It's fixed now (was also in the verifier! Ack), but unfortunately I don't have any time at the moment to try and take back the crown. Will attempt later. This is based off of my other solution, but instead of painting with the color most common to the fill edges, it paints with the color that will result in exposing edges that have many adjacent squares of the same color. Call it LookAheadPainter. I'll golf it later if necessary. ``` import java.io.*; import java.util.*; public class LookAheadPainter { static final boolean PRINT_FULL_OUTPUT = true; public static void main(String[] a) throws IOException { int totalSteps = 0, numSolved = 0; char[] board = new char[361]; Scanner s = new Scanner(new File("floodtest")); long startTime = System.nanoTime(); caseloop: while (s.hasNextLine()) { for (int l = 0; l < 19; l++) { String line = s.nextLine(); if (line.isEmpty()) continue caseloop; System.arraycopy(line.toCharArray(), 0, board, l * 19, 19); } List<Character> colorsUsed = new ArrayList<>(); for (;;) { FillResult fill = new FillResult(board, board[180], (char) 48, null); if (fill.nodesFilled.size() == 361) break; int[] branchSizes = new int[7]; for (int i = 1; i < 7; i++) { List<Integer> seeds = new ArrayList<>(); for (Integer seed : fill.edges) if (board[seed] == i + 48) seeds.add(seed); branchSizes[i] = new FillResult(fill.filledBoard, (char) (i + 48), (char) 48, seeds).nodesFilled.size(); } int maxSize = 0; char bestColor = 0; for (int i = 1; i < 7; i++) if (branchSizes[i] > maxSize) { maxSize = branchSizes[i]; bestColor = (char) (i + 48); } for (int i : fill.nodesFilled) board[i] = bestColor; colorsUsed.add(bestColor); totalSteps++; } numSolved++; if (PRINT_FULL_OUTPUT) { if (numSolved % 1000 == 0) System.out.println("Solved: " + numSolved); // So you know it's working String out = ""; for (Character c : colorsUsed) out += c; System.out.println(out); } } s.close(); System.out.println("\nTotal steps to solve all cases: " + totalSteps); System.out.printf("\nSolved %d test cases in %.2f seconds", numSolved, (System.nanoTime() - startTime) / 1000000000.); } private static class FillResult { Set<Integer> nodesFilled, edges; char[] filledBoard; FillResult(char[] board, char target, char replacement, List<Integer> seeds) { Stack<Integer> nodes = new Stack<>(); nodesFilled = new HashSet<>(); edges = new HashSet<>(); if (seeds == null) nodes.push(180); else for (int i : seeds) nodes.push(i); filledBoard = new char[361]; System.arraycopy(board, 0, filledBoard, 0, 361); while (!nodes.empty()) { int n = nodes.pop(); if (n < 0 || n > 360) continue; if (filledBoard[n] == target) { filledBoard[n] = replacement; nodesFilled.add(n); if (n % 19 > 0) nodes.push(n - 1); if (n % 19 < 18) nodes.push(n + 1); if (n / 19 > 0) nodes.push(n - 19); if (n / 19 < 18) nodes.push(n + 19); } else edges.add(n); } } } } ``` EDIT: I wrote a verifier, feel free to use, it expects a steps.txt file containing the steps your program outputs as well as the floodtest file: Edit-Edit: (See OP) If anyone finds a problem, please report it to me! [Answer] # C - 2,480,714 steps Still not optimal, but it is now faster and scores better. ``` #include <stdio.h> #include <string.h> #include <stdbool.h> char map[19][19], reach[19][19]; int reachsum[6], totalsum[6]; bool loadmap(FILE *fp) { char buf[19 + 2]; size_t row = 0; while (fgets(buf, sizeof buf, fp) && row < 19) { if (strlen(buf) != 20) break; memcpy(map[row++], buf, 19); } return row == 19; } void calcreach(bool first, size_t row, size_t col); void check(char c, bool first, size_t row, size_t col) { if (map[row][col] == c) calcreach(first, row, col); else if (first) calcreach(false, row, col); } void calcreach(bool first, size_t row, size_t col) { char c = map[row][col]; reach[row][col] = c; reachsum[c - '1']++; if (row < 18 && !reach[row + 1][col]) check(c, first, row + 1, col); if (col < 18 && !reach[row][col + 1]) check(c, first, row, col + 1); if (row > 0 && !reach[row - 1][col]) check(c, first, row - 1, col); if (col > 0 && !reach[row][col - 1]) check(c, first, row, col - 1); } void calctotal() { size_t row, col; for (row = 0; row < 19; row++) for (col = 0; col < 19; col++) totalsum[map[row][col] - '1']++; } void apply(char c) { char d = map[9][9]; size_t row, col; for (row = 0; row < 19; row++) for (col = 0; col < 19; col++) if (reach[row][col] == d) map[row][col] = c; } int main() { char c, best; size_t steps = 0; FILE *fp; if (!(fp = fopen("floodtest", "r"))) return 1; while (loadmap(fp)) { do { memset(reach, 0, sizeof reach); memset(reachsum, 0, sizeof reachsum); calcreach(true, 9, 9); if (reachsum[map[9][9] - '1'] == 361) break; memset(totalsum, 0, sizeof totalsum); calctotal(); reachsum[map[9][9] - '1'] = 0; for (best = 0, c = 0; c < 6; c++) { if (!reachsum[c]) continue; if (reachsum[c] == totalsum[c]) { best = c; break; } else if (reachsum[c] > reachsum[best]) { best = c; } } apply(best + '1'); } while (++steps); } fclose(fp); printf("steps: %zu\n", steps); return 0; } ``` [Answer] # Java - ~~2,245,529~~ 2,201,995 steps Parallel & caching tree search at depth 5, minimizing the number of "islands". Since the improvement from depth 4 to depth 5 was so small, I don't think there is much point in improving it much more. But if it were to need improvement, my gut feeling says to work with calculating the number of islands as a diff between two states, instead of recalculating everything. Currently outputs to stdout, until I know the verifier's input format. ``` import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.AbstractList; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveTask; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class FloodPaint { private static final ForkJoinPool FORK_JOIN_POOL = new ForkJoinPool(); public static void main(String[] arg) throws IOException, InterruptedException, ExecutionException { try (BufferedReader reader = new BufferedReader(new FileReader("floodtest"))) { int sum = 0; State initState = readNextInitState(reader); while (initState != null) { List<Integer> solution = generateSolution(initState); System.out.println(solution); sum += solution.size(); initState = readNextInitState(reader); } System.out.println(sum); } } private static State readNextInitState(BufferedReader reader) throws IOException { int[] initGrid = new int[State.DIM * State.DIM]; String line = reader.readLine(); while ((line != null) && line.isEmpty()) { line = reader.readLine(); } if (line == null) { return null; } for (int rowNo = 0; rowNo < State.DIM; ++rowNo) { for (int colNo = 0; colNo < State.DIM; ++colNo) { initGrid[(State.DIM * rowNo) + colNo] = line.charAt(colNo) - '0'; } line = reader.readLine(); } return new State(initGrid); } private static List<Integer> generateSolution(State initState) throws InterruptedException, ExecutionException { List<Integer> solution = new LinkedList<>(); StateFactory stateFactory = new StateFactory(); State state = initState; while (!state.isSolved()) { int num = findGoodNum(state, stateFactory); solution.add(num); state = state.getNextState(num, stateFactory); } return solution; } private static int findGoodNum(State state, StateFactory stateFactory) throws InterruptedException, ExecutionException { SolverTask task = new SolverTask(state, stateFactory); FORK_JOIN_POOL.invoke(task); return task.get(); } } class SolverTask extends RecursiveTask<Integer> { private static final int DEPTH = 5; private final State state; private final StateFactory stateFactory; SolverTask(State state, StateFactory stateFactory) { this.state = state; this.stateFactory = stateFactory; } @Override protected Integer compute() { try { Map<Integer,AnalyzerTask> tasks = new HashMap<>(); for (int num = 1; num <= 6; ++num) { if (num != state.getCenterNum()) { State nextState = state.getNextState(num, stateFactory); AnalyzerTask task = new AnalyzerTask(nextState, DEPTH - 1, stateFactory); tasks.put(num, task); } } invokeAll(tasks.values()); int bestValue = Integer.MAX_VALUE; int bestNum = -1; for (Map.Entry<Integer,AnalyzerTask> taskEntry : tasks.entrySet()) { int value = taskEntry.getValue().get(); if (value < bestValue) { bestValue = value; bestNum = taskEntry.getKey(); } } return bestNum; } catch (InterruptedException | ExecutionException ex) { throw new RuntimeException(ex); } } } class AnalyzerTask extends RecursiveTask<Integer> { private static final int DEPTH_THRESHOLD = 3; private final State state; private final int depth; private final StateFactory stateFactory; AnalyzerTask(State state, int depth, StateFactory stateFactory) { this.state = state; this.depth = depth; this.stateFactory = stateFactory; } @Override protected Integer compute() { return (depth < DEPTH_THRESHOLD) ? analyze() : split(); } private int analyze() { return analyze(state, depth); } private int analyze(State state, int depth) { if (state.isSolved()) { return -depth; } if (depth == 0) { return state.getNumIslands(); } int bestValue = Integer.MAX_VALUE; for (int num = 1; num <= 6; ++num) { if (num != state.getCenterNum()) { State nextState = state.getNextState(num, stateFactory); int nextValue = analyze(nextState, depth - 1); bestValue = Math.min(bestValue, nextValue); } } return bestValue; } private int split() { try { if (state.isSolved()) { return -depth; } Collection<AnalyzerTask> tasks = new ArrayList<>(5); for (int num = 1; num <= 6; ++num) { State nextState = state.getNextState(num, stateFactory); AnalyzerTask task = new AnalyzerTask(nextState, depth - 1, stateFactory); tasks.add(task); } invokeAll(tasks); int bestValue = Integer.MAX_VALUE; for (AnalyzerTask task : tasks) { int nextValue = task.get(); bestValue = Math.min(bestValue, nextValue); } return bestValue; } catch (InterruptedException | ExecutionException ex) { throw new RuntimeException(ex); } } } class StateFactory { private static final int INIT_CAPACITY = 40000; private static final float LOAD_FACTOR = 0.9f; private final ReadWriteLock cacheLock = new ReentrantReadWriteLock(); private final Map<List<Integer>,State> cache = new HashMap<>(INIT_CAPACITY, LOAD_FACTOR); State get(int[] grid) { List<Integer> stateKey = new IntList(grid); State state; cacheLock.readLock().lock(); try { state = cache.get(stateKey); } finally { cacheLock.readLock().unlock(); } if (state == null) { cacheLock.writeLock().lock(); try { state = cache.get(stateKey); if (state == null) { state = new State(grid); cache.put(stateKey, state); } } finally { cacheLock.writeLock().unlock(); } } return state; } } class State { static final int DIM = 19; private static final int CENTER_INDEX = ((DIM * DIM) - 1) / 2; private final int[] grid; private int numIslands; State(int[] grid) { this.grid = grid; numIslands = calcNumIslands(grid); } private static int calcNumIslands(int[] grid) { int numIslands = 0; BitSet uncounted = new BitSet(DIM * DIM); uncounted.set(0, DIM * DIM); int index = -1; while (!uncounted.isEmpty()) { index = uncounted.nextSetBit(index + 1); BitSet island = new BitSet(DIM * DIM); generateIsland(grid, index, grid[index], island); ++numIslands; uncounted.andNot(island); } return numIslands; } private static void generateIsland(int[] grid, int index, int num, BitSet island) { if ((grid[index] == num) && !island.get(index)) { island.set(index); if ((index % DIM) > 0) { generateIsland(grid, index - 1, num, island); } if ((index % DIM) < (DIM - 1)) { generateIsland(grid, index + 1, num, island); } if ((index / DIM) > 0) { generateIsland(grid, index - DIM, num, island); } if ((index / DIM) < (DIM - 1)) { generateIsland(grid, index + DIM, num, island); } } } int getCenterNum() { return grid[CENTER_INDEX]; } boolean isSolved() { return numIslands == 1; } int getNumIslands() { return numIslands; } State getNextState(int num, StateFactory stateFactory) { int[] nextGrid = grid.clone(); if (num != getCenterNum()) { flood(nextGrid, CENTER_INDEX, getCenterNum(), num); } State nextState = stateFactory.get(nextGrid); return nextState; } private static void flood(int[] grid, int index, int fromNum, int toNum) { if (grid[index] == fromNum) { grid[index] = toNum; if ((index % 19) > 0) { flood(grid, index - 1, fromNum, toNum); } if ((index % 19) < (DIM - 1)) { flood(grid, index + 1, fromNum, toNum); } if ((index / 19) > 0) { flood(grid, index - DIM, fromNum, toNum); } if ((index / 19) < (DIM - 1)) { flood(grid, index + DIM, fromNum, toNum); } } } } class IntList extends AbstractList<Integer> implements List<Integer> { private final int[] arr; private int hashCode = -1; IntList(int[] arr) { this.arr = arr; } @Override public int size() { return arr.length; } @Override public Integer get(int index) { return arr[index]; } @Override public Integer set(int index, Integer value) { int oldValue = arr[index]; arr[index] = value; return oldValue; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof IntList) { IntList arg = (IntList) obj; return Arrays.equals(arr, arg.arr); } return super.equals(obj); } @Override public int hashCode() { if (hashCode == -1) { hashCode = 1; for (int elem : arr) { hashCode = 31 * hashCode + elem; } } return hashCode; } } ``` [Answer] # My Last Entry: C - 2,384,020 steps This time a 'check-all-possibilities' one... This score is gained with Depth set on 3. Depth at 5 should give ~2.1M steps... TOO SLOW. Depth 20+ gives the least amount of steps possible (it just checks all matches and the shortest wins ofcourse)... It has the least amount of steps, though I hate it since it only is a tiny bit better, but performance sucks. I prefer my other C entry, which is also in this post. ``` #include <stdio.h> #include <string.h> #include <stdbool.h> char map[19][19], reach[19][19]; int reachsum[6], totalsum[6], mapCount = 0; FILE *stepfile; bool loadmap(FILE *fp) { fprintf(stepfile, "%s", "\n"); mapCount++; char buf[19 + 2]; size_t row = 0; while (fgets(buf, sizeof buf, fp) && row < 19) { if (strlen(buf) != 20) break; memcpy(map[row++], buf, 19); } return row == 19; } void calcreach(bool first, size_t row, size_t col); void check(char c, bool first, size_t row, size_t col) { if (map[row][col] == c) calcreach(first, row, col); else if (first) calcreach(false, row, col); } void calcreach(bool first, size_t row, size_t col) { char c = map[row][col]; reach[row][col] = c; reachsum[c - '1']++; if (row < 18 && !reach[row + 1][col]) check(c, first, row + 1, col); if (col < 18 && !reach[row][col + 1]) check(c, first, row, col + 1); if (row > 0 && !reach[row - 1][col]) check(c, first, row - 1, col); if (col > 0 && !reach[row][col - 1]) check(c, first, row, col - 1); } void calctotal() { size_t row, col; for (row = 0; row < 19; row++) for (col = 0; col < 19; col++) totalsum[map[row][col] - '1']++; } void apply(char c) { char d = map[9][9]; size_t row, col; for (row = 0; row < 19; row++) for (col = 0; col < 19; col++) if (reach[row][col] == d) map[row][col] = c; } int pown(int x, int y){ int p = 1; for(int i = 0; i < y; i++){ p = p * x; } return p; } int main() { size_t steps = 0; FILE *fp; if (!(fp = fopen("floodtest", "r"))) return 1; if(!(stepfile = fopen("steps.txt", "w"))) return 1; const int depth = 5; char possibilities[pown(6, depth)][depth]; int t = 0; for(int a = 0; a < 6; a++){ for(int b = 0; b < 6; b++){ for(int c = 0; c < 6; c++){ for(int d = 0; d < 6; d++){ for(int e = 0; e < 6; e++){ possibilities[t][0] = (char)(a + '1'); possibilities[t][1] = (char)(b + '1'); possibilities[t][2] = (char)(c + '1'); possibilities[t][3] = (char)(d + '1'); possibilities[t++][4] = (char)(e + '1'); } } } } } poes: while (loadmap(fp)) { do { char map2[19][19]; memcpy(map2, map, sizeof(map)); memset(reach, 0, sizeof reach); memset(reachsum, 0, sizeof reachsum); calcreach(true, 9, 9); int best = 0, index = 0, end = depth; for(int i = 0; i < pown(6, depth); i++){ for(int d = 0; d < end; d++){ apply(possibilities[i][d]); memset(reach, 0, sizeof reach); memset(reachsum, 0, sizeof reachsum); calcreach(true, 9, 9); if(reachsum[map[9][9] - '1'] == 361 && d < end){ end = d+1; index = i; break; } } if(end == depth && best < reachsum[map[9][9] - '1']){ best = reachsum[map[9][9] - '1']; index = i; } memcpy(map, map2, sizeof(map2)); memset(reach, 0, sizeof reach); memset(reachsum, 0, sizeof reachsum); calcreach(true, 9, 9); } for(int d = 0; d < end; d++){ apply(possibilities[index][d]); memset(reach, 0, sizeof reach); memset(reachsum, 0, sizeof reachsum); calcreach(true, 9, 9); fprintf(stepfile, "%c", possibilities[index][d]); steps++; } if(reachsum[map[9][9] - '1'] == 361) goto poes; } while (1); } fclose(fp); fclose(stepfile); printf("steps: %zu\n", steps); return 0; } ``` # Another Improved AI written in C - 2,445,761 steps Based on SteelTermite's: ``` #include <stdio.h> #include <string.h> #include <stdbool.h> char map[19][19], reach[19][19]; int reachsum[6], totalsum[6], mapCount = 0; FILE *stepfile; bool loadmap(FILE *fp) { fprintf(stepfile, "%s", "\n"); if(mapCount % 1000 == 0) printf("mapCount = %d\n", mapCount); mapCount++; char buf[19 + 2]; size_t row = 0; while (fgets(buf, sizeof buf, fp) && row < 19) { if (strlen(buf) != 20) break; memcpy(map[row++], buf, 19); } return row == 19; } void calcreach(bool first, size_t row, size_t col); void check(char c, bool first, size_t row, size_t col) { if (map[row][col] == c) calcreach(first, row, col); else if (first) calcreach(false, row, col); } void calcreach(bool first, size_t row, size_t col) { char c = map[row][col]; reach[row][col] = c; reachsum[c - '1']++; if (row < 18 && !reach[row + 1][col]) check(c, first, row + 1, col); if (col < 18 && !reach[row][col + 1]) check(c, first, row, col + 1); if (row > 0 && !reach[row - 1][col]) check(c, first, row - 1, col); if (col > 0 && !reach[row][col - 1]) check(c, first, row, col - 1); } void calctotal() { size_t row, col; for (row = 0; row < 19; row++) for (col = 0; col < 19; col++) totalsum[map[row][col] - '1']++; } void apply(char c) { char d = map[9][9]; size_t row, col; for (row = 0; row < 19; row++) for (col = 0; col < 19; col++) if (reach[row][col] == d) map[row][col] = c; } int main() { char c, best, answer; size_t steps = 0; FILE *fp; if (!(fp = fopen("floodtest", "r"))) return 1; if(!(stepfile = fopen("steps.txt", "w"))) return 1; while (loadmap(fp)) { do { memset(reach, 0, sizeof reach); memset(reachsum, 0, sizeof reachsum); calcreach(true, 9, 9); if (reachsum[map[9][9] - '1'] == 361) break; memset(totalsum, 0, sizeof totalsum); calctotal(); reachsum[map[9][9] - '1'] = 0; for (best = 0, c = 0; c < 6; c++) { if (!reachsum[c]) continue; if (reachsum[c] == totalsum[c]) { best = c; goto outLoop; } else if (reachsum[c] > reachsum[best]) { best = c; } } char map2[19][19]; memcpy(map2, map, sizeof(map)); int temp = best; for(c = 0; c < 6; c++){ if(c != best){ apply(c + '1'); memset(reach, 0, sizeof reach); memset(reachsum, 0, sizeof reachsum); calcreach(true, 9, 9); if (reachsum[best] == totalsum[best]) { memcpy(map, map2, sizeof(map2)); memset(reach, 0, sizeof reach); memset(reachsum, 0, sizeof reachsum); calcreach(true, 9, 9); if(temp == -1) temp = c; else if(reachsum[c] > reachsum[temp]) temp = c; } memcpy(map, map2, sizeof(map2)); memset(reach, 0, sizeof reach); memset(reachsum, 0, sizeof reachsum); calcreach(true, 9, 9); } } outLoop: answer = (char)(temp + '1'); fprintf(stepfile, "%c", answer); apply(answer); } while (++steps); } fclose(fp); fclose(stepfile); printf("steps: %zu\n", steps); return 0; } ``` [Answer] # Java - 2,610,797 4,780,841 steps (Fill-Bug fixed, score is now dramatically worse -\_- ) This is my basic reference algorithm submission, simply makes a histogram of the squares on the edges of the painted area, and paints with the most common color. Runs the 100k in a couple minutes. Obviously won't win, but it's certainly not last. I'll probably make another submission for clever stuff. Feel free to use this algorithm as a starting point. Un-comment the commented lines for the full output. Defaults to printing the # of steps taken. ``` import java.io.*; import java.util.*; public class PainterAI { public static void main(String[] args) throws IOException { int totalSteps = 0, numSolved = 0; char[] board = new char[361]; Scanner s = new Scanner(new File("floodtest")); long startTime = System.nanoTime(); caseloop: while (s.hasNextLine()) { for (int l = 0; l < 19; l++) { String line = s.nextLine(); if (line.isEmpty()) continue caseloop; System.arraycopy(line.toCharArray(), 0, board, l * 19, 19); } List<Character> colorsUsed = new ArrayList<>(); Stack<Integer> nodes = new Stack<>(); for (;; totalSteps++) { char p = board[180]; int[] occurrences = new int[7]; nodes.add(180); int numToPaint = 0; while (!nodes.empty()) { int n = nodes.pop(); if (n < 0 || n > 360) continue; if (board[n] == p) { board[n] = 48; numToPaint++; if (n % 19 > 0) nodes.push(n - 1); if(n%19<18) nodes.push(n + 1); if(n/19>0) nodes.push(n - 19); if(n/19<18) nodes.push(n + 19); } else occurrences[board[n] - 48]++; } if (numToPaint == 361) break; char mostFrequent = 0; int times = -1; for (int i = 1; i < 7; i++) if (occurrences[i] > times) { times = occurrences[i]; mostFrequent = (char) (i + 48); } for (int i = 0; i < 361; i++) if (board[i] == 48) board[i] = mostFrequent; //colorsUsed.add(mostFrequent); } numSolved++; /*String out = ""; for (Character c : colorsUsed) out += c; System.out.println(out); //print output*/ } s.close(); System.out.println("Total steps to solve all cases: " + totalSteps); System.out.printf("\nSolved %d test cases in %.2f seconds", numSolved, (System.nanoTime() - startTime) / 1000000000.); } } ``` Golfs to 860 chars (not including the newlines for formatting), but could be shrunk more if I felt like trying: ``` import java.io.*;import java.util.*;class P{ public static void main(String[]a)throws Exception{int t=0;char[]b=new char[361]; Scanner s=new Scanner(new File("floodtest"));c:while(s.hasNextLine()){ for(int l=0;l<19;l++){String L=s.nextLine();if(L.isEmpty())continue c; System.arraycopy(L.toCharArray(),0,b,l*19,19);}List<Character>u=new ArrayList<>(); Stack<Integer>q=new Stack<>();for(int[]o=new int[7];;t++){char p=b[180];q.add(180); int m=0;while(!q.empty()){int n=q.pop();if(n<0|n>360)continue;if(b[n]==p){b[n]=48;m++; if(n%19>0)q.add(n-1);if(n%19<18)q.add(n+1);if(n/19>0)q.add(n-19);if(n/19<18) q.add(n+19);}else o[b[n]-48]++;}if(m==361)break; char f=0;int h=0;for(int i=1;i<7;i++)if(o[i]>h){h=o[i];f=(char)(i+48);} for(int i=0;i<361;i++)if(b[i]==48)b[i]=f;u.add(f);}String y="";for(char c:u)y+=c; System.out.println(y);}s.close();System.out.println("Steps: "+t);}} ``` [Answer] # Haskell - 2,475,056 steps Algorithm is similar to the one suggested by MrBackend in the comments. The difference is: his suggestion finds the cheapest path to the highest cost square, mine greedily reduces the graph eccentricity at every step. ``` import Data.Array import qualified Data.Map as M import Data.Word import Data.List import Data.Maybe import Data.Function (on) import Data.Monoid import Control.Arrow import Control.Monad (liftM) import System.IO import System.Environment import Control.Parallel.Strategies import Control.DeepSeq type Grid v = Array (Word8,Word8) v main = do (ifn:_) <- getArgs hr <- openFile ifn ReadMode sp <- liftM parseFile $ hGetContents hr let (len,sol) = turns (map solve sp `using` parBuffer 3 (evalList rseq)) putStrLn $ intercalate "\n" $ map (concatMap show) sol putStrLn $ "\n\nTotal turns: " ++ (show len) turns :: [[a]] -> (Integer,[[a]]) turns l = rl' 0 l where rl' c [] = (c,[]) rl' c (k:r) = let s = c + genericLength k (s',l') = s `seq` rl' s r in (s',k:l') centrepoint :: Grid v -> (Word8,Word8) centrepoint g = let ((x0,y0),(x1,y1)) = bounds g med l h = let t = l + h in t `div` 2 + t `mod` 2 in (med x0 x1, med y0 y1) neighbours :: Grid v -> (Word8,Word8) -> [(Word8,Word8)] neighbours g (x,y) = filter (inRange $ bounds g) [(x,y+1),(x+1,y),(x,y-1),(x-1,y)] areas :: Eq v => Grid v -> [[(Word8,Word8)]] areas g = p $ indices g where p [] = [] p (a:r) = f : p (r \\ f) where f = s g [a] [] s g [] _ = [] s g (h:o) v = let n = filter (((==) `on` (g !)) h) $ neighbours g h in h : s g ((n \\ (o ++ v)) ++ o) (h : v) applyFill :: Eq v => v -> Grid v -> Grid v applyFill c g = g // (zip fa $ repeat c) where fa = s g [centrepoint g] [] solve g = solve' gr' where aa = areas g cp = centrepoint g ca = head $ head $ filter (elem cp) aa gr' = M.fromList $ map ( \r1 -> (head r1, map head $ filter ( \r2 -> head r1 /= head r2 && (not $ null $ intersect (concatMap (neighbours g) r1) r2) ) aa ) ) aa solve' gr | null $ tail $ M.keys $ gr = [] | otherwise = best : solve' ngr where djk _ [] = [] djk v ((n,q):o) = (n,q) : djk (q:v) ( o ++ zip (repeat (n+1)) ((gr M.! q) \\ (v ++ map snd o)) ) dout = djk [] [(0,ca)] din = let m = maximum $ map fst dout s = filter ((== m) . fst) dout in djk [] s rc = filter (flip elem (gr M.! ca) . snd) din frc = let m = minimum $ map fst rc in map snd $ filter ((==m) . fst) rc msq = concat $ filter (flip elem frc . head) aa clr = map (length &&& head) $ group $ sort $ map (g !) msq best = snd $ maximumBy (compare `on` fst) clr ngr = let ssm = filter ((== best) . (g !)) $ map snd rc sml = (concatMap (gr M.!) ssm) ncl = ((gr M.! ca) ++ sml) \\ (ca : ssm) brk = M.insert ca ncl $ M.filterWithKey (\k _ -> (not . flip elem ssm) k ) gr in M.map (\l -> nub $ map (\e -> if e `elem` ssm then ca else e) l) brk parseFile :: String -> [Grid Word8] parseFile f = map mk $ filter (not . null . head) $ groupBy ((==) `on` null) $ map (map ((read :: String -> Word8) . (:[]))) $ lines f where mk :: [[Word8]] -> Grid Word8 mk m = let w = fromIntegral (length $ head m) - 1 h = fromIntegral (length m) - 1 in array ((0,0),(w,h)) [ ((x,y),v) | (y,l) <- zip [h,h-1..] m, (x,v) <- zip [0..] l ] showGrid :: Grid Word8 -> String showGrid g = intercalate "\n" l where l = map sl $ groupBy ((==) `on` snd) $ sortBy ((flip (compare `on` snd)) <> (compare `on` fst)) $ indices g sl = intercalate " " . map (show . (g !)) testsolve = do hr <- openFile "floodtest" ReadMode sp <- liftM (head . parseFile) $ hGetContents hr let sol = solve sp a = snd $ mapAccumL (\g s -> let g' = applyFill s g in (g',g')) sp sol sequence_ $ map (\g -> putStrLn (showGrid g) >> putStrLn "\n") a ``` [Answer] ## C#- 2,383,569 It's a depth traversal of possible solutions that roughly chooses the path of best improvement (similar/same as Herjan's C entry), except I *cleverly* reversed the order of candidate solution generation after seeing Herjan posted the same numbers. Takes a good 12+ hours to run though. ``` class Solver { static void Main() { int depth = 3; string text = File.ReadAllText(@"C:\TEMP\floodtest.txt"); text = text.Replace("\n\n", ".").Replace("\n", ""); int count = 0; string[] tests = text.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < tests.Length; i++) { Solver s = new Solver(tests[i]); string k1 = s.solve(depth); count += k1.Length; Console.WriteLine(((100 * i) / tests.Length) + " " + i + " " + k1.Length + " " + count + " " + k1); } Console.WriteLine(count); } public readonly int MAX_DIM; public char[] board; public Solver(string prob) { board = read(prob); MAX_DIM = (int)Math.Sqrt(board.Length); } public string solve(int d) { var sol = ""; while (score(eval(copy(board), sol)) != board.Length) { char[] b = copy(board); eval(b, sol); var canidates = new List<string>(); buildCanidates("", canidates, d); var best = canidates.Select(c => new {score = score(eval(copy(b), c)), sol = c}).ToList().OrderByDescending(t=>t.score).ThenBy(v => v.sol.Length).First(); sol = sol + best.sol[0]; } return sol; } public void buildCanidates(string b, List<string> r, int d) { if(b.Length>0) r.Add(b); if (d > 0) { r.Add(b); for (char i = '6'; i >= '1'; i--) if(b.Length == 0 || b[b.Length-1] != i) buildCanidates(b + i, r, d - 1); } } public char[] read(string s) { return s.Where(c => c >= '0' && c <= '9').ToArray(); } public void print(char[] b) { for (int i = 0; i < MAX_DIM; i++) { for(int j=0; j<MAX_DIM; j++) Console.Write(b[i*MAX_DIM+j]); Console.WriteLine(); } Console.WriteLine(); } public char[] copy(char[] b) { char[] n = new char[b.Length]; for (int i = 0; i < b.Length; i++) n[i] = b[i]; return n; } public char[] eval(char[] b, string sol) { foreach (char c in sol) eval(b, c); return b; } public void eval(char[] b, char c) { foreach (var l in flood(b)) b[l] = c; } public int score(char[] b) { return flood(b).Count; } public List<int> flood(char[] b) { int start = (MAX_DIM * (MAX_DIM / 2)) + (MAX_DIM / 2); var check = new List<int>(MAX_DIM * MAX_DIM); bool[] seen = new bool[b.Length]; var hits = new List<int>(MAX_DIM*MAX_DIM); check.Add(start); seen[start]=true; char target = b[start]; int at = 0; while (at<check.Count) { int toCheck = check[at++]; if (b[toCheck] == target) { addNeighbors(check, seen, toCheck); hits.Add(toCheck); } } return hits; } public void addNeighbors(List<int> check, bool[] seen, int loc) { int x = loc / MAX_DIM; int y = loc % MAX_DIM; addNeighbor(check, seen, x, y - 1); addNeighbor(check, seen, x, y + 1); addNeighbor(check, seen, x - 1, y); addNeighbor(check, seen, x + 1, y); } public void addNeighbor(List<int> check, bool[] seen, int x, int y) { if (x >= 0 && x < MAX_DIM && y >= 0 && y < MAX_DIM) { int l = (x * MAX_DIM) + y; if (!seen[l]) { seen[l] = true; check.Add(l); } } } } ``` [Answer] ## Java - 2,403,189 ``` BUILD SUCCESSFUL (total time: 220 minutes 15 seconds) ``` This was supposed to be my attempt at a brute force. But! My first implementation of single-depth "best" choice yielded: ``` 2,589,328 - BUILD SUCCESSFUL (total time: 3 minutes 11 seconds) ``` The code used for both is the same with the brute force storing a "snapshot" of the other possible moves and running the algorithm over all of them. --- * Issues If running with the "multi" pass approach random failures will occur. I setup the first 100 puzzle entries in a unit test and can achieve a 100% pass but not 100% of the time. To compensate, I just tracked the current puzzle number at fail time and started a new Thread picking up where the last one left off. Each thread wrote their respective results to a file. The file pool was then condensed into a single file. * Approach `Node` represents a tile/square of the board and stores a reference to all of it's neighbors. Track three `Set<Node>` variables: `Remaining`, `Painted`, `Targets`. Each iteration looks at `Targets` to group all `candidate` nodes by value, selecting the `target value` by the number of "affected" nodes. These affected nodes then become the targets for the next iteration. The source is spread across many classes and snippets aren't very meaningful away from the context of the whole. My source can be browsed via [GitHub](http://github.com/origineil02/sandbox/tree/master/SandBox/src/main/java/stackexchange/codegolf/floodpaint). I also messed around with a [JSFiddle](http://jsfiddle.net/G8R8c/embedded/result/) demo for visualization. Nevertheless, my workhorse method from `Solver.java`: ``` public void flood() { final Data data = new Data(); consolidateCandidates(data, targets); input.add(data.getTarget()); if(input.size() > SolutionRepository.getInstance().getThreshold()){ //System.out.println("Exceeded threshold: " + input.toString()); cancelled = true; } paintable.addAll(data.targets()); remaining.removeAll(data.targets()); if(!data.targets().isEmpty()){ targets = data.potentialTargets(data.targets(), paintable); data.setPaintable(paintable); data.setRemaining(remaining); data.setInput(input); SolutionRepository.getInstance().addSnapshot(data, input); } } ``` [Answer] ## C#- 2,196,462 2,155,834 This is effectively the same 'look for best descendant' approach as my other solver, but with a few optimizations that just barely, with parallelism, allow it go to depth 5 in a little under 10 hours. In the course of testing this I also found a bug in the original, such that the algorithm would occasionally take inefficient routes to the end state (it wasn't accounting for depth of states with score=64; discovered while toying with results of depth=7). The main difference between this and the previous solver is that it keeps the Flood Game States in memory, so it doesn't have to regenerate 6^5 states. Based on CPU use during running, I'm fairly certain this has moved from CPU bound to memory bandwidth bound. Great fun. So many sins. Edit: Because of reasons, the depth 5 algorithm doesn't always produce the best result. To improve performance, let's just do depth 5... and 4... and 3 and 2 and 1, and see which is best. Did shave off another 40k moves. Since depth 5 is the bulk of the time, adding 4 through 1 only increases runtime from ~10hrs to ~11hrs. Yay! ``` using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Collections.Generic; public class Program { static void Main() { int depth = 5; string text = File.ReadAllText(@"C:\TEMP\floodtest.txt"); text = text.Replace("\n\n", ".").Replace("\n", ""); int count = 0; string[] tests = text.Split(new [] { '.' }, StringSplitOptions.RemoveEmptyEntries); Stopwatch start = Stopwatch.StartNew(); const int parChunk = 16*16; for (int i = 0; i < tests.Length; i += parChunk) { //did not know that parallel select didn't respect order string[] sols = tests.Skip(i).Take(parChunk).AsParallel().Select((t, idx) => new { s = new Solver2(t).solve(depth), idx}).ToList().OrderBy(v=>v.idx).Select(v=>v.s).ToArray(); for (int j = 0; j < sols.Length; j++) { string k1 = sols[j]; count += k1.Length; int k = i + j; int estimate = (int)((count*(long)tests.Length)/(k+1)); Console.WriteLine(k + "\t" + start.Elapsed.TotalMinutes.ToString("F2") + "\t" + count + "\t" + estimate + "\t" + k1.Length + "\t" + k1); } } Console.WriteLine(count); } } public class Solver2 { public readonly int MAX_DIM; public char[] board; public Solver2(string prob) { board = read(prob); MAX_DIM = (int)Math.Sqrt(board.Length); } public string solve(int d) { string best = null; for (int k = d; k >= 1; k--) { string c = subSolve(k); if (best == null || c.Length < best.Length) best = c; } return best; } public string subSolve(int d) { State current = new State(copy(board), '\0', flood(board)); var sol = ""; while (current.score != board.Length) { State nextState = subSolve(current, d); sol = sol + nextState.key; current = nextState; } return sol; } public State subSolve(State baseState, int d) { if (d == 0) return baseState; if (!baseState.childrenGenerated) { for (int i = 0; i < baseState.children.Length; i++) { if (('1' + i) == baseState.key) continue; //no point in even eval'ing char[] board = copy(baseState.board); foreach(int idx in baseState.flood) board[idx] = (char)('1' + i); List<int> f = flood(board); if (f.Count != baseState.score) baseState.children[i] = new State(board, (char)('1' + i), f); } baseState.childrenGenerated = true; } State bestState = null; for (int i = 0; i < baseState.children.Length; i++) if (baseState.children[i] != null) { State bestChild = subSolve(baseState.children[i], d - 1); baseState.children[i].bestChildScore = bestChild.bestChildScore; if (bestState == null || bestState.bestChildScore < bestChild.bestChildScore) bestState = baseState.children[i]; } if (bestState == null || bestState.bestChildScore == baseState.score) { if (baseState.score == baseState.board.Length) baseState.bestChildScore = baseState.score*(d + 1); return baseState; } return bestState; } public char[] read(string s) { return s.Where(c => c >= '1' && c <= '6').ToArray(); } public char[] copy(char[] b) { char[] n = new char[b.Length]; for (int i = 0; i < b.Length; i++) n[i] = b[i]; return n; } public List<int> flood(char[] b) { int start = (MAX_DIM * (MAX_DIM / 2)) + (MAX_DIM / 2); var check = new List<int>(MAX_DIM * MAX_DIM); bool[] seen = new bool[b.Length]; var hits = new List<int>(MAX_DIM * MAX_DIM); check.Add(start); seen[start] = true; char target = b[start]; int at = 0; while (at < check.Count) { int toCheck = check[at++]; if (b[toCheck] == target) { addNeighbors(check, seen, toCheck); hits.Add(toCheck); } } return hits; } public void addNeighbors(List<int> check, bool[] seen, int loc) { //int x = loc / MAX_DIM; int y = loc % MAX_DIM; if(loc+MAX_DIM < seen.Length) addNeighbor(check, seen, loc+MAX_DIM); if(loc-MAX_DIM >= 0) addNeighbor(check, seen, loc-MAX_DIM); if(y<MAX_DIM-1) addNeighbor(check, seen, loc+1); if (y > 0) addNeighbor(check, seen, loc-1); } public void addNeighbor(List<int> check, bool[] seen, int l) { if (!seen[l]) { seen[l] = true; check.Add(l); } } } public class State { public readonly char[] board; public readonly char key; public readonly State[] children = new State[6]; public readonly List<int> flood; public readonly int score; public bool childrenGenerated; public int bestChildScore; public State(char[] board, char k, List<int> flood) { this.board = board; key = k; this.flood = flood; score = flood.Count; bestChildScore = score; } } ``` [Answer] # Delphi XE3 2,979,145 steps Ok so this is my attempt. I call the changing part a blob, each turn it will make a copy of the array and test every possible color to see which color will give the biggest blob. Runs all puzzles in 3 hours and 6 minutes ``` program Main; {$APPTYPE CONSOLE} {$R *.res} uses SysUtils, Classes, Generics.Collections, math, stopwatch in 'stopwatch.pas'; type myArr=array[0..1]of integer; const MaxSize=19; puzLoc='here is my file'; var L:TList<TList<integer>>; puzzles:TStringList; sc:TList<myArr>; a:array[0..MaxSize-1,0..MaxSize-1] of Integer; aTest:array[0..MaxSize-1,0..MaxSize-1] of Integer; turns,midCol,sX,sY,i:integer; currBlob,biggestBlob,ColorBigBlob:integer; sTurn:string=''; GLC:integer=0; procedure FillArrays; var ln,x,y:integer; puzzle:TStringList; begin sc:=TList<myArr>.Create; puzzle:=TStringList.Create; while puzzle.Count<19 do begin if puzzles[GLC]='' then begin inc(GLC); continue end else puzzle.Add(puzzles[GLC]); inc(GLC) end; for y:=0to MaxSize-1do for x:=0to MaxSize-1do a[y][x]:=Ord(puzzle[y][x+1])-48; puzzle.Free; end; function CreateArr(nx,ny:integer):myArr; begin Result[1]:=nx; Result[0]:=ny; end; procedure CreateBlob; var tst:myArr; n,tx,ty:integer; currColor:integer; begin n:=0; sc.Clear; currColor:=a[sy][sx]; sc.Add(CreateArr(sx,sy)); repeat tx:=sc[n][1]; ty:=sc[n][0]; if tx>0 then if a[ty][tx-1]=currColor then begin tst:=CreateArr(tx-1,ty); if not sc.Contains(tst)then sc.Add(tst); end; if tx<MaxSize-1 then if a[ty][tx+1]=currColor then begin tst:=CreateArr(tx+1,ty); if not sc.Contains(tst)then sc.Add(tst); end; if ty>0 then if a[ty-1][tx]=currColor then begin tst:=CreateArr(tx,ty-1); if not sc.Contains(tst)then sc.Add(tst); end; if ty<MaxSize-1 then if a[ty+1][tx]=currColor then begin tst:=CreateArr(tx,ty+1); if not sc.Contains(tst)then sc.Add(tst); end; inc(n); until (n=sc.Count); end; function BlobSize:integer; var L:TList<myArr>; tst:myArr; n,currColor,tx,ty:integer; begin n:=0; L:=TList<myArr>.Create; currColor:=aTest[sy][sx]; L.Add(CreateArr(sx,sy)); repeat tx:=L[n][1]; ty:=L[n][0]; if tx>0then if aTest[ty][tx-1]=currColor then begin tst:=CreateArr(tx-1,ty); if not L.Contains(tst)then L.Add(tst); end; if tx<MaxSize-1then if aTest[ty][tx+1]=currColor then begin tst:=CreateArr(tx+1,ty); if not L.Contains(tst)then L.Add(tst); end; if ty>0then if aTest[ty-1][tx]=currColor then begin tst:=CreateArr(tx,ty-1); if not L.Contains(tst)then L.Add(tst); end; if ty<MaxSize-1then if aTest[ty+1][tx]=currColor then begin tst:=CreateArr(tx,ty+1); if not L.Contains(tst)then L.Add(tst); end; inc(n); until n=l.Count; Result:=L.Count; L.Free; end; function AllsameColor(c:integer):boolean; var cy,cx:integer; begin Result:=true; for cy:=0to MaxSize-1do for cx:=0to MaxSize-1do if a[cy][cx]=c then continue else exit(false); end; procedure ChangeColors(old,new:integer; testing:boolean=false); var i,j:integer; tst:myArr; begin if testing then begin for i:= 0to MaxSize-1do for j:= 0to MaxSize-1do aTest[i][j]:=a[i][j]; for I:=0to sc.Count-1do begin tst:=sc[i]; aTest[tst[0]][tst[1]]:=new; end; end else begin for I:=0to sc.Count-1do begin tst:=sc[i]; a[tst[0]][tst[1]]:=new; end; end; end; var sw, swTot:TStopWatch; solved:integer=0; solutions:TStringList; steps:integer; st:TDateTime; begin st:=Now; writeln(FormatDateTime('hh:nn:ss',st)); solutions:=TStringList.Create; puzzles:=TStringList.Create; puzzles.LoadFromFile(puzLoc); swTot:=TStopWatch.Create(true); turns:=0; repeat sTurn:=''; FillArrays; sX:=Round(Sqrt(MaxSize))+1; sY:=sX; repeat biggestBlob:=0; ColorBigBlob:=0; midCol:=a[sy][sx]; CreateBlob; for I:=1to 6do begin if I=midCol then continue; ChangeColors(midCol,I,true); currBlob:=BlobSize; if currBlob>biggestBlob then begin biggestBlob:=currBlob; ColorBigBlob:=i; end; end; ChangeColors(midCol,ColorBigBlob); inc(turns); if sTurn='' then sTurn:=IntToStr(ColorBigBlob) else sTurn:=sTurn+', '+IntToStr(ColorBigBlob); until AllsameColor(a[sy][sx]); solutions.Add(sTurn); inc(solved); if solved mod 100=0then writeln(Format('Solved %d puzzles || %s',[solved,FormatDateTime('hh:nn:ss',Now-st)])); until GLC>=puzzles.Count-1; swTot.Stop; WriteLn(Format('solving these puzzles took %d',[swTot.Elapsed])); writeln(Format('Total moves: %d',[turns])); solutions.SaveToFile('save solutions here'); readln; end. ``` Thinking about a bruteforce backtracing method too. Maybe fun for this weekend ^^ [Answer] ## Javascript/node.js - 2,588,847 Algoritm is a bit different then most here as it makes use of precalculated regions and diff states between calculations. It runs under 10 minutes here if you are worried about speed because of javascript. ``` var fs = require('fs') var file = fs.readFileSync('floodtest','utf8'); var boards = file.split('\n\n'); var linelength = boards[0].split('\n')[0].length; var maxdim = linelength* linelength; var board = function(info){ this.info =[]; this.sameNeighbors = []; this.differentNeighbors = []; this.samedifferentNeighbors = []; for (var i = 0;i <info.length;i++ ){ this.info.push(info[i]|0); }; this.getSameAndDifferentNeighbors(); } board.prototype.getSameAndDifferentNeighbors = function(){ var self = this; var info = self.info; function getSameNeighbors(i,value,sameneighbors,diffneighbors){ var neighbors = self.getNeighbors(i); for(var j =0,nl = neighbors.length; j< nl;j++){ var index = neighbors[j]; if (info[index] === value ){ if( sameneighbors.indexOf(index) === -1){ sameneighbors.push(index); getSameNeighbors(index,value,sameneighbors,diffneighbors); } }else if( diffneighbors.indexOf(index) === -1){ diffneighbors.push(index); } } } var sneighbors = []; var dneighbors = []; var sdneighbors = []; for(var i= 0,l= maxdim;i<l;i++){ if (sneighbors[i] === undefined){ var sameneighbors = [i]; var diffneighbors = []; getSameNeighbors(i,info[i],sameneighbors,diffneighbors); for (var j = 0; j<sameneighbors.length;j++){ var k = sameneighbors[j]; sneighbors[k] = sameneighbors; dneighbors[k] = diffneighbors; } } } for(var i= 0,l= maxdim;i<l;i++){ if (sdneighbors[i] === undefined){ var value = []; var dni = dneighbors[i]; for (var j = 0,dnil = dni.length; j<dnil;j++){ var dnij = dni[j]; var sdnij = sneighbors[dnij]; for(var k = 0,sdnijl = sdnij.length;k<sdnijl;k++){ if (value.indexOf(sdnij[k])=== -1){ value.push(sdnij[k]); } } }; var sni = sneighbors[i]; for (var j=0,snil = sni.length;j<snil;j++){ sdneighbors[sni[j]] = value; }; }; } this.sameNeighbors = sneighbors; this.differentNeighbors = dneighbors; this.samedifferentNeighbors =sdneighbors; } board.prototype.getNeighbors = function(i){ var returnValue = []; var index = i-linelength; if (index >= 0){ returnValue.push(index); } index = i+linelength; if (index < maxdim){ returnValue.push(index); } index = i-1; if (index >= 0 && index/linelength >>> 0 === i/linelength >>> 0){ returnValue.push(index); } index = i+1; if (index/linelength >>> 0 === i/linelength >>> 0){ returnValue.push(index); } if (returnValue.indexOf(-1) !== -1){ console.log(i,parseInt(index/linelength,10),parseInt(i/linelength,10)); } return returnValue } board.prototype.solve = function(){ var i,j; var info = this.info; var sameNeighbors = this.sameNeighbors; var samedifferentNeighbors = this.samedifferentNeighbors; var middle = 9*19+9; var maxValues = []; var done = {}; for (i=0; i<sameNeighbors[middle].length;i++){ done[sameNeighbors[middle][i]] = true; } var usefullNeighbors = [[],[],[],[],[],[],[]]; var diff = []; var count = [0]; count[1] = 0; count[2] = 0; count[3] = 0; count[4] = 0; count[5] = 0; count[6] = 0; var addusefullNeighbors = function(index,diff){ var indexsamedifferentNeighbors =samedifferentNeighbors[index]; for (var i=0;i < indexsamedifferentNeighbors.length;i++){ var is = indexsamedifferentNeighbors[i]; var value = info[is]; if (done[is] === undefined && usefullNeighbors[value].indexOf(is) === -1){ usefullNeighbors[value].push(is); diff.push(value); } } } addusefullNeighbors(middle,diff); while( usefullNeighbors[1].length > 0 || usefullNeighbors[2].length > 0 || usefullNeighbors[3].length > 0 || usefullNeighbors[4].length > 0 || usefullNeighbors[5].length > 0 || usefullNeighbors[6].length > 0 ){ for (i=0;i < diff.length;i++){ count[diff[i]]++; }; var maxValue = count.indexOf(Math.max.apply(null, count)); diff.length = 0; var used = usefullNeighbors[maxValue]; for (var i=0,ul = used.length;i < ul;i++){ var index = used[i]; if (info[index] === maxValue){ done[index] = true; addusefullNeighbors(index,diff); } } used.length = 0; count[maxValue] = 0; maxValues.push(maxValue); } return maxValues.join(""); }; var solved = []; var start = Date.now(); for (var boardindex =0;boardindex < boards.length;boardindex++){ var b = boards[boardindex].replace(/\n/g,'').split(''); var board2 = new board(b); solved.push(board2.solve()); }; var diff = Date.now()-start; console.log(diff,boards.length); console.log(solved.join('').length); console.log("end"); fs.writeFileSync('solution.txt',solved.join('\n'),'utf8'); ``` [Answer] C code that is guaranteed to find an optimal solution by simple brute force. Works for arbitrary size grids and all inputs. Takes a very, very long time to run on most grids. The flood fill is extremely inefficient and relies on recursion. Might need to make your stack bigger if it is very small. The brute force system uses a string to hold the numbers and simple add-with-carry to cycle through all possible options. This is also extremely inefficient as it repeats most of the steps quadrillions of times. Unfortunately I was unable to test it against all the test cases, since I'll die of old age before it finishes. ``` #include <stdio.h> #include <string.h> #define GRID_SIZE 19 char grid[GRID_SIZE][GRID_SIZE] = { {3,3,5,4,1,3,4,1,5,3,3,5,4,1,3,4,1,5}, {5,1,3,4,1,1,5,2,1,3,3,5,4,1,3,4,1,5}, {6,5,2,3,4,3,3,4,3,3,3,5,4,1,3,4,1,5}, {4,4,4,5,5,5,4,1,4,3,3,5,4,1,3,4,1,5}, {6,2,5,3,3,1,1,6,6,3,3,5,4,1,3,4,1,5}, {5,5,1,2,5,2,6,6,3,3,3,5,4,1,3,4,1,5}, {6,1,1,5,3,6,2,3,6,3,3,5,4,1,3,4,1,5}, {1,2,2,4,5,3,5,1,2,3,3,5,4,1,3,4,1,5}, {3,6,6,1,5,1,3,2,4,3,3,5,4,1,3,4,1,5} }; char grid_save[GRID_SIZE][GRID_SIZE]; char test_grids[6][GRID_SIZE][GRID_SIZE]; void flood_fill(char x, char y, char old_colour, char new_colour) { if (grid[y][x] == new_colour) return; grid[y][x] = new_colour; if (y > 0) { if (grid[y-1][x] == old_colour) flood_fill(x, y-1, old_colour, new_colour); } if (y < GRID_SIZE - 1) { if (grid[y+1][x] == old_colour) flood_fill(x, y+1, old_colour, new_colour); } if (x > 0) { if (grid[y][x-1] == old_colour) flood_fill(x-1, y, old_colour, new_colour); } if (x < GRID_SIZE - 1) { if (grid[y][x+1] == old_colour) flood_fill(x+1, y, old_colour, new_colour); } } bool check_grid(void) { for (char i = 0; i < 6; i++) { if (!memcmp(grid, &test_grids[i][0][0], sizeof(grid))) return(true); } return(false); } void inc_string_num(char *s) { char *c; c = s + strlen(s) - 1; *c += 1; // carry while (*c > '6') { *c = '1'; if (c == s) // first char { strcat(s, "1"); return; } c--; *c += 1; } } void print_grid(void) { char x, y; for (y = 0; y < GRID_SIZE; y++) { for (x = 0; x < GRID_SIZE; x++) printf("%d ", grid[y][x]); printf("\n"); } printf("\n"); } int main(int argc, char* argv[]) { // create test grids for comparisons for (char i = 0; i < 6; i++) memset(&test_grids[i][0][0], i+1, GRID_SIZE*GRID_SIZE); char s[256] = "0"; //char s[256] = "123456123456123455"; memcpy(grid_save, grid, sizeof(grid)); print_grid(); do { memcpy(grid, grid_save, sizeof(grid)); inc_string_num(s); for (unsigned int i = 0; i < strlen(s); i++) { flood_fill(4, 4, grid[4][4], s[i] - '0'); } } while(!check_grid()); print_grid(); printf("%s\n", s); return 0; } ``` --- As far as I can tell this is the current winner. The competition requires that: > > Your program must be entirely deterministic; pseudorandom solutions are allowed, but the program must generate the same output for the same test case every time. > > > Check > > The winning program will take the fewest total number of steps to solve all 100,000 test cases found in this file (zipped text file, 14.23 MB). If two solutions take the same number of steps (e.g. if they both found the optimal strategy), the shorter program will win. > > > Since this always finds the lowest number of steps to complete every board and none of the others do, it is currently ahead. If someone can come up with a shorter program they could win, so I present the following size optimized version. Execution is a bit slower, but execution time isn't part of the winning conditions: ``` #include <stdio.h> #include <string.h> #define A 9 int g[A][A]={{3,3,5,4,1,3,4,1,5},{5,1,3,4,1,1,5,2,1},{6,5,2,3,4,3,3,4,3},{4,4,4,5,5,5,4,1,4},{6,2,5,3,3,1,1,6,6},{5,5,1,2,5,2,6,6,3},{6,1,1,5,3,6,2,3,6},{1,2,2,4,5,3,5,1,2},{3,6,6,1,5,1,3,2,4}}; int s[A][A]; int t[6][A][A]; void ff(int x,int y,int o,int n) {if (g[y][x]==n)return;g[y][x]=n;if (y>0){if(g[y-1][x]==o)ff(x,y-1,o,n);}if(y<A-1){if(g[y+1][x]==o)ff(x,y+1,o,n);}if(x>0){if (g[y][x-1] == o)ff(x-1,y,o,n);}if(x<A-1){if(g[y][x+1]==o)ff(x+1,y,o,n);}} bool check_g(void) {for(int i=0;i<6;i++){if(!memcmp(g,&t[i][0][0],sizeof(g)))return(true);}return(0);} void is(char*s){char*c;c=s+strlen(s)-1;*c+=1;while(*c>'6'){*c='1';if (c==s){strcat(s,"1");return;}c--;*c+=1;}} void pr(void) {int x, y;for(y=0;y<A;y++){for(x=0;x<A;x++)printf("%d ",g[y][x]);printf("\n");}printf("\n");} int main(void) {for(int i=0;i<6;i++)memset(&t[i][0][0],i+1,A*A);char s[256]="0";memcpy(s,g,sizeof(g));pr();do{memcpy(g,s,sizeof(g));is(s);for(int i=0;i<strlen(s);i++){ff(4,4,g[4][4],s[i]-'0');}}while(!check_g()); pr();printf("%s\n",s);return 0;} ``` ]
[Question] [ Given an input of a string consisting entirely of `q`s representing quarter notes and `e`s representing eighth notes, output the indices of the quarter notes that are syncopated. [Syncopation](https://en.wikipedia.org/wiki/Syncopation) is complex, but for the purposes of this challenge, our definition of "syncopated" will be very simple: a quarter note that starts on the "off-beat"—that is, the beats counted as "and" in n/4 time. This may alternatively be defined as any quarter note that is preceded by an odd number of eighth notes. For example, the notes marked with `*` below are considered syncopated, and their indices are also shown: ``` eqqeqqeqqe ** ** 12 78 Output: 1 2 7 8 ``` The input will always consist of a whole number of measures in 4/4 time (a quarter note is a quarter of a measure, and an eighth note is an eighth of a measure). (The input will also never be empty.) Output can either be a single string with elements separated by any delimiter that does not contain numbers or an array/list/etc. The output may be 1-based (i.e. the first index is 1 instead of 0) if you wish, and it may also be in any numeric base (unary, decimal, etc.). Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins. Test cases: ``` In Out ----------------------------------------------- eqqqe 1 2 3 qeqeq 2 qqqeqqeeeeqeqeqeqqeqqeqq 4 5 10 14 19 20 eeeeeqeeqeeqqqqeqeqeeqe 5 8 11 12 13 14 18 21 qqqq <none> eeeeeeee <none> ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~12~~ 9 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md) ``` =“e”µ<^\O ``` As a program, the above code requires quotes around the input. Since that is not allowed, this is a function submission. The output is 1-based. ~~Try it online!~~ ### How it works ``` =“e”µ<^\O Monadic link. Argument: s (string) =“e” Check each character for equality with 'e'. Yields a Boolean array. µ Start a new, monadic chain. ^\ Compute the array of partial reductions by XOR, i. e., the parities of all prefixes of the Boolean array. < Check if the Booleans are strictly smaller than the parities. A truthy outcome indicates an off-beat quarter note. O Yield all indices of 1's. ``` ### Update The above code doesn't work anymore in the latest version of Jelly, since we need a *character* **e**, but `“e”` yields a string. Fixing that saves a byte, for a total of **8 bytes**. ``` =”eµ<^\O ``` This works as a full program. [Try it online!](http://jelly.tryitonline.net/#code=PeKAnWXCtTxeXE8&input=&args=cXFxZXFxZWVlZXFlcWVxZXFxZXFxZXFx) [Answer] # Ruby, 46 ``` i=e=0 gets.bytes{|n|e^=n e&4|n>114&&p(i) i+=1} ``` Input to stdin. Output to stdout, newline separated. Commented ``` i=e=0 #i keeps index, e keeps track of 8ths. gets.bytes{|n| #iterate through bytes in the input e^=n #xor e with input. We're interested in the 4's bit, which is only affected by ascii e, not ascii q e&4|n>114&&p(i) #e&4 evaluates to 4 or 0. OR with n and if the value is greater than ascii code for q, print index i+=1} #increment index ``` [Answer] # JavaScript ES7, ~~50~~ 48 bytes Pretty short for JS, if you ask me. `[for...of]` syntax, basically combined map and filter, comes in handy for this challenge. ``` s=>[for(c of(i=f=0,s))if(++i&&c>'e'?f%2:f++&0)i] ``` Defines an anonymous function that outputs a 1-indexed array. ### Test snippet This uses an ungolfed, un-ES7'd version of the code. ``` a = function(s) { // Create a function a that takes in a parameter s and does these things: var r = [], // Set variable r to an empty array, i = 0, f = 0; // i to 0, and f to 0. for(c of s) { // For each character c in s: i++; // Increment i by 1. if( // If c == 'q' ? // if c == 'q', f%2 === 1 : // f is even; otherwise, f++ && false) // increment f and don't execute this: r.push(i); // Add i to the end of r. } return r; // Return r. } ``` ``` <input type="text" value="eqqqe" id=O /> <button onclick="P.innerHTML='['+a(O.value)+']'">Try it</button> <p id=P /> ``` [Answer] ## J, ~~20 19~~ 17 bytes ``` =&'e'(I.@:<~:/\@) ``` Thanks to randomra for saving a byte, and to Dennis for saving two. This is an unnamed monadic verb, used as follows: ``` f =: =&'e'(I.@:<~:/\@) f 'eqqqe' 1 2 3 ``` [Try it here.](http://tryj.tk/) ## Explanation ``` =&'e'(I.@:<~:/\@) =&'e' Replace every 'e' with 1, other chars with 0 ( @) Apply the verb in parentheses to the resulting 0-1 vector ~:/\ Cumulative reduce with XOR (parity of 'e'-chars to the left) < Element-wise less-than with original vector I.@: Positions of 1s in that vector ``` [Answer] # GNU grep, ~~3+17=20~~ 3 + 15 = 18 bytes The program requires the options `boP`. The code is ``` q(?!(q|eq*e)*$) ``` Save it as `synco`, then run as `grep -boPf synco`. The output separator is `:q` followed by a newline. E.g. the output for `eqqqe` is ``` 1:q 2:q 3:q ``` The meanings of the flags are: * `P`: Use PCRE regexes. * `o`: This means to print only the part of the line that matches the regular expression, but that's not why it's important. `o` is used because it has the effect of allowing multiple matches per line. * `b`: Print the offset in bytes of the beginning of each match from the beginning of the file. The pattern checks that there is not an even number of eighth notes after a quarter note. [Answer] # [MATL](https://esolangs.org/wiki/MATL), 12 ~~14~~ ~~16~~ bytes ``` j101=tYs2\<f ``` *Thanks to Dennis for removing 2 bytes (and for hosting MATL in his awesome online platform!)* This uses [current version (9.3.0)](https://github.com/lmendo/MATL/releases/tag/9.3.0) of the language/compiler. Input and output are through stdin and stdout. The result is 1-based. **Example**: ``` >> matl j101=tYs2\<f > eeeeeqeeqeeqqqqeqeqeeqe 6 9 12 13 14 15 19 22 ``` Or [**try it online!**](http://matl.tryitonline.net/#code=ajEwMT10WXMyXDxm&input=cXFxZXFxZWVlZXFlcWVxZXFxZXFxZXFx) ## Explanation ``` j % input string 101= % vector that equals 1 at 'e' characters and 0 otherwise t % duplicate Ys2\ % cumulative sum modulo 2 < % detect where first vector is 0 and second is 1 f % find (1-based) indices of nonzero values ``` [Answer] # Python 2, ~~94~~ ~~85~~ ~~79~~ ~~75~~ 66 bytes **EDIT:** Thanks Doorknob and Alex A. **EDIT:** Thanks Alex A. **EDIT:** Now using input() so the input must be a string with the quotes. **EDIT:** Thanks Zgarb for recommending me to use enumerate. Simply counts number of e's and if q, check if e count is odd, then print index. ``` e=0 for j,k in enumerate(input()): if"q">k:e+=1 elif e%2:print j ``` [Try it here](http://ideone.com/UX6pf8) [Answer] ## Haskell, ~~58~~ 51 bytes ``` f x=[i|(i,'q')<-zip[0..]x,odd$sum[1|'e'<-take i x]] ``` Usage example: `f "eeeeeqeeqeeqqqqeqeqeeqe"` -> `[5,8,11,12,13,14,18,21]`. Go through the list and output the current index `i` for every char `'q'` if there's an odd number of `'e'`s before it. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 12 bytes ``` (⍸~×≠\)'e'∘= ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v9f41HvjrrD0x91LojRVE9Vf9Qxw/Z/2qO2CY96@x51NR9ab/yobeKjvqnBQc4KQCrEwzP4f5qCemphYWGqOheQVZgKhBAWUAiIgKAQAqEILJkKEQcjsEIIB6YRSREQqAMA "APL (Dyalog Classic) – Try It Online") Outputs 1-indexed. ### Explanation: ``` 'e'∘= ⍝ Map each element to whether it is equal to 'e' ( ) ⍝ Then apply the train ~ ⍝ Not the array into indexes of 'p' × ⍝ Multiply this by ≠\ ⍝ The cumulative reduction by inequality ⍸ ⍝ And get the indexes of the ones in the array ``` [Answer] ## [Minkolang 0.15](https://github.com/elendiastarman/Minkolang), 28 bytes ``` (o"q"=7&z1+$z8!z2%,2&iN$I$). ``` [Try it here.](http://play.starmaninnovations.com/minkolang/?code=%28o%22q%22%3D7%26z1%2B%24z8!z2%25%2C2%26iN%24I%24%29%2E&input=eeeeeqeeqeeqqqqeqeqeeqe) ### Explanation ``` ( Open while loop o Read in character from input "q" Push the character "q" = 1 if the top two items on stack are equal, 0 otherwise 7& Pop and jump 7 spaces if truthy z Push register value on stack 1+ Add one $z Pop top of stack and store in register 8! Jump eight spaces z Push register value on stack 2% Modulo by 2 , boolean not 2& Pop and jump two spaces if truthy i Push loop counter N Output as number $I Push length of input $). Close while loop when top of stack is 0 and stop. ``` [Answer] # C (function), 65 Thanks to @Dennis for the extra golfing! ``` i,n;f(char*m){for(i=n=0;*m;i++)*m++&4?++n:n%2?printf("%d ",i):0;} ``` [Answer] # Python 3, ~~109~~ ~~95~~ ~~80~~ ~~90~~ ~~88~~ ~~76~~ ~~68~~ ~~67~~ ~~66~~ 64 bytes Counts the number of `q`s and `e`s and adds the index of the current `q` if the number of preceding `e`s is odd. **Edit:** Now it prints a list of the indices of s that are `q` and have an odd number of `e`s preceding them. Eight bytes saved thanks to [Doorknob](https://codegolf.stackexchange.com/users/3808/doorknob) and two more thanks to [feersum](https://codegolf.stackexchange.com/users/30688/feersum). ``` lambda s:[x for x,m in enumerate(s)if("e"<m)*s[:x].count("e")%2] ``` **Ungolfed:** ``` def f(s): c = [] for index, item in enumerate(s): if item == "q": if s[:index].count("e")%2 == 1: c.append(index) return c ``` [Answer] # JavaScript ES6, ~~63~~ ~~60~~ 58 bytes ``` x=>[...x].map((e,i)=>e>'e'?n%2&&a.push(i):n++,a=[],n=0)&&a ``` Anonymous function that outputs an array. Thanks to user81655 for saving two bytes. Here is an ungolfed version that uses better supported syntax. ``` f=function(x) { a=[] // Indeces of syncopated notes n=0 // Number of e's encountered so far x.split('').map(function(e,i) { // For each letter... e>'e'? // If the letter is q... n%2&& // ...and the number of e's is odd... a.push(i): // ...add the current index to the array n++ // Otherwise, it is e so increment the counter }) return a } run=function(){document.getElementById('output').textContent=f(document.getElementById('input').value)};document.getElementById('run').onclick=run;run() ``` ``` <input type="text" id="input" value="qqqeqqeeeeqeqeqeqqeqqeqq" /><button id="run">Run</button><br /> <samp id="output"></samp> ``` [Answer] # Mathematica, 76 bytes ``` Flatten[Range[#+1,#2-1]&@@@StringPosition[#,"e"~~"q"..~~"e",Overlaps->1<0]]& ``` Something interesting I noticed. All of the syncopated parts are of form `eqqq..qqe`, so I just detect those and give the indices of the `q`s. [Answer] # Japt, ~~29~~ ~~23~~ 21 bytes Not non-competing anymore! ``` 0+U ¬®¥'e} å^ ä© m© f ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=MCtVIKyupSdlfSDlXiDkqSBtqSBm&input=ImVxcXFlcWVxZXFlcSI=) ### How it works ``` // Implicit: U = input string, e.g. "eqqeqeq" 0+U // Add a 0 to the beginning. "0eqqeqeq" ¬ // Split into chars. ['0,'e,'q,'q,'e,'q,'e,'q] ®¥'e} // Map each item X to (X == 'e). [F, T, F, F, T, F, T, F] å^ // Cumulative reduce by XOR'ing. [0, 1, 1, 1, 0, 0, 1, 1] ä© // Map each consecutive pair with &&. [0, 1, 1, 0, 0, 0, 1] m© // Map each item with &&. This performs (item && index): // [0, 1, 2, 0, 0, 0, 6] f // Filter out the falsy items. [ 1, 2, 6] // Implicit output [1,2,6] ``` ### Non-competing version, 18 bytes ``` U¬m¥'e å^ ä©0 m© f ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=VaxtpSdlIOVeIOSpMCBtqSBm&input=ImVxcXFlcWVxZXFlcSI=) [Answer] # Befunge, 43 bytes ``` :~:0\`#@_5%2/:99p1++\>2%#<9#\9#.g#:*#\_\1+\ ``` [Try it online!](http://befunge.tryitonline.net/#code=On46MFxgI0BfNSUyLzo5OXAxKytcPjIlIzw5I1w5Iy5nIzoqI1xfXDErXA&input=ZXFxZXFxZXFxZQ) **Explanation** We start with two implicit zeros on the stack: the note number, and a beat count. ``` : Make a duplicate of the beat count. ~ Read a character from stdin. :0\`#@_ Exit if it's less than zero (i.e. end-of-file). 5%2/ Take the ASCII value mod 5, div 2, translating q to 1 and e to 0. :99p Save a copy in memory for later use. 1+ Add 1, so q maps to 2 and e to 1. + Then add that number to our beat count. \ Get the original beat count that we duplicated at the start. 2% Mod 2 to check if it's an off-beat. 99g* Multiply with the previously saved note number (1 for q, 0 for e). _ Essentially testing if it's a quarter note on an off-beat. \.:\ If true, we go turn back left, get the beat count, and output it. >2 Then push 2 onto the stack, and turn right again. 2% That 2 modulo 2 is just zero. 99g* Then multiplied by the saved note number is still zero. _ And thus we branch right on the second pass. \1+\ Finally we increment the note number and wrap around to the start again. ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ðÈø¬?Tu:!°T ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=cQ&code=8Mj4rD9UdTohsFQ&input=ImVlZWVlcWVlcWVlcXFxcWVxZXFlZXFlIg) ]
[Question] [ # The Challenge I was reading [Google's Java Style Guide](https://google.github.io/styleguide/javaguide.html#s5.3-camel-case) the other day and stumbled over their algorithm to convert any arbitrary string into camelCase notation. In this challenge you have to implement this algorithm since you don't want to do all this stuff in your head when you are writing your super competitive Java submissions to code-golf challenges. *Note: I made some small adjustments to the algorithm. You need to use the one specified below.* # The algorithm You start with an arbitrary input string and apply the following operations to it: 1. Remove all apostrophes ``'` 2. Split the result into words by splitting at * characters that are not alphanumerical and not a digit `[^a-zA-Z0-9]` * Uppercase letters which are surrounded by lowercase letters on both sides. `abcDefGhI jk` for example yields `abc Def Ghi jk` 3. Lowercase every word. 4. Uppercase the first character of every but the first word. 5. Join all words back together. ### Additional notes * The input will only contain printable ASCII. * If a digit is the first letter in a word, leave it as it is and don't capitalize something else in this word. * The input will always have at least one character. # Rules * Function or full program allowed. * [Default rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) for input/output. * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte-count wins. Tiebreaker is earlier submission. # Test cases ``` "Programming Puzzles & Code Golf" -> "programmingPuzzlesCodeGolf" "XML HTTP request" -> "xmlHttpRequest" "supports IPv6 on iOS?" -> "supportsIpv6OnIos" "SomeThing w1th, apo'strophe's and' punc]tuation" -> "someThingW1thApostrophesAndPuncTuation" "nothing special" -> "nothingSpecial" "5pecial ca5e" -> "5pecialCa5e" "1337" -> "1337" "1337-spEAk" -> "1337Speak" "whatA mess" -> "whataMess" "abcD" -> "abcd" "a" -> "a" "B" -> "b" ``` **Happy Coding!** [Answer] ## [Retina](https://github.com/mbuettner/retina), 56 bytes Byte count assumes ISO 8859-1 encoding. ``` T`'\` S_`\W|_|(?<=[a-z])(?=[A-Z][a-z]) T`L`l T`l`L`¶. ¶ ``` [Try it online!](http://retina.tryitonline.net/#code=VGAnXGAKU19gXFd8X3woPzw9W2Etel0pKD89W0EtWl1bYS16XSkKVGBMYGwKVGBsYExgwrYuCsK2Cg&input=IVNvbWVUaGluZyB3MXRoLCBhcG8nc3Ryb2BwaGUncyBhbkQnIHB1bmNddHVhVElvbg) ### Explanation This implements the specification quite literally: ``` T`'\` ``` Remove apostrophes and backticks. ``` S_`\W|_|(?<=[a-z])(?=[A-Z][a-z]) ``` Split the string around non-word characters (in regex this also excludes digits and underscores), or underscores or positions that have a lower case letter on the left and and upper case, lower case on the right. This would create some empty segments when there are two non-letter, non-digit characters in a row, or more important at the beginning of the string. We get rid of those with the `_` option. Here, "splitting" means put each remaining part on its own line. ``` T`L`l ``` Convert everything to lower case. ``` T`l`L`¶. ``` Convert each character that occurs after the linefeed to upper case. This will conveniently skip the first word because there's no linefeed in front of it. ``` ¶ ``` Get rid of the linefeeds to join everything back together. [Answer] ## Java, ~~198~~ 190 bytes *+3 bytes because I forgot that `\W+` == `[^a-zA-Z0-9_]+` and I need to match `[^a-zA-Z0-9]+`* -11 bytes thanks to [user20093](https://codegolf.stackexchange.com/users/20093/user902383) - `?:` instead of `if`/`else` [Because, Java.](http://meta.codegolf.stackexchange.com/a/5829) ``` s->{String[]a=s.replaceAll("`|'","").split("[\\W_]+|(?<=[a-z])(?=[A-Z][a-z])");s="";for(String w:a){String t=w.toLowerCase();s+=a[0]==w?t:t.toUpperCase().charAt(0)+t.substring(1);}return s;} ``` This is a lambda. Call like so: ``` UnaryOperator<String> op = s->{String[]a=s.replaceAll("`|'","").split("[\\W_]+|(?<=[a-z])(?=[A-Z][a-z])");s="";for(String w:a){String t=w.toLowerCase();s+=a[0]==w?t:t.toUpperCase().charAt(0)+t.substring(1);}return s;}; System.out.println(op.apply("Programming Puzzles & Code Golf")); ``` Readable version: ``` public static String toCamelCase(String s) { String[] tokens = s .replaceAll("`|'", "") // 1. Remove all apostrophes .split("[\\W_]+|(?<=[a-z])(?=[A-Z][a-z])"); // 2. Split on [\W_]+ or between [a-z] and [A-Z][a-z] s = ""; // Reusing s for building output is cheap for (String token : tokens) { String lowercaseToken = token.toLowerCase(); // 3. Lowercase every word s += tokens[0].equals(token)?lowercaseToken:lowercaseToken.toUpperCase().charAt(0) + lowercaseToken.substring(1); // 4. Uppercase first char of all but first word // ^ 5. Join all words back together } return s; } ``` [Answer] # JavaScript (ES6), ~~156~~ ~~154~~ ~~152~~ ~~148~~ ~~145~~ ~~141~~ 140 bytes *Thanks @Neil (6 bytes), @ETHproductions (3 bytes), and @edc65 (7 bytes)* ``` a=>a[r='replace'](/`|'/g,a='')[r](/[a-z](?=[A-Z][a-z])/g,'$& ')[r](/[^\W_]+/g,b=>a+=(a?b[0].toUpperCase():'')+b.slice(!!a).toLowerCase())&&a ``` Removes apostrophes, then does a replace to split on special characters/before surrounded capitals, then combines with proper casing. Unfortunately, `toLowerCase()` and `toUpperCase()` are annoyingly long and hard to avoid here... [Answer] ## vim, ~~69~~ ~~68~~ 66 ``` :s/[`']//g<cr>:s/[a-z]\zs\ze[A-Z][a-z]\|\W\|_/\r/g<cr>o<esc>guggj<C-v>GgU:%s/\n<cr> ``` vim shorter than Perl?! What is this madness? ``` :s/[`']//g<cr> remove ` and ' :s/ match... [a-z]\zs\ze[A-Z][a-z] right before a lowercase-surrounded uppercase letter \|\W\|_ or a non-word char or underscore /\r/g<cr> insert newlines between parts o<esc> add an extra line at the end, necessary later... gugg lowercasify everything j go to line 2 (this is why we added the extra line) <C-v>G visual select the first char of all-but-first line gU uppercase :%s/\n<cr> join all lines into one ``` Thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil) for spotting a useless keystroke! [Answer] ## Mathematica 10.1, 101 bytes ``` ""<>(ToCamelCase@{##2}~Prepend~ToLowerCase@#&@@StringCases[StringDelete[#,"`"|"'"],WordCharacter..])& ``` Uses the undocumented `ToCamelCase`, which works similarly to `Capitalize` but sets other characters to lowercase. [Answer] # Julia, ~~98~~ 89 bytes ``` s->lcfirst(join(map(ucfirst,split(replace(s,r"['`]",""),r"[a-z]\K(?=[A-Z][a-z])|\W|_")))) ``` This is an anonymous function that accepts a string and returns a string. To call it, assign it to a variable. The approach here is the same as in Doorknob's [Perl answer](https://codegolf.stackexchange.com/a/74658/20469): `replace` apostrophes and backticks with the empty string, `split` into an array on a regular expression that matches the necessary cases, `map` the `ucfirst` function over the array to uppercase the first letter of each element, `join` the array back into a string, and `lcfirst` the result to convert the first character to lowercase. [Answer] # Perl 67 + 1 = 68 bytes ``` y/'`//d;s/([a-z](?=[A-Z][a-z]))|\W|_/$1 /g;$_=lc;s/^ +| +(.)/\u$1/g ``` Requires the `-p` flag, and `-l` for multi line: ``` $ perl -pl camelCase.pl input.txt programmingPuzzlesCodeGolf xmlHttpRequest supportsIpv6OnIos: someThingW1thApostrophesAndPuncTuation nothingSpecial 5pecialCa5e 1337 1337Speak abcd ``` How it works: ``` y/'`//d; # Remove ' and ` s/([a-z](?=[A-Z][a-z]))|\W|_/$1 /g; # Replace according to '2. Split...' this will create # a space separated string. $_=lc; # lower case string s/^ +| +(.)/\u$1/g # CamelCase the space separated string and remove any # potential leading spaces. ``` [Answer] # Lua, 127 Bytes ``` t=''l=t.lower z=io.read()for x in z:gmatch('%w+')do t=t..(t==''and l(x:sub(1,1))or x:sub(1,1):upper())..l(x:sub(2))end return t ``` Accepts a string from stdin and returns camelized results. Probably still gonna look for a better solution as storing everything in a variable feels inefficient. But anyhow, pretty simple in general: ``` z:gmatch('%w+') ``` This is the beauty that saved me a bit of bytes. gmatch will split the string based on the pattern: `%w+` which grabs only alphanumerics. After that it's simple string operations. string.upper, string.lower and done. [Answer] # PHP, ~~145~~ ~~122~~ 133 bytes ``` <?=join(split(" ",lcfirst(ucwords(strtolower(preg_replace(["#`|'#","#\W|_#","#([a-z])([A-Z][a-z])#"],[""," ","$1 $2"],$argv[1])))))); ``` Save to file, call from CLI. Takes input from a single command line argument; escape quotes and whitespace where necessary. **breakdown** ``` <?= // 9. print result join(split(" ", // 8. remove spaces lcfirst( // 7. lowercase first character ucwords( // 6. uppercase first character in every word strtolower( // 5. lowercase everything preg_replace( ["#`|'#", "#\W|_#", "#([a-z])([A-Z][a-z])#"], ["", " ", "$1 $2"], // 2. replace apostrophes with empty string (remove them) // 3. replace non-word characters with space // 4. insert space before solitude uppercase $argv[1] // 1. take input from command line )))) )); ``` `lcfirst` allowed to reduce this to a single command, saving 23 bytes. Fixing the apostrophes cost 11 bytes for the additional replace case. [Answer] ## Perl, ~~87~~ ~~80~~ 78 bytes ``` y/'`//d;$_=join'',map{ucfirst lc}split/[a-z]\K(?=[A-Z][a-z])|\W|_/,$_;lcfirst ``` Byte added for the `-p` flag. First, we use the `y///` transliteration operator to `d`elete all `'`` characters in the input: ``` y/'`//d; ``` Then comes the meat of the code: ``` split/[a-z]\K(?=[A-Z][a-z])|\W|_/,$_; ``` (split the input string `$_` in the appropriate locations, using the fancy `\K` in the match string to exclude the portion preceding it from the actual match) ``` map{ucfirst lc} ``` (map over each split portion of the string and make the entire string lowercase, then make the first character of the modified string uppercase) ``` $_=join'', ``` (join on empty string and re-assign to magic underscore `$_`, which gets printed at the end) Finally, we lowercase the first letter ~~by regex-matching it and using `\l` in the replacement string~~ with a builtin, saving 2 bytes over the previous method: ``` lcfirst ``` Thanks to [@MartinBüttner](https://codegolf.stackexchange.com/users/8478/martin-b%c3%bcttner) for 7 bytes (`[^a-zA-Z\d]` -> `\W|_`)! [Answer] # [Kotlin](https://kotlinlang.org/), 160 Bytes ``` fun a(s: String)=s.replace(Regex("['`]"),"").split(Regex("[\\W_]+|(?<=[a-z])(?=[A-Z][a-z])")).map{it.toLowerCase().capitalize()}.joinToString("").decapitalize() ``` My goal was to be Scala, the other "alternative Java", so I'm somewhat happy with my results. I stole the regex from the [Java](https://codegolf.stackexchange.com/a/74684/20198) answer. Test it with: ``` fun main(args: Array<String>) { val testCases = arrayOf( "Programming Puzzles & Code Golf", "XML HTTP request", "supports IPv6 on iOS?", "SomeThing w1th, apo'strophe's and' punc]tuation", "nothing special", "5pecial ca5e", "1337", "1337-spEAk", "abcD", "a", "B") testCases.forEach { println(a(it)) } } ``` [Answer] # Scala, ~~181~~ ~~170~~ 144 ``` def f(s:String)={val l=s.replaceAll("'|`","")split("[\\W_]+|(?<=[a-z])(?=[A-Z][a-z])")map(_.toLowerCase);l(0)+l.tail.map(_.capitalize).mkString} ``` Tester: ``` val testCases = List( "Programming Puzzles & Code Golf" -> "programmingPuzzlesCodeGolf", "XML HTTP request" -> "xmlHttpRequest" // etc ) println(testCases.map(t=>if(t._2!=f(t._1))s"FAIL:${f(t._1)}"else"PASS").mkString("\n")) ``` Props to [CAD97](https://codegolf.stackexchange.com/users/51825/cad97) and apologies to [Nathan Merrill](https://codegolf.stackexchange.com/users/20198/nathan-merrill) :) [Answer] # C 272 characters C program pass string to camelCase in quotes as argument 1. There are lot's of gotchas in this problem statement... ``` #define S strlen(t) #define A isalnum(t[i]) j=0;main(i,v)char**v;{char*p=v[1],*t;char o[99]={0};while(t=strtok(p," [{(~!@#$%^*-+=)}]")){i=0;p+=S+1;while((!A)&&i<S)i++;if(i!=S){o[j]=((j++==0)?tolower(t[i++]):toupper(t[i++]));while(i<S){if(A)o[j++]=t[i];i++;}}}puts(o);} ``` [Answer] # JavaScript, 123 bytes ``` v=>v[r="replace"](/[`']/g,"")[r](/^.|.$|[A-Z][^a-z]+/g,x=>x.toLowerCase())[r](/[^a-z0-9]+./ig,x=>x.slice(-1).toUpperCase()) ``` Readable version ``` v=> v.replace(/[`']/g,"") .replace(/^.|.$|[A-Z][^a-z]+/g,x=>x.toLowerCase()) .replace(/[^a-z0-9]+./ig,x=>x.slice(-1).toUpperCase()) ``` Remove the apostrophes, make the first character lower case, the last character lowercase, and any grouping of multiple uppercase characters, match any group of 1 or more non-alphanumeric chars + 1 other character, replace with that last character capitalized. [r="replace"] trick from Mrw247's solution. ]
[Question] [ I'm pretty sure there's not a better way to do this but figured it couldn't hurt to ask. I'm tired of typing out `a='abcdefghijklmnopqrstuvwxyz'`. Cool languages have `Range('a'..'z')` or similar What can we come up with with JS that's as short as possible?? ``` for(i=97,a='';i<123;){a+=String.fromCharCode(i++)} ``` is longer than just the alphabet - but guarantees I don't screw up somewhere. I'm hoping there's a nasty bit-shifty way to produce a-z in less than 50 characters. I messed around with `i=97;Array(26).map(x=>String.fromChar....i++` but it was always way longer by the time I joined then split the array(26) to be useable --- Edit: I've gotten it down to ``` [...Array(26)].reduce(a=>a+String.fromCharCode(i++),'',i=97) ``` 60 bytes [Answer] # Alternative to String.fromCharCode ... if you are happy with a lowercase only alphabet. ``` for(i=9,a='';++i<36;)a+=i.toString(36) // 38, cannot be used in an expression [...Array(26)].map(_=>(++i).toString(36),i=9).join`` // 52 directly returnig the string desired [...Array(26)].map(_=>a+=(++i).toString(36),a='',i=9) // 53 assign to a variable (i=9,[for(_ of Array(26))(++i).toString(36)].join``) // 52 ES7 direct return i=9,a='',[for(_ of Array(26))a+=(++i).toString(36)] // 51 ES7 assign to a variable ``` [Answer] **Note:** All of these techniques assign the alphabet string to variable `a`. --- I am 99% certain that the shortest way to achieve this in JavaScript is indeed: ``` a="abcdefghijklmnopqrstuvwxyz" // 30 bytes ``` But there are several other interesting methods. You can use string compression: ``` a=btoa`i·?yø!?9%?z)ª»-ºü1`+'yz' // 31 bytes; each ? represents an unprintable ``` You can get the compressed string from `atob`abcdefghijklmnopqrstuvwx``. The `'yz'` must be added manually because if you compress the whole string, while the result is only 27 bytes, it will turn out as `abcdefghijklmnopqrstuvwxyw==`. I believe the shortest way to do it programmatically is also the method you suggested: ``` for(i=97,a='';i<123;)a+=String.fromCharCode(i++) // 48 bytes ``` You can do it with ES6 features ([template strings ````](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings), [spread operator `...`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator)) if you want: ``` a=[...Array(26)].map(_=>String.fromCharCode(i++),i=97).join`` // 61 bytes a=[...Array(26)].map((_,i)=>String.fromCharCode(i+97)).join`` // also 61 bytes a=[...Array(i=26)].map(_=>String.fromCharCode(++i+70)).join`` // again, 61 bytes ``` You can do one better with a variable instead of `.join```: ``` [...Array(26)].map(_=>a+=String.fromCharCode(i++),i=97,a='') // all 60 bytes [...Array(26)].map((_,i)=>a+=String.fromCharCode(i+97),a='') [...Array(i=26)].map(_=>a+=String.fromCharCode(++i+70),a='') ``` Or ES7 with [array comprehensions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Array_comprehensions), which is another byte shorter: ``` a=[for(_ of Array(i=26))String.fromCharCode(++i+70)].join`` // 59 bytes ``` Creating the variable beforehand saves yet another byte: ``` a='',[for(_ of Array(i=26))a+=String.fromCharCode(++i+70)] // 58 bytes ``` Also, `String.fromCharCode` accepts multiple arguments and will automatically join them. So we can golf each ES6 version down to 57 bytes: ``` a=String.fromCharCode(...[...Array(26)].map(_=>i++,i=97)) // all 57 bytes a=String.fromCharCode(...[...Array(26)].map((_,i)=>i+97)) a=String.fromCharCode(...[...Array(i=26)].map(_=>++i+70)) ``` And the ES7 one down to 55: ``` a=String.fromCharCode(...[for(_ of Array(i=26))++i+70]) // 55 bytes ``` If you'd like to learn more about golfing ranges, check out [this set of tips](https://codegolf.stackexchange.com/a/61505/42545). There's also one about [ES7's array comprehensions](https://codegolf.stackexchange.com/a/61489/42545). **EDIT:** As edc65 has pointed out, most of these become shorter using `i.toString(36)` instead of `String.fromCharCode(i)`: ``` for(i=9,a='';++i<36;)a+=i.toString(36) // 38 bytes a=[...Array(26)].map(_=>(++i).toString(36),i=9).join`` // 54 bytes [...Array(26)].map(_=>a+=(++i).toString(36),i=9,a='') // 53 bytes i=9,a=[for(_ of Array(26))(++i).toString(36)].join`` // 52 bytes i=9,a='',[for(_ of Array(26))a+=(++i).toString(36)] // 51 bytes ``` I believe this one is the shortest possible that can be called as a function return value: ``` eval("for(i=9,a='';++i<36;)a+=i.toString(36)") // 46 bytes ``` It's three bytes shorter than manually returning it from a function: ``` x=>eval("for(i=9,a='';++i<36;)a+=i.toString(36)") // 49 bytes x=>{for(i=9,a='';++i<36;)a+=i.toString(36);return a} // 52 bytes ``` Of course, `x=>"abcdefghijklmnopqrstuvwxyz"` still beats everything else. [Answer] Here's another approach, a 51 byte ES6 expression: ``` String.fromCharCode(...Array(123).keys()).slice(97) ``` 50 bytes in upper case of course. [Answer] ``` (36n**26n*351n/1225n-1n).toString(36) ``` 37 bytes, as an expression. Uses the same base-36 method as many others, but further, obtaining all the letters from a single number. Requires BigInt support. [Answer] 36 bytes, using a trick I just learned about (from this post: <https://codegolf.stackexchange.com/a/176496/64538>): ``` for(i=9;++i<36;)name+=i.toString(36) ``` `window.name` is an empty string by default. Of course, this is even less practical than the 38-byte solution since it uses a longer variable name. [Answer] Using what may or may not be defined at global scope 39 bytes for object properties to array matching `a-z` ``` a=`${Object.keys(top)}`.match(/[a-z]/g) ``` 48 bytes for an unsorted `Set` ``` a=new Set(`${Object.keys(top)}`.match(/[a-z]/g)) ``` 55 bytes for a sorted `Set` ``` a=new Set(`${Object.keys(top)}`.match(/[a-z]/g).sort()) ``` 67 bytes for a sorted string ``` a=[...new Set(`${Object.keys(top)}`.match(/[a-z]/g).sort())].join`` ``` [Answer] I like this answer from above, but just throwing this small addition out there: ``` const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''); ``` The other answers are great but consider this example: ``` const excelSheet = sheet('whatever.csv') const headers = excelSheet.meta.headers // ['First Name', 'Last Name'] headers.map((header, i) => { console.log(`${header} is column ${alphabet[i]}`) }) // First Name is column A // Last Name is column B ``` It's more usable and readable for beginner/intermediate JavaScript developers. But this **is** code golf so I understand if this gets downvoted. ]
[Question] [ ## Background In most reasonable programming languages, it's very easy to rotate the rows or columns of a 2D array. In this challenge, your task is to rotate the *anti-diagonals* instead. Recall that the anti-diagonals of a 2D array are its 1D slices taken in the northeast direction ↗. ## Input A non-empty rectangular 2D array of single-digit numbers in any reasonable format. Note that the array may not be a square. ## Output The same array, but with each anti-diagonal rotated one step to the right. ## Example Consider the `3x4` input array ``` 0 1 2 3 4 5 6 7 8 9 0 1 ``` The anti-diagonals of this array are ``` 0 4 1 8 5 2 9 6 3 0 7 1 ``` Their rotated versions are ``` 0 1 4 2 8 5 3 9 6 7 0 1 ``` Thus the correct output is ``` 0 4 5 6 1 8 9 0 2 3 7 1 ``` ## Rules and scoring You can write a full program or a function. It's also acceptable to write a function that modifies the input array in place, if your language allows that. The lowest byte count wins, and standard loopholes are disallowed. ## Leaderboard 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 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, or you want to show old scores that you improved), make sure that the actual score is the *last* number in the header. ``` var QUESTION_ID=63755,OVERRIDE_USER=32014;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> ``` ## Additional test cases ``` Input: 4 Output: 4 Input: 5 6 1 Output: 5 6 1 Input: 0 1 6 2 Output: 0 6 1 2 Input: 6 3 0 8 4 6 1 4 6 2 3 3 9 3 0 3 Output: 6 4 6 1 3 6 2 3 0 9 3 0 8 4 3 3 Input: 5 8 2 6 7 3 2 6 1 6 0 6 6 4 1 Output: 5 6 7 8 2 6 2 6 0 3 6 4 1 6 1 Input: 9 9 4 0 6 2 2 3 2 6 4 7 1 5 9 3 1 5 0 2 6 0 4 7 Output: 9 2 3 2 6 4 9 1 5 9 3 1 4 0 2 6 0 4 0 6 2 7 5 7 ``` [Answer] # CJam, 20 ``` {z_)\zLa+(@+\.+s\,/} ``` Written as a function block. [Try it online](http://cjam.aditsu.net/#code=qN%2F%20e%23%20read%20and%20convert%20input%0A%0A%7Bz_)%5CzLa%2B(%40%2B%5C.%2Bs%5C%2C%2F%7D%0A%0A~N*%20e%23%20execute%20and%20format&input=994062%0A232647%0A159315%0A026047) **Explanation:** The input can be viewed like this: [![input diagram](https://i.stack.imgur.com/SFeZk.png)](https://i.stack.imgur.com/SFeZk.png) That is, we separate the top row and right column from the rest of the matrix, and consider those elements in the order shown by the arrow. Then the output is like this: [![output diagram](https://i.stack.imgur.com/8IDfX.png)](https://i.stack.imgur.com/8IDfX.png) The remaining rectangular block is moved diagonally as a whole, and the edge elements are rearranged in the order/positions showed by the new arrow. The code does almost exactly that, except the output is first generated with the arrow going straight down (so the matrix has a tail, like the letter P), then corrected. ``` z zip (transpose) the matrix _ make a copy ) take out the last row (right column before transposing) \ swap with the rest of the matrix z transpose back La+ append an empty row (needed for the single-column case, which leaves an empty matrix here) ( take out the first row (top row without the corner) @+ bring the right column to the top of the stack and concatenate obtaining an array of the edge elements (marked with the blue arrow) \ swap with the remaining part (big white block in the diagrams) .+ concatenate element by element each edge element is concatenated with a row of the white block after the white block runs out, the remaining elements form new rows s convert the whole thing to a string (concatenating all rows) \ swap with the copy of the transposed matrix , get its length (number of original columns) / split the string into rows of that length ``` [Answer] ## CJam, ~~44~~ ~~43~~ ~~42~~ 40 bytes ``` qN/:ReeSf.*:sz1fm<{Rz,{(S-(o\}*~]{},No}h ``` [Test it here.](http://cjam.aditsu.net/#code=qN%2F%3AReeSf.*%3Asz1fm%3C%7BRz%2C%7B(S-(o%5C%7D*~%5D%7B%7D%2CNo%7Dh&input=0123%0A4567%0A8901) Hmm, much better than my first attempt, but I have a feeling Dennis will solve this in much less anyway... Input and output are as ASCII grids: ``` 0123 4567 8901 ``` gives ``` 0456 1890 2371 ``` [Answer] # J, 24 char Function taking one argument. ``` $$<@(1&|.)/./:&;</.@i.@$ ``` J has an operator `/.` called [*Oblique*](http://www.jsoftware.com/help/dictionary/d421.htm). It can't invert it, so reconstruction isn't trivial, but you can consider "listing obliques" as a permutation of the elements of the array. So we invert that permutation with `/:` (dyadic [*Sort*](http://www.jsoftware.com/help/dictionary/d422.htm)), by putting the "listing obliques" permutation for that size (`</.@i.@$`) on the right and our new oblique values, rotated properly, on the left. Then we reshape this list into the old rectangular array using good old `$$`. ``` 3 4$i.10 0 1 2 3 4 5 6 7 8 9 0 1 ($$<@(1&|.)/./:&;</.@i.@$) 3 4$i.10 0 4 5 6 1 8 9 0 2 3 7 1 ``` [Try it online.](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%28%24%24%3C%40%281%26%7C.%29%2F.%2F%3A%26%3B%3C%2F.%40i.%40%24%29%203%204%24i.10) [Answer] # J, ~~38~~ 30 bytes *8 bytes saved thanks to @algorithmshark.* ``` {./.((}.~#),~({.~#),.])}:"1@}. ``` The function collects the top and left edges into a list, cuts the list to two pieces of sufficient sizes and stitches them to the right and bottom of the core part. Usage: ``` ]input=.0 1 2 3, 4 5 6 7,: 8 9 0 1 0 1 2 3 4 5 6 7 8 9 0 1 ({./.((}.~#),~({.~#),.])}:"1@}.) input 0 4 5 6 1 8 9 0 2 3 7 1 ``` [Try it online here.](http://tryj.tk/) [Answer] # Julia, ~~153~~ ~~149~~ 139 bytes ``` A->(length(A)>1&&((m,n)=size(A);r(X)=for i=1:n X[:,i]=reverse(X[:,i])end;r(A);for i=-m:m A[diagind(A,i)]=circshift(diag(A,i),1)end;r(A));A) ``` This creates an unnamed function that accepts an array and returns the input array modified in place. Ungolfed: ``` # Create a function to reverse the columns of a matrix function revcols!(X) for = 1:size(X, 2) X[:,i] = reverse(X[:,i]) end return X end # Our main function function zgarb!(A) # Only perform operations if the array isn't one element if length(A) > 1 # Record the number of rows m = size(A, 1) # Reverse the columns in place revcols!(A) # Shift each diagonal for i = -m:m A[diagind(A, i)] = circshift(diag(A, i), 1) end # Reverse the columns back revcols!(A) end return A end ``` Thanks to Martin Büttner for algorithmic advice and for saving 4 bytes! [Answer] ## ES6, 75 bytes This accepts an array of arrays as a parameter and modifies it in place. ``` a=>{t=a.shift();a.map(r=>{t.push(r.pop());r.unshift(t.shift())});a.push(t)} ``` Ungolfed: ``` function anti_diagonal(array) { var temp = array.shift(); // strip off the first row array.forEach(row => temp.push(row.pop())); // strip off the last elements of each row array.forEach(row => row.unshift(temp.shift())); // distribute the elements to the beginning of each row array.push(temp); // the remaining elements become the last row } ``` See @aditsu's diagram for further clarification. [Answer] # Pyth, 20 bytes ``` J+PhQ.)MQ++L.(J0tQ]J ``` Uses Adistu's approach of removing the top row and right column, then sticking them on the left and bottom. But with mutable data structures, not transpositions. [Answer] # Octave, 85 bytes ``` @(a)[(b=[a(1,1:end),a(2:end,end)'])(1:(s=size(a)(1)))',[a(2:end,1:end-1);b(s+1:end)]] ``` I hope I could get rid of the `end`s. [Answer] # [Python 2](https://docs.python.org/2/), ~~113~~ ~~104~~ 94 bytes ``` f=lambda i,b=[]:i and[b and b[:1]+i[0][:-1]]+f(i[1:],b[1:]or i[0][:-1]+[l[-1]for l in i])or[b] ``` [Try it online!](https://tio.run/##PY7LisMwDEX3@opLVwl1i51nG8iXGC8SShkNeRF70/n5jJSB2UjWOXp4@6SvdSmO491Pwzy@BrAZex86xrC8/KgRo@9cuLK3wXc3F8L1nbF3XTCjxnXHv7r6yUt6C5vACzjk6@7HcPC8rXtC/ERKvbemNs4aJ7E1NhD387BlMe33uE2cjLTdY3rxkpOuiibpsh/esnSeMUkP5x3h1Cr1S7FLIhVj23lJuOBy/155yWJOf@hoUMLiQRUaOFTUoBBS0vPkJVGNBwrBrRSFNsnboiHpeKLSp2idUVmhJYcaOi2Z7EntyUVoWyVaph0VVFJFNUnxCw "Python 2 – Try It Online") This is a fairly literal interpretation of @aditsu's method. Python's syntax for treating empty lists as False helped save an extra 10 bytes. ]
[Question] [ Given a string **s** composed of lowercase letters, such as ``` aabaaababbbbaaba ``` and a positive integer **n**, such as `4`, output a length-**n** string **t** such that when **t** is repeated to the length of **s**, they have as many chars in common as possible. For the given example, the optimal output would be `aaba`, because it has thirteen chars in common with the target string: ``` s: aabaaababbbbaaba t: aabaaabaaabaaaba (aaba) ^^^^^^^^ ^ ^^^^ ``` and no possible **t** has more. However, for `aaaaaab`, there are two possible outputs: `aaaa` and `aaba`, which each have 6 chars in common with the target string: ``` s: aaaaaab t: aaaaaaaa (aaaa) ^^^^^^ s: aaaaaab t: aabaaaba (aaba) ^^ ^^^^ ``` Either `aaaa` or `aaba` can be outputted, or both if you'd like. Note that **s** is not ever repeated; the trailing `a` in both repeated values of **t** is simply ignored. ## Test cases ``` Inputs -> Valid outputs 1 a -> a 1 aa -> a 2 aa -> aa 1 ab -> a b 2 ab -> ab 1 abb -> b 2 abb -> ab bb 2 ababa -> ab 2 abcba -> ab 2 aabbbbb -> bb (ab is not a valid output here) 3 aababba -> aab abb 3 aababbaa -> aab 3 asdasfadf -> asf 3 asdasfadfsdf -> asf adf 2 abcdefghijklmnopqrstuvwxyzyx -> yx 2 supercalifragilisticexpialidocious -> ic ii 3 supercalifragilisticexpialidocious -> iri ili ioi 4 supercalifragilisticexpialidocious -> scii 5 supercalifragilisticexpialidocious -> iapic 2 eeeebaadbaecaebbbbbebbbbeecacebdccaecadbbbaceebedbbbddadebeddedbcedeaadcabdeccceccaeaadbbaecbbcbcbea -> bb be 10 bbbbacacbcedecdbbbdebdaedcecdabcebddbdcecebbeeaacdebdbebaebcecddadeeedbbdbbaeaaeebbedbeeaeedadeecbcd -> ebbbdbeece ebdbdbeece 20 aabbbaaabaaabaaaabbbbabbbbabbbabbbbbabbaaaababbbaababbbaababaaaabbaaabbaabbbabaaabbabbaaabbaaaaaaaba -> aabbbbaaabbabbbaabba ``` ## Rules * You may assume the input will only ever be a non-empty string of lowercase letters and a positive integer no greater than the length of the string. * You may take the inputs in any standard format and in either order. * You may output a single string, or more than one in the form of an array, separated by newlines or spaces, etc. * Your code must finish for each test-case in less than 1 minute on any fairly modern computer. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so make your code as short as possible. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` sZµṢŒrUṀṪµ€ ``` [Try it online!](https://tio.run/nexus/jelly#FYyxEcJQDENXgmFo0lmWFiALcIzACJS5tCl@mzsG@VnEyD43T092rct5zPH9fZ6POV5zbOdxvfeqgicyEikqaaLAENMUTkGiQYAUka0hhNANBiX5zBvW6hq76bSdH7Putz8 "Jelly – TIO Nexus") Wasn't expecting to beat Dennis on this one, so tried to FGITW it (after trying several possibilities; there's more than one way to make 11). I came in shorter, much to my surprise. Takes the string then the count as command-line arguments. Outputs on stdout. ## Explanation ``` sZµṢŒrUṀṪµ€ s Split {the first input} into {the second input}-sized groups Z Transpose µ µ€ On each of the transposed groups: Ṣ Sort it; Œr Run-length encode it; U Rearrange it to the form {count, letter}; Ṁ Take the largest element (i.e. largest count) Ṫ Take the second element of the pair (i.e. just the letter) ``` This uses the insight that the letter in each position of the pattern must be the most common letter corresponding to that position. We can find the letters corresponding to a particular pattern via splitting into pattern-sized groups, and transposing. The main reason this solution is so long is that Jelly doesn't seem to have a short way to find the mode of a list (I made several attempts, but they're all at least six bytes long). # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes, based on @Dennis' solution ``` ⁸ċ$ÞṪ sZÇ€ ``` [Try it online!](https://tio.run/nexus/jelly#FYwxFQIBDEN3dCCAs8OWNFGAAlgY8IAAHgK4@TDCGSlpX5efn7b36@f7OG7P3/o6XM7bfb@9u5sZFIpluRSSKVgVQlJKHDBpAzWaJsxpCLKdsyyiPTVNM@m4PFYvpz8 "Jelly – TIO Nexus") This is a combination of @Dennis' solution and my own; there was a five-byte mode in that solution, which I stole for this solution. (I already had solutions based on `⁸ċ`, but couldn't get below six bytes with it; I hadn't thought of using `Þ`.) ## Explanation `µ…µ€` and `Ç€` (with the `…` on the previous line) are both three bytes long (the latter needs a newline), and equivalent. Normally I use the former, but the latter's more flexible, as it allows you to use `⁸` to mention the argument. This makes it possible to sort (`Þ`) by the number of occurrences in `⁸` (`⁸ċ`), then take the last element (`Ṫ`), to find the mode in just five characters. [Answer] ## Mathematica, 51 bytes ``` #&@@@Commonest/@(PadRight@Partition[#2,UpTo@#])& ``` Input and output are lists of characters. Also based on the modes of the lines of the transpose. I believe they called the built-in for the mode of a list `Commonest` *solely* to spite code golfers. [Answer] # Python 3, ~~99, 73~~ 61 bytes -12, thx to @Rod ``` lambda s,n:''.join(max(s,key=s[i::n].count)for i in range(n)) ``` Same idea, but rewrote it to eliminate the import statement. ``` lambda s,n:''.join(max(s,key=lambda c:s[i::n].count(c))for i in range(n)) ``` Original ``` from collections import* lambda s,n:''.join(Counter(s[i::n]).most_common(1)[0][0]for i in range(n)) ``` Explanation: ``` s[i::n] a slice of every nth character of s, starting at position i Counter(s[i::n]) counts the characters in the slice .most_common() returns a list of (character, count) pairs, sorted by decreasing count [0][0] grabs the letter from the first pair (i.e., the most common letter for i in range(n) repeat for all starting positions ''.join combines the most common letters into a single string ``` [Answer] ## Python 2, 106 Now it's a different answer! I was thinking about one(almost)-liner from the beggining. Now even shorter, based on zip usage by @Rod. Thanks to @L3viathan and @Rod for clarification about using lambdas as answer [Try it online](https://tio.run/nexus/python2#LcoxEoMgEEDRPqfYsQKHKqUzXCGNbRpUSDayLAFMwMsbi/zyz3P6fnhD02JgVLeBTBUz04TBFOSQxTmlWm3Tf5SHvJGoWjdwnKCqBhhgx3jK3HsbxCjPLi4xARabCrPPgBQ5lf6ICUMBJ3oMcStCyqMz07xY93jia/UUOL5TLtvnW9veaqeuPw) ``` lambda S,N:max(combinations(S,N),key=lambda s:sum(x==y for x,y in zip(S,s*len(S)))) from itertools import* ``` Explanation: `combinations(S,N)` creates all combinations length N from characters of S `max()` have argument `key` which takes as input function to use to compare elements `lambda s:sum(x==y for x,y in zip(S,s*len(S)))` passed as such function This lambda counts number of matching characters in list of tuples, produces by `zip(S,s*len(S))` `s` - one of combinations and it's multipled by `len(S)` which creates string that is guaranteed longer than S `zip` creates tuples of characters of each string `S` and `s*len(S)` and ignores all characters that can't be matched (in case of one string longer than another) So `max` chooses combination, that produce maximum sum [Answer] ## JavaScript (ES6), ~~104~~ ~~101~~ 94 bytes ``` (n,s)=>s.replace(/./g,(_,i)=>[...s].map((c,j,a)=>j%n-i||(a[c]=-~a[c])>m&&(m++,r=c),m=r=``)&&r) ``` Saved 3 bytes twice thanks to @Arnauld. 97-byte solution that works with all non-newline characters: ``` (n,s)=>s.replace(/./g,(_,i)=>[...s].map((c,j)=>j%n-i||(o[c]=-~o[c])>m&&(m++,r=c),m=r=``,o={})&&r) ``` The previous 104-byte solution works with newline characters too: ``` (n,s)=>[...Array(n)].map((_,i)=>[...s].map((c,j)=>j%n-i||(o[c]=-~o[c])>m&&(m++,r=c),m=0,o={})&&r).join`` ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 bytes ``` s@ZċþZMḢ$€ị ``` [Try it online!](https://tio.run/nexus/jelly#jVE7TgNBDO33FCnoCQF6LkCLRDqP7Q0DC0l2EthQ0uYWSIiGClFEikRBuMhykeXZg0LKzGg8z/bzm4@7dDb8Xm4@h@ft6vng5@mtXS@7dv3Rrt7hXGxev14OAS677qhHBRYVAzNAwVBwlGG2mL5z3hHGKI4NAdM/cpiEUklS7uIE1xVEy9FVvL6pbu/Gk2mdZvP7h2bxuGiQTvOJ1kxVLGsaxSqmWWRtJhERGXMczxMk9yCd7EM63Yc06CkG3iWBlEn94W4VLmsQZksIInA1qCEREoMCj1UU5UxBlJnV@CZnegEfykHx8/1ecAViL2BXgTqpoETwb3AkmKN2NhFbGlfBnYxhJ6od7spEajQxJqKWg7AUg35uHlm78vJebk3urHcydzTsbpn@Z5yX8TZGuewX "Jelly – TIO Nexus") ### How it works ``` s@ZċþZMḢ$€ị Main link. Arguments: n (integer), s (string) s@ Split swapped; split s into chunks of length n. Z Zip/transpose, grouping characters that correspond to repetitions. ċþ Count table; for each slice in the previous result, and each character in s, count the occurrences of the character in the group. This groups by character. Z Zip/transpose to group by slice. $€ Map the two-link chain to the left over the groups. M Find all maximal indices. Ḣ Head; pick the first. ị Index into s to retrieve the corresponding characters. ``` [Answer] # Pyth, 11 bytes ``` meo/dNd.TcF ``` Takes input as `s,n` and outputs as a list of characters. ### Explanation ``` meo/dNd.TcF cFQ Split s into chunks of length n. .T Transpose. m o/dNd Sort characters in each string by frequency. e Take the most common. ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~16~~ 15 bytes *Saved 1 byte thanks to @obarakon* ``` Ç=VëUZ)¬ñ!èZ o ``` 14 bytes of code + 1 byte for the `-P` flag. [Try it online!](https://tio.run/nexus/japt#@3@43Tbs8OrQKM1Daw5vVDy8Ikoh//9/UwWl4tKC1KLkxJzMtKLE9MyczOKSzOTUioJMoEhKfnJmfmmxkoJuAAA "Japt – TIO Nexus") ### Ungolfed and explanation ``` Ç =VëUZ)¬ ñ!èZ o UoZ{Z=VëUZ)q ñ!èZ o} Implicit: U = input number, V = input string Uo Create the range [0...U). Z{ } Map each item Z by this function: VëUZ Take every U'th char of V, starting at index Z. Z= ) Call the result Z. q Split the result into chars. ñ!èZ Sort each char X by the number of occurrences of X in Z. o Pop; grab the last item (the most common char). -P Join the results (array of most common chars) into a string. ``` [Answer] # [Python 2](https://docs.python.org/2/), 132 bytes ``` from itertools import* p,k=input() b=l=len(p) for i in combinations(p,k): x=sum(x!=y for x,y in zip(p,i*l)) if x<b:b,o=x,i print o ``` [Try it online!](https://tio.run/nexus/python2#FcoxDsMgDADAnVe4UyBi6xaVx@AqSFbBtoBIpJ8nyc03U5UC1PfaRXIDKiq1r0b9LxDr0a0zGHLIO1t1JkkFAmL4SkHi2Em42Tu7zcAI7Sh2vMIJzxv@fOaf9A60ZucMUILxwQ29hOHJaCXuIHMuMWJEjHHx7ws "Python 2 – TIO Nexus") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes ``` Iôð«øvy{.¡é®èÙJðÜ ``` [Try it online!](https://tio.run/nexus/05ab1e#FYyxDQJRDEN7hkHcGLBFHHsFJMQkSNfQcUJCV1BQ/wz2caI0z8/JPNe39vGu3/V2P45nbeNTr3pcaq91zuV0gCcyEikqaaLAENMUTkGiQYAUka0hhNANBiX5zBvW6hq76bSdH/MP "05AB1E – TIO Nexus") **Explanation** ``` Iô # split 2nd input in chunks of 1st input size ð« # append a space to each ø # zip vy # for each y in the zipped list { # sort the string .¡ # group into chunks of consecutive equal elements é # sort by length ®è # pop the last element (the longest) Ù # remove duplicate characters from the string J # join the stack into one string ðÜ # remove any trailing spaces ``` [Answer] # PHP, 245 Bytes ``` function p($c,$s,$r=""){global$a;if(($c-strlen($r)))foreach(str_split(count_chars($s,3))as$l)p($c,$s,$r.$l);else{for($v=str_pad("",$w=strlen($s),$r);$z<$w;)$t+=$v[$z]==$s[$z++];$a[$t][]=$r;}}p($argv[1],$argv[2]);ksort($a);echo join(" ",end($a)); ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/279a92a6ac8467fb5220a8d697eab14d044b51d1) ## Breakdown ``` function p($c,$s,$r=""){ global$a; if(($c-strlen($r))) # make permutation foreach(str_split(count_chars($s,3))as$l) p($c,$s,$r.$l); #recursive else{ for($v=str_pad("",$w=strlen($s),$r);$z<$w;) $t+=$v[$z]==$s[$z++]; #compare strings $a[$t][]=$r; # insert value in array } } p($argv[1],$argv[2]); #start function with the input parameter ksort($a); # sort result array echo join(" ",end($a)); #Output ``` [Answer] ## Haskell, 84 bytes ``` import Data.Lists f n=map(argmax=<<(length.).flip(filter.(==))).transpose.chunksOf n ``` Usage example: ``` f 10 "bbbbacacbcedecdbbbdebdaedcecdabcebddbdcecebbeeaacdebdbebaebcecddadeeedbbdbbaeaaeebbedbeeaeedadeecbcd" "ebbbdbeece" ``` Split input string into chunks of length `n`, transpose and ffind for each sublist the most frequent element. [Answer] # [Röda](https://github.com/fergusq/roda), 68 bytes ``` f s,n{seq 0,n-1|{|i|sort s/"",key={|c|x=s[i::n]x~=c,"";[#x]}|head}_} ``` [Try it online!](https://tio.run/nexus/roda#jVLBjtpADD2Tr7BSqQIpq8K2vdBm7/0GhCqPx4HpsplsJtmGEvrr1J7JUo6AmNjP7/mZiS8VhKI@BX6FZVE/rMbT6Mbg2w7CpzwvnvlYnkYahzJs3Hpdb4e/JRV5/m3zYdiexz2jPf88X17Q1XDKZqE5OFFyU@bw8AQ5jFD5FlzhwfpsNsO2hXUJm8ibu8VWsKYP@/mmmktts1pvP@aQF9BgG/hH3fGO21hZbhcLqUkph@9PSvGLbGZ9zdn5sgJUO8wkmKLH9yiCJoZgFE6xiXCMEzrBYFIq34mnGd1mwjWT0gDMReMC1L4Tgzc8OAu@75q@gz23vMg@q0Ak0zRGrf6D76giwWKo0FYRCtUtFK4oSJZGslzt9u7X8@Gl9s1rG7r@7fdw/HMclHkchBT6hluSkaoWd@7gQueIh8bpkJ6c74NSHYFzYnYnu3UgRXDeZV/u1AQSg6/3GmDjSIZn@cj9WINMyPHK48mSEhtLpAUriKRsWCNr0WpoJSO2LHJCY5mIWPnaTvsZeaFkGKd3aDhbLcHEVkhRSbGd2CBb0Vq5b0ms0YR1CETSsswkwylDrVmniBaIrDSrTEG1Jo2tGuq/UJwYtEEKs8dlWizUxUi/uGfXI21d3Jm0O@b2kejTEXkpvmKYZNO6GXOtRz7@Aw "Röda – TIO Nexus") It's a function that prints the output without trailing newline. This was inspired by [this answer](https://codegolf.stackexchange.com/a/113619/66323). [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` ►ȯΣz=¹¢Ṗ² ``` [Try it online!](https://tio.run/##ATkAxv9odXNr///ilrrIr86jej3CucKi4bmWwrL///8y/2FiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6eXg "Husk – Try It Online") Zgarb-quality questions need a Zgarb language answer. ## Explanation ``` ►ȯΣz=¹¢Ṗ² ¹ Ṗ² length n powerset of string ►ȯ max by: ¢ repeating each subsequence infinitely z=¹ and check equality with the input Σ sum the results this will return the most optimal pattern. ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` òV ÕËü ñÊ¬Ì ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=8lYg1cv8IPHKrMw&input=InN1cGVyY2FsaWZyYWdpbGlzdGljZXhwaWFsaWRvY2lvdXMiCjM) ``` òV ÕËü ñÊ¬Ì :Implcit input of string U & integer V òV :Partitions of U of length V Õ :Transpose Ë :Map ü : Group & sort ñ : Sort by Ê : Length ¬ : Join Ì : Last character :Implicitly join & output ``` ]
[Question] [ This is kind of inspired by the Intel 8086 challenge that's also on here, but I thought a 6502 challenge would be interesting too. ## The challenge I thought this would be a fun one to see the results for. This one is obviously towards the more advanced side of the spectrum. The challenge is to write your own 6502 CPU emulator. This involves, of course, understanding its instruction set and its encoding format. Resources are linked at the bottom of this. The 6502 is one of the easiest real-world processors to emulate. For the purposes of this challenge, you won't need to worry about cycle timing if you don't want to — but that's always a plus to include! DON'T COPY ANYBODY ELSE'S CODE!! Of course, you can certainly peek at other emulators to help you understand, but no copy and pasting! :) Once your code works, you can always go the extra mile if you like and turn it into an Apple II emulator, or NES, C64, VIC-20 or any of the other billions of old 6502-based systems from back in the day. ### Testing your emulator I have compiled a 6502 test suite which I found the source code to here: [AllSuiteA.asm from hcm-6502](https://code.google.com/archive/p/hmc-6502/source/default/source) My [compiled version can be downloaded here](http://rubbermallet.org/AllSuiteA.zip). Load the 48 KB binary into your emulator's memory space at $4000, which leaves 16 KB of read-write RAM below it. When the test has finished executing, the value in address $0210 should be $FF, if your CPU passed. You will know that the test is finished when the program counter (PC) has reached address $45C0. Other tests are available here as well: [6502 Test programs (for emulators and re-implementations)](http://www.6502.org/tools/emu/#tests) ### Doing something more interactive with it Once your CPU works, you probably will want to do something more fun than staring at test output! I compiled a ROM image of Enhanced BASIC for the 6502. It is 16 KB, so you should load it into $C000 of your emulated memory space, reset your virtual 6502, and begin execution. Download this [ZIP, which contains ehbasic.bin](http://rubbermallet.org/ehbasic.zip). The way that EhBASIC handles input/output is very simple. When it wants to write a character to the console, it writes the byte to memory location $F001. So, when your emulator sees the 6502 try to write to that location, simply print that character value to the console with a `printf("%c", value);` or however else you'd like. (This challenge isn't limited to C of course.) When it polls for a character being inputted from the console, it's pretty similar. It keeps reading from memory location $F004, where you should have the next ASCII character value from the keyboard waiting to be read. If there is no more input to read, it should return a value of zero. EhBASIC polls the value at that location until it's non-zero, which lets it know the byte is valid keyboard input. That's why if there's no more input to read, the emulator should return zero there. EhBASIC will spin on it until the next valid key when it's looking for input. If you don't clear that value to zero after it reads the last key value, it will cause it to repeat as if you were holding the key down, so be careful to do that correctly! If your emulator works correctly, this is what you will see printed out on your console when it executes the ROM image: ``` 6502 EhBASIC [C]old/[W]arm ? ``` Press C, then press enter and you should see: ``` Memory size ? 31999 Bytes free Enhanced BASIC 2.22 Ready ``` The bytes free may be different for you, but in my emulator I limited the writable memory area to a cap of 32 KB. You could really go all the way up to where the ROM begins, which is the 48 KB mark. ### 6502 CPU resource links Here are some resources that should give you enough information to work with: * [The Instruction Set](https://cx16.dk/6502/instructions.html) * [6502 Instruction Set](https://www.masswerk.at/6502/6502_instruction_set.html) * [The 6502/65C02/65C816 Instruction Set Decoded](https://llx.com/Neil/a2/opcodes.html) <-- this one has some very interesting info * [MOS Technology 6502](https://en.wikipedia.org/wiki/MOS_Technology_6502) If you have questions or need more technical information, feel free to ask me. There is also a massive wealth of other 6502 info on the web. Google is your friend! [Answer] Thought I would go ahead and post my own implementation. It's COMPLETELY ungolfed, but it's a full implementation. * 668 lines of C. (not counting blank lines or lines with only comments) * Supports (I think) all undocumented instructions. * Supports BCD. * CPU clock cycle timing. (including adjustments on certain page-boundary wraps) * Can execute instructions by either single-step or by specifying number of ticks. * Supports hooking an external function to be called after every instruction is exectued. This was because it was originally for a NES emulator and I used this for audio timing. ``` /* Fake6502 CPU emulator core v1.1 ******************* * (c)2011-2013 Mike Chambers * *****************************************************/ #include <stdio.h> #include <stdint.h> //externally supplied functions extern uint8_t read6502(uint16_t address); extern void write6502(uint16_t address, uint8_t value); //6502 defines #define UNDOCUMENTED //when this is defined, undocumented opcodes are handled. //otherwise, they're simply treated as NOPs. //#define NES_CPU //when this is defined, the binary-coded decimal (BCD) //status flag is not honored by ADC and SBC. the 2A03 //CPU in the Nintendo Entertainment System does not //support BCD operation. #define FLAG_CARRY 0x01 #define FLAG_ZERO 0x02 #define FLAG_INTERRUPT 0x04 #define FLAG_DECIMAL 0x08 #define FLAG_BREAK 0x10 #define FLAG_CONSTANT 0x20 #define FLAG_OVERFLOW 0x40 #define FLAG_SIGN 0x80 #define BASE_STACK 0x100 #define saveaccum(n) a = (uint8_t)((n) & 0x00FF) //flag modifier macros #define setcarry() status |= FLAG_CARRY #define clearcarry() status &= (~FLAG_CARRY) #define setzero() status |= FLAG_ZERO #define clearzero() status &= (~FLAG_ZERO) #define setinterrupt() status |= FLAG_INTERRUPT #define clearinterrupt() status &= (~FLAG_INTERRUPT) #define setdecimal() status |= FLAG_DECIMAL #define cleardecimal() status &= (~FLAG_DECIMAL) #define setoverflow() status |= FLAG_OVERFLOW #define clearoverflow() status &= (~FLAG_OVERFLOW) #define setsign() status |= FLAG_SIGN #define clearsign() status &= (~FLAG_SIGN) //flag calculation macros #define zerocalc(n) {\ if ((n) & 0x00FF) clearzero();\ else setzero();\ } #define signcalc(n) {\ if ((n) & 0x0080) setsign();\ else clearsign();\ } #define carrycalc(n) {\ if ((n) & 0xFF00) setcarry();\ else clearcarry();\ } #define overflowcalc(n, m, o) { /* n = result, m = accumulator, o = memory */ \ if (((n) ^ (uint16_t)(m)) & ((n) ^ (o)) & 0x0080) setoverflow();\ else clearoverflow();\ } //6502 CPU registers uint16_t pc; uint8_t sp, a, x, y, status = FLAG_CONSTANT; //helper variables uint64_t instructions = 0; //keep track of total instructions executed uint32_t clockticks6502 = 0, clockgoal6502 = 0; uint16_t oldpc, ea, reladdr, value, result; uint8_t opcode, oldstatus; //a few general functions used by various other functions void push16(uint16_t pushval) { write6502(BASE_STACK + sp, (pushval >> 8) & 0xFF); write6502(BASE_STACK + ((sp - 1) & 0xFF), pushval & 0xFF); sp -= 2; } void push8(uint8_t pushval) { write6502(BASE_STACK + sp--, pushval); } uint16_t pull16() { uint16_t temp16; temp16 = read6502(BASE_STACK + ((sp + 1) & 0xFF)) | ((uint16_t)read6502(BASE_STACK + ((sp + 2) & 0xFF)) << 8); sp += 2; return(temp16); } uint8_t pull8() { return (read6502(BASE_STACK + ++sp)); } void reset6502() { pc = (uint16_t)read6502(0xFFFC) | ((uint16_t)read6502(0xFFFD) << 8); a = 0; x = 0; y = 0; sp = 0xFD; status |= FLAG_CONSTANT; } static void (*addrtable[256])(); static void (*optable[256])(); uint8_t penaltyop, penaltyaddr; //addressing mode functions, calculates effective addresses static void imp() { //implied } static void acc() { //accumulator } static void imm() { //immediate ea = pc++; } static void zp() { //zero-page ea = (uint16_t)read6502((uint16_t)pc++); } static void zpx() { //zero-page,X ea = ((uint16_t)read6502((uint16_t)pc++) + (uint16_t)x) & 0xFF; //zero-page wraparound } static void zpy() { //zero-page,Y ea = ((uint16_t)read6502((uint16_t)pc++) + (uint16_t)y) & 0xFF; //zero-page wraparound } static void rel() { //relative for branch ops (8-bit immediate value, sign-extended) reladdr = (uint16_t)read6502(pc++); if (reladdr & 0x80) reladdr |= 0xFF00; } static void abso() { //absolute ea = (uint16_t)read6502(pc) | ((uint16_t)read6502(pc+1) << 8); pc += 2; } static void absx() { //absolute,X uint16_t startpage; ea = ((uint16_t)read6502(pc) | ((uint16_t)read6502(pc+1) << 8)); startpage = ea & 0xFF00; ea += (uint16_t)x; if (startpage != (ea & 0xFF00)) { //one cycle penlty for page-crossing on some opcodes penaltyaddr = 1; } pc += 2; } static void absy() { //absolute,Y uint16_t startpage; ea = ((uint16_t)read6502(pc) | ((uint16_t)read6502(pc+1) << 8)); startpage = ea & 0xFF00; ea += (uint16_t)y; if (startpage != (ea & 0xFF00)) { //one cycle penlty for page-crossing on some opcodes penaltyaddr = 1; } pc += 2; } static void ind() { //indirect uint16_t eahelp, eahelp2; eahelp = (uint16_t)read6502(pc) | (uint16_t)((uint16_t)read6502(pc+1) << 8); eahelp2 = (eahelp & 0xFF00) | ((eahelp + 1) & 0x00FF); //replicate 6502 page-boundary wraparound bug ea = (uint16_t)read6502(eahelp) | ((uint16_t)read6502(eahelp2) << 8); pc += 2; } static void indx() { // (indirect,X) uint16_t eahelp; eahelp = (uint16_t)(((uint16_t)read6502(pc++) + (uint16_t)x) & 0xFF); //zero-page wraparound for table pointer ea = (uint16_t)read6502(eahelp & 0x00FF) | ((uint16_t)read6502((eahelp+1) & 0x00FF) << 8); } static void indy() { // (indirect),Y uint16_t eahelp, eahelp2, startpage; eahelp = (uint16_t)read6502(pc++); eahelp2 = (eahelp & 0xFF00) | ((eahelp + 1) & 0x00FF); //zero-page wraparound ea = (uint16_t)read6502(eahelp) | ((uint16_t)read6502(eahelp2) << 8); startpage = ea & 0xFF00; ea += (uint16_t)y; if (startpage != (ea & 0xFF00)) { //one cycle penlty for page-crossing on some opcodes penaltyaddr = 1; } } static uint16_t getvalue() { if (addrtable[opcode] == acc) return((uint16_t)a); else return((uint16_t)read6502(ea)); } static void putvalue(uint16_t saveval) { if (addrtable[opcode] == acc) a = (uint8_t)(saveval & 0x00FF); else write6502(ea, (saveval & 0x00FF)); } //instruction handler functions static void adc() { penaltyop = 1; value = getvalue(); result = (uint16_t)a + value + (uint16_t)(status & FLAG_CARRY); carrycalc(result); zerocalc(result); overflowcalc(result, a, value); signcalc(result); #ifndef NES_CPU if (status & FLAG_DECIMAL) { clearcarry(); if ((a & 0x0F) > 0x09) { a += 0x06; } if ((a & 0xF0) > 0x90) { a += 0x60; setcarry(); } clockticks6502++; } #endif saveaccum(result); } static void and() { penaltyop = 1; value = getvalue(); result = (uint16_t)a & value; zerocalc(result); signcalc(result); saveaccum(result); } static void asl() { value = getvalue(); result = value << 1; carrycalc(result); zerocalc(result); signcalc(result); putvalue(result); } static void bcc() { if ((status & FLAG_CARRY) == 0) { oldpc = pc; pc += reladdr; if ((oldpc & 0xFF00) != (pc & 0xFF00)) clockticks6502 += 2; //check if jump crossed a page boundary else clockticks6502++; } } static void bcs() { if ((status & FLAG_CARRY) == FLAG_CARRY) { oldpc = pc; pc += reladdr; if ((oldpc & 0xFF00) != (pc & 0xFF00)) clockticks6502 += 2; //check if jump crossed a page boundary else clockticks6502++; } } static void beq() { if ((status & FLAG_ZERO) == FLAG_ZERO) { oldpc = pc; pc += reladdr; if ((oldpc & 0xFF00) != (pc & 0xFF00)) clockticks6502 += 2; //check if jump crossed a page boundary else clockticks6502++; } } static void bit() { value = getvalue(); result = (uint16_t)a & value; zerocalc(result); status = (status & 0x3F) | (uint8_t)(value & 0xC0); } static void bmi() { if ((status & FLAG_SIGN) == FLAG_SIGN) { oldpc = pc; pc += reladdr; if ((oldpc & 0xFF00) != (pc & 0xFF00)) clockticks6502 += 2; //check if jump crossed a page boundary else clockticks6502++; } } static void bne() { if ((status & FLAG_ZERO) == 0) { oldpc = pc; pc += reladdr; if ((oldpc & 0xFF00) != (pc & 0xFF00)) clockticks6502 += 2; //check if jump crossed a page boundary else clockticks6502++; } } static void bpl() { if ((status & FLAG_SIGN) == 0) { oldpc = pc; pc += reladdr; if ((oldpc & 0xFF00) != (pc & 0xFF00)) clockticks6502 += 2; //check if jump crossed a page boundary else clockticks6502++; } } static void brk() { pc++; push16(pc); //push next instruction address onto stack push8(status | FLAG_BREAK); //push CPU status to stack setinterrupt(); //set interrupt flag pc = (uint16_t)read6502(0xFFFE) | ((uint16_t)read6502(0xFFFF) << 8); } static void bvc() { if ((status & FLAG_OVERFLOW) == 0) { oldpc = pc; pc += reladdr; if ((oldpc & 0xFF00) != (pc & 0xFF00)) clockticks6502 += 2; //check if jump crossed a page boundary else clockticks6502++; } } static void bvs() { if ((status & FLAG_OVERFLOW) == FLAG_OVERFLOW) { oldpc = pc; pc += reladdr; if ((oldpc & 0xFF00) != (pc & 0xFF00)) clockticks6502 += 2; //check if jump crossed a page boundary else clockticks6502++; } } static void clc() { clearcarry(); } static void cld() { cleardecimal(); } static void cli() { clearinterrupt(); } static void clv() { clearoverflow(); } static void cmp() { penaltyop = 1; value = getvalue(); result = (uint16_t)a - value; if (a >= (uint8_t)(value & 0x00FF)) setcarry(); else clearcarry(); if (a == (uint8_t)(value & 0x00FF)) setzero(); else clearzero(); signcalc(result); } static void cpx() { value = getvalue(); result = (uint16_t)x - value; if (x >= (uint8_t)(value & 0x00FF)) setcarry(); else clearcarry(); if (x == (uint8_t)(value & 0x00FF)) setzero(); else clearzero(); signcalc(result); } static void cpy() { value = getvalue(); result = (uint16_t)y - value; if (y >= (uint8_t)(value & 0x00FF)) setcarry(); else clearcarry(); if (y == (uint8_t)(value & 0x00FF)) setzero(); else clearzero(); signcalc(result); } static void dec() { value = getvalue(); result = value - 1; zerocalc(result); signcalc(result); putvalue(result); } static void dex() { x--; zerocalc(x); signcalc(x); } static void dey() { y--; zerocalc(y); signcalc(y); } static void eor() { penaltyop = 1; value = getvalue(); result = (uint16_t)a ^ value; zerocalc(result); signcalc(result); saveaccum(result); } static void inc() { value = getvalue(); result = value + 1; zerocalc(result); signcalc(result); putvalue(result); } static void inx() { x++; zerocalc(x); signcalc(x); } static void iny() { y++; zerocalc(y); signcalc(y); } static void jmp() { pc = ea; } static void jsr() { push16(pc - 1); pc = ea; } static void lda() { penaltyop = 1; value = getvalue(); a = (uint8_t)(value & 0x00FF); zerocalc(a); signcalc(a); } static void ldx() { penaltyop = 1; value = getvalue(); x = (uint8_t)(value & 0x00FF); zerocalc(x); signcalc(x); } static void ldy() { penaltyop = 1; value = getvalue(); y = (uint8_t)(value & 0x00FF); zerocalc(y); signcalc(y); } static void lsr() { value = getvalue(); result = value >> 1; if (value & 1) setcarry(); else clearcarry(); zerocalc(result); signcalc(result); putvalue(result); } static void nop() { switch (opcode) { case 0x1C: case 0x3C: case 0x5C: case 0x7C: case 0xDC: case 0xFC: penaltyop = 1; break; } } static void ora() { penaltyop = 1; value = getvalue(); result = (uint16_t)a | value; zerocalc(result); signcalc(result); saveaccum(result); } static void pha() { push8(a); } static void php() { push8(status | FLAG_BREAK); } static void pla() { a = pull8(); zerocalc(a); signcalc(a); } static void plp() { status = pull8() | FLAG_CONSTANT; } static void rol() { value = getvalue(); result = (value << 1) | (status & FLAG_CARRY); carrycalc(result); zerocalc(result); signcalc(result); putvalue(result); } static void ror() { value = getvalue(); result = (value >> 1) | ((status & FLAG_CARRY) << 7); if (value & 1) setcarry(); else clearcarry(); zerocalc(result); signcalc(result); putvalue(result); } static void rti() { status = pull8(); value = pull16(); pc = value; } static void rts() { value = pull16(); pc = value + 1; } static void sbc() { penaltyop = 1; value = getvalue() ^ 0x00FF; result = (uint16_t)a + value + (uint16_t)(status & FLAG_CARRY); carrycalc(result); zerocalc(result); overflowcalc(result, a, value); signcalc(result); #ifndef NES_CPU if (status & FLAG_DECIMAL) { clearcarry(); a -= 0x66; if ((a & 0x0F) > 0x09) { a += 0x06; } if ((a & 0xF0) > 0x90) { a += 0x60; setcarry(); } clockticks6502++; } #endif saveaccum(result); } static void sec() { setcarry(); } static void sed() { setdecimal(); } static void sei() { setinterrupt(); } static void sta() { putvalue(a); } static void stx() { putvalue(x); } static void sty() { putvalue(y); } static void tax() { x = a; zerocalc(x); signcalc(x); } static void tay() { y = a; zerocalc(y); signcalc(y); } static void tsx() { x = sp; zerocalc(x); signcalc(x); } static void txa() { a = x; zerocalc(a); signcalc(a); } static void txs() { sp = x; } static void tya() { a = y; zerocalc(a); signcalc(a); } //undocumented instructions #ifdef UNDOCUMENTED static void lax() { lda(); ldx(); } static void sax() { sta(); stx(); putvalue(a & x); if (penaltyop && penaltyaddr) clockticks6502--; } static void dcp() { dec(); cmp(); if (penaltyop && penaltyaddr) clockticks6502--; } static void isb() { inc(); sbc(); if (penaltyop && penaltyaddr) clockticks6502--; } static void slo() { asl(); ora(); if (penaltyop && penaltyaddr) clockticks6502--; } static void rla() { rol(); and(); if (penaltyop && penaltyaddr) clockticks6502--; } static void sre() { lsr(); eor(); if (penaltyop && penaltyaddr) clockticks6502--; } static void rra() { ror(); adc(); if (penaltyop && penaltyaddr) clockticks6502--; } #else #define lax nop #define sax nop #define dcp nop #define isb nop #define slo nop #define rla nop #define sre nop #define rra nop #endif static void (*addrtable[256])() = { /* | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F | */ /* 0 */ imp, indx, imp, indx, zp, zp, zp, zp, imp, imm, acc, imm, abso, abso, abso, abso, /* 0 */ /* 1 */ rel, indy, imp, indy, zpx, zpx, zpx, zpx, imp, absy, imp, absy, absx, absx, absx, absx, /* 1 */ /* 2 */ abso, indx, imp, indx, zp, zp, zp, zp, imp, imm, acc, imm, abso, abso, abso, abso, /* 2 */ /* 3 */ rel, indy, imp, indy, zpx, zpx, zpx, zpx, imp, absy, imp, absy, absx, absx, absx, absx, /* 3 */ /* 4 */ imp, indx, imp, indx, zp, zp, zp, zp, imp, imm, acc, imm, abso, abso, abso, abso, /* 4 */ /* 5 */ rel, indy, imp, indy, zpx, zpx, zpx, zpx, imp, absy, imp, absy, absx, absx, absx, absx, /* 5 */ /* 6 */ imp, indx, imp, indx, zp, zp, zp, zp, imp, imm, acc, imm, ind, abso, abso, abso, /* 6 */ /* 7 */ rel, indy, imp, indy, zpx, zpx, zpx, zpx, imp, absy, imp, absy, absx, absx, absx, absx, /* 7 */ /* 8 */ imm, indx, imm, indx, zp, zp, zp, zp, imp, imm, imp, imm, abso, abso, abso, abso, /* 8 */ /* 9 */ rel, indy, imp, indy, zpx, zpx, zpy, zpy, imp, absy, imp, absy, absx, absx, absy, absy, /* 9 */ /* A */ imm, indx, imm, indx, zp, zp, zp, zp, imp, imm, imp, imm, abso, abso, abso, abso, /* A */ /* B */ rel, indy, imp, indy, zpx, zpx, zpy, zpy, imp, absy, imp, absy, absx, absx, absy, absy, /* B */ /* C */ imm, indx, imm, indx, zp, zp, zp, zp, imp, imm, imp, imm, abso, abso, abso, abso, /* C */ /* D */ rel, indy, imp, indy, zpx, zpx, zpx, zpx, imp, absy, imp, absy, absx, absx, absx, absx, /* D */ /* E */ imm, indx, imm, indx, zp, zp, zp, zp, imp, imm, imp, imm, abso, abso, abso, abso, /* E */ /* F */ rel, indy, imp, indy, zpx, zpx, zpx, zpx, imp, absy, imp, absy, absx, absx, absx, absx /* F */ }; static void (*optable[256])() = { /* | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F | */ /* 0 */ brk, ora, nop, slo, nop, ora, asl, slo, php, ora, asl, nop, nop, ora, asl, slo, /* 0 */ /* 1 */ bpl, ora, nop, slo, nop, ora, asl, slo, clc, ora, nop, slo, nop, ora, asl, slo, /* 1 */ /* 2 */ jsr, and, nop, rla, bit, and, rol, rla, plp, and, rol, nop, bit, and, rol, rla, /* 2 */ /* 3 */ bmi, and, nop, rla, nop, and, rol, rla, sec, and, nop, rla, nop, and, rol, rla, /* 3 */ /* 4 */ rti, eor, nop, sre, nop, eor, lsr, sre, pha, eor, lsr, nop, jmp, eor, lsr, sre, /* 4 */ /* 5 */ bvc, eor, nop, sre, nop, eor, lsr, sre, cli, eor, nop, sre, nop, eor, lsr, sre, /* 5 */ /* 6 */ rts, adc, nop, rra, nop, adc, ror, rra, pla, adc, ror, nop, jmp, adc, ror, rra, /* 6 */ /* 7 */ bvs, adc, nop, rra, nop, adc, ror, rra, sei, adc, nop, rra, nop, adc, ror, rra, /* 7 */ /* 8 */ nop, sta, nop, sax, sty, sta, stx, sax, dey, nop, txa, nop, sty, sta, stx, sax, /* 8 */ /* 9 */ bcc, sta, nop, nop, sty, sta, stx, sax, tya, sta, txs, nop, nop, sta, nop, nop, /* 9 */ /* A */ ldy, lda, ldx, lax, ldy, lda, ldx, lax, tay, lda, tax, nop, ldy, lda, ldx, lax, /* A */ /* B */ bcs, lda, nop, lax, ldy, lda, ldx, lax, clv, lda, tsx, lax, ldy, lda, ldx, lax, /* B */ /* C */ cpy, cmp, nop, dcp, cpy, cmp, dec, dcp, iny, cmp, dex, nop, cpy, cmp, dec, dcp, /* C */ /* D */ bne, cmp, nop, dcp, nop, cmp, dec, dcp, cld, cmp, nop, dcp, nop, cmp, dec, dcp, /* D */ /* E */ cpx, sbc, nop, isb, cpx, sbc, inc, isb, inx, sbc, nop, sbc, cpx, sbc, inc, isb, /* E */ /* F */ beq, sbc, nop, isb, nop, sbc, inc, isb, sed, sbc, nop, isb, nop, sbc, inc, isb /* F */ }; static const uint32_t ticktable[256] = { /* | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F | */ /* 0 */ 7, 6, 2, 8, 3, 3, 5, 5, 3, 2, 2, 2, 4, 4, 6, 6, /* 0 */ /* 1 */ 2, 5, 2, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7, /* 1 */ /* 2 */ 6, 6, 2, 8, 3, 3, 5, 5, 4, 2, 2, 2, 4, 4, 6, 6, /* 2 */ /* 3 */ 2, 5, 2, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7, /* 3 */ /* 4 */ 6, 6, 2, 8, 3, 3, 5, 5, 3, 2, 2, 2, 3, 4, 6, 6, /* 4 */ /* 5 */ 2, 5, 2, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7, /* 5 */ /* 6 */ 6, 6, 2, 8, 3, 3, 5, 5, 4, 2, 2, 2, 5, 4, 6, 6, /* 6 */ /* 7 */ 2, 5, 2, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7, /* 7 */ /* 8 */ 2, 6, 2, 6, 3, 3, 3, 3, 2, 2, 2, 2, 4, 4, 4, 4, /* 8 */ /* 9 */ 2, 6, 2, 6, 4, 4, 4, 4, 2, 5, 2, 5, 5, 5, 5, 5, /* 9 */ /* A */ 2, 6, 2, 6, 3, 3, 3, 3, 2, 2, 2, 2, 4, 4, 4, 4, /* A */ /* B */ 2, 5, 2, 5, 4, 4, 4, 4, 2, 4, 2, 4, 4, 4, 4, 4, /* B */ /* C */ 2, 6, 2, 8, 3, 3, 5, 5, 2, 2, 2, 2, 4, 4, 6, 6, /* C */ /* D */ 2, 5, 2, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7, /* D */ /* E */ 2, 6, 2, 8, 3, 3, 5, 5, 2, 2, 2, 2, 4, 4, 6, 6, /* E */ /* F */ 2, 5, 2, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7 /* F */ }; void nmi6502() { push16(pc); push8(status); status |= FLAG_INTERRUPT; pc = (uint16_t)read6502(0xFFFA) | ((uint16_t)read6502(0xFFFB) << 8); } void irq6502() { push16(pc); push8(status); status |= FLAG_INTERRUPT; pc = (uint16_t)read6502(0xFFFE) | ((uint16_t)read6502(0xFFFF) << 8); } uint8_t callexternal = 0; void (*loopexternal)(); void exec6502(uint32_t tickcount) { clockgoal6502 += tickcount; while (clockticks6502 < clockgoal6502) { opcode = read6502(pc++); penaltyop = 0; penaltyaddr = 0; (*addrtable[opcode])(); (*optable[opcode])(); clockticks6502 += ticktable[opcode]; if (penaltyop && penaltyaddr) clockticks6502++; instructions++; if (callexternal) (*loopexternal)(); } } void step6502() { opcode = read6502(pc++); penaltyop = 0; penaltyaddr = 0; (*addrtable[opcode])(); (*optable[opcode])(); clockticks6502 += ticktable[opcode]; if (penaltyop && penaltyaddr) clockticks6502++; clockgoal6502 = clockticks6502; instructions++; if (callexternal) (*loopexternal)(); } void hookexternal(void *funcptr) { if (funcptr != (void *)NULL) { loopexternal = funcptr; callexternal = 1; } else callexternal = 0; } ``` [Answer] A MOS 6502 emulator in Haskell. Features include: * bit accurate implementation including subtle P register handling and page wrapping during indexing and indirection * memory mapped IO, with spin loop detection (so host CPU doesn't peg while waiting for input) * halt detection (jumps/branches to self) * CPU implemented in exactly 200 lines & 6502 characters of code * CPU implementation is pure state monad This is a somewhat golf'd version of a full implementation (with more features) I did for this challenge that I'll post later. Despite the golf, the code is still straight forward. Only known missing feature is BCD mode (coming...) Runs the ehBASIC code: ``` & ghc -O2 -o z6502min -Wall -fwarn-tabs -fno-warn-missing-signatures Z6502.hs [1 of 1] Compiling Main ( Z6502.hs, Z6502.o ) Z6502.hs:173:1: Warning: Defined but not used: `nmi' Z6502.hs:174:1: Warning: Defined but not used: `irq' Linking z6502min ... & ./z6502min ehbasic.bin 6502 EhBASIC [C]old/[W]arm ? Memory size ? 48383 Bytes free Enhanced BASIC 2.22 Ready PRINT "Hello World" Hello World Ready 10 FOR I = 1 TO 10 20 FOR J = 1 TO I 30 PRINT J; 40 NEXT J 50 PRINT 60 NEXT I RUN 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 1 2 3 4 5 6 7 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 10 Ready ``` And the code, at under 300 lines total: ``` -- Z6502: a 6502 emulator -- by Mark Lentczner module Main (main) where import Control.Applicative import Control.Monad import Control.Monad.State.Strict import Data.Bits import qualified Data.ByteString as B import Data.List import qualified Data.Vector as V import qualified Data.Vector.Unboxed as VU import Data.Word import System.Environment import System.IO {- === CPU: 200 lines, 6502 characters === -} type Addr = Word16 toAd = fromIntegral :: Int -> Addr addr :: Word8 -> Word8 -> Addr addr lo hi = fromIntegral hi `shiftL` 8 .|. fromIntegral lo lohi ad = (fromIntegral ad, fromIntegral $ ad `shiftR` 8) zeroPage v = addr v 0 index ad idx = ad + fromIntegral (idx :: Word8) relativeAddr ad off = index ad off - if off > 0x7f then 256 else 0 data Page = Missing | ROM !B.ByteString | RAM !(VU.Vector Word8) type Memory = V.Vector Page emptyMemory = V.replicate 256 Missing fetchByte ad mv = case mv V.! hi of ROM bs -> B.index bs lo RAM vs -> vs VU.! lo _ -> 0 where (hi,lo) = fromIntegral ad `divMod` 256 storeByte ad v mv = case mv V.! hi of RAM vs -> mv V.// [(hi, RAM $ vs VU.// [(lo, v)])] _ -> mv where (hi,lo) = fromIntegral ad `divMod` 256 data S = S { rA, rX, rY, rP, rS :: !Word8, rPC :: !Addr , mem :: !Memory, busR,busW :: Maybe Addr } powerOnState = S 0 0 0 0 0 0 emptyMemory Nothing Nothing [bitN, bitV, bitX, bitB, bitD, bitI, bitZ, bitC] = [7,6..0] toBit b t v = (if t then setBit else clearBit) v b toZ v = toBit bitZ (v == 0) toZN v = toBit bitZ (v == 0) . toBit bitN (testBit v 7) to67 v = toBit bitV (testBit v 6) . toBit bitN (testBit v 7) setZN v = modify $ \s -> s { rP = toZN v $ rP s } setAZN v = modify $ \s -> s { rA = v, rP=toZN v $ rP s } setXZN v = modify $ \s -> s { rX = v, rP=toZN v $ rP s } setYZN v = modify $ \s -> s { rY = v, rP=toZN v $ rP s } setZVNbit (a,v) = modify $ \s -> s { rP = toZ (a .&. v) $ to67 v $ rP s } setACZVN (c,v,a) = modify $ \s -> s { rA = a, rP = toBit bitC c $ toBit bitV v $ toZN a $ rP s } setCZN (c,v) = modify $ \s -> s { rP = toBit bitC c $ toZN v $ rP s } fetch a = state $ \s -> (fetchByte a $ mem s, s { busR = Just a }) fetchIndirectAddr a0 = do m <- gets mem let (lo,hi) = lohi a0 a1 = addr (lo+1) hi bLo = fetchByte a0 m bHi = fetchByte a1 m return $ addr bLo bHi store a v = modify $ \s -> s { mem = storeByte a v $ mem s, busW = Just a } clearBus = modify $ \s -> s { busR = Nothing, busW = Nothing } nextPC = state $ \s -> (rPC s, s { rPC = rPC s + 1 }) fetchPC = nextPC >>= \a -> gets mem >>= return . fetchByte a adjSP n m = state $ \s -> (addr (rS s + m) 1, s { rS = rS s + n }) push v = adjSP (-1) 0 >>= flip store v pull = adjSP 1 1 >>= fetch pushAddr a = let (lo, hi) = lohi a in push hi >> push lo pullAddr = addr <$> pull <*> pull pushP fromSW = gets rP >>= push . toBit bitX True . toBit bitB fromSW pullP = pull >>= \v -> modify $ \s -> s { rP = v .&. 0xCF } indexX a = gets rX >>= return . index a indexY a = gets rY >>= return . index a aImm=nextPC aZero=zeroPage<$>fetchPC aZeroX=zeroPage<$>((+)<$>fetchPC<*>gets rX) aZeroY=zeroPage<$>((+)<$>fetchPC<*>gets rY) aRel=flip relativeAddr<$>fetchPC<*>gets rPC aAbs=addr<$>fetchPC<*>fetchPC aAbsX=aAbs>>=indexX aAbsY=aAbs>>=indexY aInd=aAbs>>=fetchIndirectAddr aIndIdx=aZeroX>>=fetchIndirectAddr aIdxInd=aZero>>=fetchIndirectAddr>>=indexY decode = V.fromList $ concat $ transpose [[iBRK,iBPL,iJSR&aAbs,iBMI,iRTI,iBVC,iRTS,iBVS ,iErr,iBCC,iLDY&aImm,iBCS,iCPY&aImm,iBNE,iCPX&aImm,iBEQ] ,cAlu aIndIdx aIdxInd ,cErr//(10,iLDX&aImm) ,cErr ,[iErr,iErr,iBIT&aZero,iErr,iErr,iErr,iErr,iErr ,iSTY&aZero,iSTY&aZeroX,iLDY&aZero,iLDY&aZeroX,iCPY&aZero,iErr,iCPX&aZero,iErr] ,cAlu aZero aZeroX ,cBit aZero aZeroX//(9,iSTX&aZeroY)//(11,iLDX&aZeroY) ,cErr ,[iPHP,iCLC,iPLP,iSEC,iPHA,iCLI,iPLA,iSEI,iDEY,iTYA,iTAY,iCLV,iINY,iCLD,iINX,iSED] ,cAlu aImm aAbsY//(8,iErr) ,[iASLa,iErr,iROLa,iErr,iLSRa,iErr,iRORa,iErr ,iTXA,iTXS,iTAX,iTSX,iDEX,iErr,iNOP,iErr ] ,cErr ,[iErr,iErr,iBIT&aAbs,iErr,iJMP&aAbs,iErr,iJMP&aInd,iErr ,iSTY&aAbs,iErr,iLDY&aAbs,iLDY&aAbsX,iCPY&aAbs,iErr,iCPX&aAbs,iErr] ,cAlu aAbs aAbsX ,cBit aAbs aAbsX//(9,iErr)//(11,iLDX&aAbsY) ,cErr ] cAlt is e o = is >>= (\i->[i&e,i&o]) cAlu = cAlt [iORA,iAND,iEOR,iADC,iSTA,iLDA,iCMP,iSBC] cBit = cAlt [iASL,iROL,iLSR,iROR,iSTX,iLDX,iDEC,iINC] cErr = replicate 16 iErr is//(n,j) = let (f,_:h) = splitAt n is in f++j:h i&a=a>>=i loadIns l a = fetch a >>= l storeIns f a = f >>= store a aluIns set op ad = do v <- fetch ad a <- gets rA set $ op a v modIns op a = fetch a >>= op >>= store a modAccIns op = gets rA >>= op >>= \v -> modify $ \s -> s { rA = v } stIns b op = modify $ \s -> s { rP = op (rP s) b } jump a = modify $ \s -> s { rPC = a } brIns b t = do a <- aRel p <- gets rP when (testBit p b == t) $ jump a adcOp a b cIn = (cOut, v, s) where h = b + (if cIn then 1 else 0) s = a + h cOut = h < b || s < a v = testBit (a `xor` s .&. b `xor` s) 7 sbcOp a b cIn = adcOp a (complement b) cIn carryOp f = gets rP >>= setACZVN . f . flip testBit bitC cmpOp a b = (a >= b, a - b) shiftOp shifter isRot inBit outBit v = do s <- get let newC = testBit v outBit bitIn = toBit inBit $ isRot && testBit (rP s) bitC v' = bitIn $ shifter v 1 put s { rP = toBit bitC newC $ toZN v' $ rP s } return v' vector a = fetchIndirectAddr a >>= jump interrupt isBrk pcOffset a = do gets rPC >>= pushAddr . flip index pcOffset pushP isBrk iSEI vector a reset = vector $ toAd 0xFFFC nmi = interrupt False 0 $ toAd 0xFFFA irq = interrupt False 0 $ toAd 0xFFFE [iORA,iAND,iEOR]=aluIns setAZN<$>[(.|.),(.&.),xor] [iADC,iSBC]=aluIns carryOp<$>[adcOp,sbcOp] iSTA=storeIns$gets rA iLDA=loadIns setAZN iCMP=aluIns setCZN cmpOp [iSTX,iSTY]=storeIns.gets<$>[rX,rY] [iLDX,iLDY]=loadIns<$>[setXZN,setYZN] [iCPX,iCPY]=(\r a->gets r>>= \v->fetch a>>=setCZN.cmpOp v)<$>[rX,rY] [iDEC,iINC]=modIns.(\i v->setZN(v+i)>>return(v+i))<$>[-1,1] [iDEX,iINX]=(gets rX>>=).(setXZN.).(+)<$>[-1,1] [iDEY,iINY]=(gets rY>>=).(setYZN.).(+)<$>[-1,1] shOps=[shiftOp d r b(7-b)|(d,b)<-[(shiftL,0),(shiftR,7)],r<-[False,True]] [iASL,iROL,iLSR,iROR]=modIns<$>shOps [iASLa,iROLa,iLSRa,iRORa]=modAccIns<$>shOps iBIT=aluIns setZVNbit(,) iJMP=jump [iBPL,iBMI,iBVC,iBVS,iBCC,iBCS,iBNE,iBEQ]=brIns<$>[bitN,bitV,bitC,bitZ]<*>[False,True] [iCLC,iSEC,iCLI,iSEI,iCLV,_,iCLD,iSED]=stIns<$>[bitC,bitI,bitV,bitD]<*>[clearBit,setBit] iBRK=interrupt True 1 $ toAd 0xFFFE iJSR a=gets rPC>>=pushAddr.(-1+)>>jump a iRTI=iPLP>>pullAddr>>=jump iRTS=pullAddr>>=jump.(1+) iPHP=pushP True iPLP=pullP iPHA=gets rA>>=push iPLA=pull>>=setAZN iNOP=return () [iTAX,iTAY]=(gets rA>>=)<$>[setXZN,setYZN] [iTXA,iTYA]=(>>=setAZN).gets<$>[rX,rY] iTXS=modify $ \s -> s { rS=rX s } iTSX=gets rS>>=setXZN iErr=gets rPC>>=jump.(-1+) executeOne = clearBus >> fetchPC >>= (decode V.!) . fromIntegral {- === END OF CPU === -} {- === MOTHERBOARD === -} buildMemory rom = loadRAM 0xF0 1 $ loadRAM 0x00 ramSize $ loadROM romStart rom $ emptyMemory where ramSize = 256 - (B.length rom `div` 256) romStart = fromIntegral ramSize loadRAM p0 n = (V.// zip [p0..] (map RAM $ replicate n ramPage)) ramPage = VU.replicate 256 0 loadROM p0 bs = (V.// zip [p0..] (map ROM $ romPages bs)) romPages b = case B.length b of l | l == 0 -> [] | l < 256 -> [b `B.append` B.replicate (256 - l) 0] | l == 256 -> [b] | otherwise -> let (b0,bn) = B.splitAt 256 b in b0 : romPages bn main = getArgs >>= go where go [romFile] = B.readFile romFile >>= exec . buildState . buildMemory go _ = putStrLn "agument should be a single ROM file" buildState m = execState reset (powerOnState { mem = m }) exec s0 = do stopIO <- startIO loop (0 :: Int) s0 stopIO loop n s = do let pcsp = (rPC s, rS s) (n',s') <- processIO n (execState executeOne s) let pcsp' = (rPC s', rS s') if pcsp /= pcsp' then (loop $! n') $! s' else do putStrLn $ "Execution snagged at " ++ show (fst pcsp') startIO = do ibuf <- hGetBuffering stdin obuf <- hGetBuffering stdout iecho <- hGetEcho stdin hSetBuffering stdin NoBuffering hSetBuffering stdout NoBuffering hSetEcho stdin False return $ do hSetEcho stdin iecho hSetBuffering stdin ibuf hSetBuffering stdout obuf putStr "\n\n" processIO n s = do when (busW s == Just outPortAddr) $ do let c = fetchByte outPortAddr $ mem s when (c /= 0) $ hPutChar stdout $ toEnum $ fromIntegral c if (busR s == Just inPortAddr) then do r <- if n < 16 then hWaitForInput stdin 50 else hReady stdin c <- if r then (fromIntegral . fromEnum) <$> hGetChar stdin else return 0 let c' = if c == 0xA then 0xD else c let s' = s { mem = storeByte inPortAddr c' $ mem s } return (0,s') else return (n+1,s) inPortAddr = toAd 0xF004 outPortAddr = toAd 0xF001 ``` [Answer] For anyone interested I thought I would share my implementation of the 6502 in C#. As with other posts here it is completely ungolfed but is a feature complete implementation. * Supports NMOS and CMOS * Includes several test programs including the AllSuite test above as Unit Tests. * Supports BCD I started this project by creating a spreadsheet of instructions when I was first learning about the CPU. I realized I could use this spreadsheet to save myself some typing. I turned this into a text file table that the emulator loads to help count cycles and for easy disassembly output. Entire project is available on Github <https://github.com/amensch/e6502> ``` /* * e6502: A complete 6502 CPU emulator. * Copyright 2016 Adam Mensch */ using System; namespace e6502CPU { public enum e6502Type { CMOS, NMOS }; public class e6502 { // Main Register public byte A; // Index Registers public byte X; public byte Y; // Program Counter public ushort PC; // Stack Pointer // Memory location is hard coded to 0x01xx // Stack is descending (decrement on push, increment on pop) // 6502 is an empty stack so SP points to where next value is stored public byte SP; // Status Registers (in order bit 7 to 0) public bool NF; // negative flag (N) public bool VF; // overflow flag (V) // bit 5 is unused // bit 4 is the break flag however it is not a physical flag in the CPU public bool DF; // binary coded decimal flag (D) public bool IF; // interrupt flag (I) public bool ZF; // zero flag (Z) public bool CF; // carry flag (C) // RAM - 16 bit address bus means 64KB of addressable memory public byte[] memory; // List of op codes and their attributes private OpCodeTable _opCodeTable; // The current opcode private OpCodeRecord _currentOP; // Clock cycles to adjust due to page boundaries being crossed, branches taken, or NMOS/CMOS differences private int _extraCycles; // Flag for hardware interrupt (IRQ) public bool IRQWaiting { get; set; } // Flag for non maskable interrupt (NMI) public bool NMIWaiting { get; set; } public e6502Type _cpuType { get; set; } public e6502(e6502Type type) { memory = new byte[0x10000]; _opCodeTable = new OpCodeTable(); // Set these on instantiation so they are known values when using this object in testing. // Real programs should explicitly load these values before using them. A = 0; X = 0; Y = 0; SP = 0; PC = 0; NF = false; VF = false; DF = false; IF = true; ZF = false; CF = false; NMIWaiting = false; IRQWaiting = false; _cpuType = type; } public void Boot() { // On reset the addresses 0xfffc and 0xfffd are read and PC is loaded with this value. // It is expected that the initial program loaded will have these values set to something. // Most 6502 systems contain ROM in the upper region (around 0xe000-0xffff) PC = GetWordFromMemory(0xfffc); // interrupt disabled is set on powerup IF = true; NMIWaiting = false; IRQWaiting = false; } public void LoadProgram(ushort startingAddress, byte[] program) { program.CopyTo(memory, startingAddress); PC = startingAddress; } public string DasmNextInstruction() { OpCodeRecord oprec = _opCodeTable.OpCodes[ memory[PC] ]; if (oprec.Bytes == 3) return oprec.Dasm( GetImmWord() ); else return oprec.Dasm( GetImmByte() ); } // returns # of clock cycles needed to execute the instruction public int ExecuteNext() { _extraCycles = 0; // Check for non maskable interrupt (has higher priority over IRQ) if (NMIWaiting) { DoIRQ(0xfffa); NMIWaiting = false; _extraCycles += 6; } // Check for hardware interrupt, if enabled else if (!IF) { if(IRQWaiting) { DoIRQ(0xfffe); IRQWaiting = false; _extraCycles += 6; } } _currentOP = _opCodeTable.OpCodes[memory[PC]]; ExecuteInstruction(); return _currentOP.Cycles + _extraCycles; } private void ExecuteInstruction() { int result; int oper = GetOperand(_currentOP.AddressMode); switch (_currentOP.OpCode) { // ADC - add memory to accumulator with carry // A+M+C -> A,C (NZCV) case 0x61: case 0x65: case 0x69: case 0x6d: case 0x71: case 0x72: case 0x75: case 0x79: case 0x7d: if (DF) { result = HexToBCD(A) + HexToBCD((byte)oper); if (CF) result++; CF = (result > 99); if (result > 99 ) { result -= 100; } ZF = (result == 0); // convert decimal result to hex BCD result A = BCDToHex(result); // Unlike ZF and CF, the NF flag represents the MSB after conversion // to BCD. NF = (A > 0x7f); // extra clock cycle on CMOS in decimal mode if (_cpuType == e6502Type.CMOS) _extraCycles++; } else { ADC((byte)oper); } PC += _currentOP.Bytes; break; // AND - and memory with accumulator // A AND M -> A (NZ) case 0x21: case 0x25: case 0x29: case 0x2d: case 0x31: case 0x32: case 0x35: case 0x39: case 0x3d: result = A & oper; NF = ((result & 0x80) == 0x80); ZF = ((result & 0xff) == 0x00); A = (byte)result; PC += _currentOP.Bytes; break; // ASL - shift left one bit (NZC) // C <- (76543210) <- 0 case 0x06: case 0x16: case 0x0a: case 0x0e: case 0x1e: // On 65C02 (abs,X) takes one less clock cycle (but still add back 1 if page boundary crossed) if (_currentOP.OpCode == 0x1e && _cpuType == e6502Type.CMOS) _extraCycles--; // shift bit 7 into carry CF = (oper >= 0x80); // shift operand result = oper << 1; NF = ((result & 0x80) == 0x80); ZF = ((result & 0xff) == 0x00); SaveOperand(_currentOP.AddressMode, result); PC += _currentOP.Bytes; break; // BBRx - test bit in memory (no flags) // Test the zero page location and branch of the specified bit is clear // These instructions are only available on Rockwell and WDC 65C02 chips. // Number of clock cycles is the same regardless if the branch is taken. case 0x0f: case 0x1f: case 0x2f: case 0x3f: case 0x4f: case 0x5f: case 0x6f: case 0x7f: // upper nibble specifies the bit to check byte check_bit = (byte)(_currentOP.OpCode >> 4); byte check_value = 0x01; for( int ii=0; ii < check_bit; ii++) { check_value = (byte)(check_value << 1); } // if the specified bit is 0 then branch byte offset = memory[PC + 2]; PC += _currentOP.Bytes; if ((oper & check_value) == 0x00) PC += offset; break; // BBSx - test bit in memory (no flags) // Test the zero page location and branch of the specified bit is set // These instructions are only available on Rockwell and WDC 65C02 chips. // Number of clock cycles is the same regardless if the branch is taken. case 0x8f: case 0x9f: case 0xaf: case 0xbf: case 0xcf: case 0xdf: case 0xef: case 0xff: // upper nibble specifies the bit to check (but ignore bit 7) check_bit = (byte)((_currentOP.OpCode & 0x70) >> 4); check_value = 0x01; for (int ii = 0; ii < check_bit; ii++) { check_value = (byte)(check_value << 1); } // if the specified bit is 1 then branch offset = memory[PC + 2]; PC += _currentOP.Bytes; if ((oper & check_value) == check_value) PC += offset; break; // BCC - branch on carry clear case 0x90: PC += _currentOP.Bytes; CheckBranch(!CF, oper); break; // BCS - branch on carry set case 0xb0: PC += _currentOP.Bytes; CheckBranch(CF, oper); break; // BEQ - branch on zero case 0xf0: PC += _currentOP.Bytes; CheckBranch(ZF, oper); break; // BIT - test bits in memory with accumulator (NZV) // bits 7 and 6 of oper are transferred to bits 7 and 6 of conditional register (N and V) // the zero flag is set to the result of oper AND accumulator case 0x24: case 0x2c: // added by 65C02 case 0x34: case 0x3c: case 0x89: result = A & oper; // The WDC programming manual for 65C02 indicates NV are unaffected in immediate mode. // The extended op code test program reflects this. if (_currentOP.AddressMode != AddressModes.Immediate) { NF = ((oper & 0x80) == 0x80); VF = ((oper & 0x40) == 0x40); } ZF = ((result & 0xff) == 0x00); PC += _currentOP.Bytes; break; // BMI - branch on negative case 0x30: PC += _currentOP.Bytes; CheckBranch(NF, oper); break; // BNE - branch on non zero case 0xd0: PC += _currentOP.Bytes; CheckBranch(!ZF, oper); break; // BPL - branch on non negative case 0x10: PC += _currentOP.Bytes; CheckBranch(!NF, oper); break; // BRA - unconditional branch to immediate address // NOTE: In OpcodeList.txt the number of clock cycles is one less than the documentation. // This is because CheckBranch() adds one when a branch is taken, which in this case is always. case 0x80: PC += _currentOP.Bytes; CheckBranch(true, oper); break; // BRK - force break (I) case 0x00: // This is a software interrupt (IRQ). These events happen in a specific order. // Processor adds two to the current PC PC += 2; // Call IRQ routine DoIRQ(0xfffe, true); // Whether or not the decimal flag is cleared depends on the type of 6502 CPU. // The CMOS 65C02 clears this flag but the NMOS 6502 does not. if( _cpuType == e6502Type.CMOS ) DF = false; break; // BVC - branch on overflow clear case 0x50: PC += _currentOP.Bytes; CheckBranch(!VF, oper); break; // BVS - branch on overflow set case 0x70: PC += _currentOP.Bytes; CheckBranch(VF, oper); break; // CLC - clear carry flag case 0x18: CF = false; PC += _currentOP.Bytes; break; // CLD - clear decimal mode case 0xd8: DF = false; PC += _currentOP.Bytes; break; // CLI - clear interrupt disable bit case 0x58: IF = false; PC += _currentOP.Bytes; break; // CLV - clear overflow flag case 0xb8: VF = false; PC += _currentOP.Bytes; break; // CMP - compare memory with accumulator (NZC) // CMP, CPX and CPY are unsigned comparisions case 0xc5: case 0xc9: case 0xc1: case 0xcd: case 0xd1: case 0xd2: case 0xd5: case 0xd9: case 0xdd: byte temp = (byte)(A - oper); CF = A >= (byte)oper; ZF = A == (byte)oper; NF = ((temp & 0x80) == 0x80); PC += _currentOP.Bytes; break; // CPX - compare memory and X (NZC) case 0xe0: case 0xe4: case 0xec: temp = (byte)(X - oper); CF = X >= (byte)oper; ZF = X == (byte)oper; NF = ((temp & 0x80) == 0x80); PC += _currentOP.Bytes; break; // CPY - compare memory and Y (NZC) case 0xc0: case 0xc4: case 0xcc: temp = (byte)(Y - oper); CF = Y >= (byte)oper; ZF = Y == (byte)oper; NF = ((temp & 0x80) == 0x80); PC += _currentOP.Bytes; break; // DEC - decrement memory by 1 (NZ) case 0xc6: case 0xce: case 0xd6: case 0xde: // added by 65C02 case 0x3a: result = oper - 1; ZF = ((result & 0xff) == 0x00); NF = ((result & 0x80) == 0x80); SaveOperand(_currentOP.AddressMode, result); PC += _currentOP.Bytes; break; // DEX - decrement X by one (NZ) case 0xca: result = X - 1; ZF = ((result & 0xff) == 0x00); NF = ((result & 0x80) == 0x80); X = (byte)result; PC += _currentOP.Bytes; break; // DEY - decrement Y by one (NZ) case 0x88: result = Y - 1; ZF = ((result & 0xff) == 0x00); NF = ((result & 0x80) == 0x80); Y = (byte)result; PC += _currentOP.Bytes; break; // EOR - XOR memory with accumulator (NZ) case 0x41: case 0x45: case 0x49: case 0x4d: case 0x51: case 0x52: case 0x55: case 0x59: case 0x5d: result = A ^ (byte)oper; ZF = ((result & 0xff) == 0x00); NF = ((result & 0x80) == 0x80); A = (byte)result; PC += _currentOP.Bytes; break; // INC - increment memory by 1 (NZ) case 0xe6: case 0xee: case 0xf6: case 0xfe: // added by 65C02 case 0x1a: result = oper + 1; ZF = ((result & 0xff) == 0x00); NF = ((result & 0x80) == 0x80); SaveOperand(_currentOP.AddressMode, result); PC += _currentOP.Bytes; break; // INX - increment X by one (NZ) case 0xe8: result = X + 1; ZF = ((result & 0xff) == 0x00); NF = ((result & 0x80) == 0x80); X = (byte)result; PC += _currentOP.Bytes; break; // INY - increment Y by one (NZ) case 0xc8: result = Y + 1; ZF = ((result & 0xff) == 0x00); NF = ((result & 0x80) == 0x80); Y = (byte)result; PC += _currentOP.Bytes; break; // JMP - jump to new location (two byte immediate) case 0x4c: case 0x6c: // added for 65C02 case 0x7c: if (_currentOP.AddressMode == AddressModes.Absolute) { PC = GetImmWord(); } else if (_currentOP.AddressMode == AddressModes.Indirect) { PC = (ushort)(GetWordFromMemory(GetImmWord())); } else if( _currentOP.AddressMode == AddressModes.AbsoluteX) { PC = GetWordFromMemory((GetImmWord() + X)); } else { throw new InvalidOperationException("This address mode is invalid with the JMP instruction"); } // CMOS fixes a bug in this op code which results in an extra clock cycle if (_currentOP.OpCode == 0x6c && _cpuType == e6502Type.CMOS) _extraCycles++; break; // JSR - jump to new location and save return address case 0x20: // documentation says push PC+2 even though this is a 3 byte instruction // When pulled via RTS 1 is added to the result Push((ushort)(PC+2)); PC = GetImmWord(); break; // LDA - load accumulator with memory (NZ) case 0xa1: case 0xa5: case 0xa9: case 0xad: case 0xb1: case 0xb2: case 0xb5: case 0xb9: case 0xbd: A = (byte)oper; ZF = ((A & 0xff) == 0x00); NF = ((A & 0x80) == 0x80); PC += _currentOP.Bytes; break; // LDX - load index X with memory (NZ) case 0xa2: case 0xa6: case 0xae: case 0xb6: case 0xbe: X = (byte)oper; ZF = ((X & 0xff) == 0x00); NF = ((X & 0x80) == 0x80); PC += _currentOP.Bytes; break; // LDY - load index Y with memory (NZ) case 0xa0: case 0xa4: case 0xac: case 0xb4: case 0xbc: Y = (byte)oper; ZF = ((Y & 0xff) == 0x00); NF = ((Y & 0x80) == 0x80); PC += _currentOP.Bytes; break; // LSR - shift right one bit (NZC) // 0 -> (76543210) -> C case 0x46: case 0x4a: case 0x4e: case 0x56: case 0x5e: // On 65C02 (abs,X) takes one less clock cycle (but still add back 1 if page boundary crossed) if (_currentOP.OpCode == 0x5e && _cpuType == e6502Type.CMOS) _extraCycles--; // shift bit 0 into carry CF = ((oper & 0x01) == 0x01); // shift operand result = oper >> 1; ZF = ((result & 0xff) == 0x00); NF = ((result & 0x80) == 0x80); SaveOperand(_currentOP.AddressMode, result); PC += _currentOP.Bytes; break; // NOP - no operation case 0xea: PC += _currentOP.Bytes; break; // ORA - OR memory with accumulator (NZ) case 0x01: case 0x05: case 0x09: case 0x0d: case 0x11: case 0x12: case 0x15: case 0x19: case 0x1d: result = A | (byte)oper; ZF = ((result & 0xff) == 0x00); NF = ((result & 0x80) == 0x80); A = (byte)result; PC += _currentOP.Bytes; break; // PHA - push accumulator on stack case 0x48: Push(A); PC += _currentOP.Bytes; break; // PHP - push processor status on stack case 0x08: int sr = 0x00; if (NF) sr = sr | 0x80; if (VF) sr = sr | 0x40; sr = sr | 0x20; // bit 5 is always 1 sr = sr | 0x10; // bit 4 is always 1 for PHP if (DF) sr = sr | 0x08; if (IF) sr = sr | 0x04; if (ZF) sr = sr | 0x02; if (CF) sr = sr | 0x01; Push((byte)sr); PC += _currentOP.Bytes; break; // PHX - push X on stack case 0xda: Push(X); PC += _currentOP.Bytes; break; // PHY - push Y on stack case 0x5a: Push(Y); PC += _currentOP.Bytes; break; // PLA - pull accumulator from stack (NZ) case 0x68: A = PopByte(); NF = (A & 0x80) == 0x80; ZF = (A & 0xff) == 0x00; PC += _currentOP.Bytes; break; // PLP - pull status from stack case 0x28: sr = PopByte(); NF = (sr & 0x80) == 0x80; VF = (sr & 0x40) == 0x40; DF = (sr & 0x08) == 0x08; IF = (sr & 0x04) == 0x04; ZF = (sr & 0x02) == 0x02; CF = (sr & 0x01) == 0x01; PC += _currentOP.Bytes; break; // PLX - pull X from stack (NZ) case 0xfa: X = PopByte(); NF = (X & 0x80) == 0x80; ZF = (X & 0xff) == 0x00; PC += _currentOP.Bytes; break; // PLY - pull Y from stack (NZ) case 0x7a: Y = PopByte(); NF = (Y & 0x80) == 0x80; ZF = (Y & 0xff) == 0x00; PC += _currentOP.Bytes; break; // RMBx - clear bit in memory (no flags) // Clear the zero page location of the specified bit // These instructions are only available on Rockwell and WDC 65C02 chips. case 0x07: case 0x17: case 0x27: case 0x37: case 0x47: case 0x57: case 0x67: case 0x77: // upper nibble specifies the bit to check check_bit = (byte)(_currentOP.OpCode >> 4); check_value = 0x01; for (int ii = 0; ii < check_bit; ii++) { check_value = (byte)(check_value << 1); } check_value = (byte)~check_value; SaveOperand(_currentOP.AddressMode, oper & check_value); PC += _currentOP.Bytes; break; // SMBx - set bit in memory (no flags) // Set the zero page location of the specified bit // These instructions are only available on Rockwell and WDC 65C02 chips. case 0x87: case 0x97: case 0xa7: case 0xb7: case 0xc7: case 0xd7: case 0xe7: case 0xf7: // upper nibble specifies the bit to check (but ignore bit 7) check_bit = (byte)((_currentOP.OpCode & 0x70) >> 4); check_value = 0x01; for (int ii = 0; ii < check_bit; ii++) { check_value = (byte)(check_value << 1); } SaveOperand(_currentOP.AddressMode, oper | check_value); PC += _currentOP.Bytes; break; // ROL - rotate left one bit (NZC) // C <- 76543210 <- C case 0x26: case 0x2a: case 0x2e: case 0x36: case 0x3e: // On 65C02 (abs,X) takes one less clock cycle (but still add back 1 if page boundary crossed) if (_currentOP.OpCode == 0x3e && _cpuType == e6502Type.CMOS) _extraCycles--; // perserve existing cf value bool old_cf = CF; // shift bit 7 into carry flag CF = (oper >= 0x80); // shift operand result = oper << 1; // old carry flag goes to bit zero if (old_cf) result = result | 0x01; ZF = ((result & 0xff) == 0x00); NF = ((result & 0x80) == 0x80); SaveOperand(_currentOP.AddressMode, result); PC += _currentOP.Bytes; break; // ROR - rotate right one bit (NZC) // C -> 76543210 -> C case 0x66: case 0x6a: case 0x6e: case 0x76: case 0x7e: // On 65C02 (abs,X) takes one less clock cycle (but still add back 1 if page boundary crossed) if (_currentOP.OpCode == 0x7e && _cpuType == e6502Type.CMOS) _extraCycles--; // perserve existing cf value old_cf = CF; // shift bit 0 into carry flag CF = (oper & 0x01) == 0x01; // shift operand result = oper >> 1; // old carry flag goes to bit 7 if (old_cf) result = result | 0x80; ZF = ((result & 0xff) == 0x00); NF = ((result & 0x80) == 0x80); SaveOperand(_currentOP.AddressMode, result); PC += _currentOP.Bytes; break; // RTI - return from interrupt case 0x40: // pull SR sr = PopByte(); NF = (sr & 0x80) == 0x80; VF = (sr & 0x40) == 0x40; DF = (sr & 0x08) == 0x08; IF = (sr & 0x04) == 0x04; ZF = (sr & 0x02) == 0x02; CF = (sr & 0x01) == 0x01; // pull PC PC = PopWord(); break; // RTS - return from subroutine case 0x60: PC = (ushort)(PopWord() + 1); break; // SBC - subtract memory from accumulator with borrow (NZCV) // A-M-C -> A (NZCV) case 0xe1: case 0xe5: case 0xe9: case 0xed: case 0xf1: case 0xf2: case 0xf5: case 0xf9: case 0xfd: if (DF) { result = HexToBCD(A) - HexToBCD((byte)oper); if (!CF) result--; CF = (result >= 0); // BCD numbers wrap around when subtraction is negative if (result < 0) result += 100; ZF = (result == 0); A = BCDToHex(result); // Unlike ZF and CF, the NF flag represents the MSB after conversion // to BCD. NF = (A > 0x7f); // extra clock cycle on CMOS in decimal mode if (_cpuType == e6502Type.CMOS) _extraCycles++; } else { ADC((byte)~oper); } PC += _currentOP.Bytes; break; // SEC - set carry flag case 0x38: CF = true; PC += _currentOP.Bytes; break; // SED - set decimal mode case 0xf8: DF = true; PC += _currentOP.Bytes; break; // SEI - set interrupt disable bit case 0x78: IF = true; PC += _currentOP.Bytes; break; // STA - store accumulator in memory case 0x81: case 0x85: case 0x8d: case 0x91: case 0x92: case 0x95: case 0x99: case 0x9d: SaveOperand(_currentOP.AddressMode, A); PC += _currentOP.Bytes; break; // STX - store X in memory case 0x86: case 0x8e: case 0x96: SaveOperand(_currentOP.AddressMode, X); PC += _currentOP.Bytes; break; // STY - store Y in memory case 0x84: case 0x8c: case 0x94: SaveOperand(_currentOP.AddressMode, Y); PC += _currentOP.Bytes; break; // STZ - Store zero case 0x64: case 0x74: case 0x9c: case 0x9e: SaveOperand(_currentOP.AddressMode, 0); PC += _currentOP.Bytes; break; // TAX - transfer accumulator to X (NZ) case 0xaa: X = A; ZF = ((X & 0xff) == 0x00); NF = ((X & 0x80) == 0x80); PC += _currentOP.Bytes; break; // TAY - transfer accumulator to Y (NZ) case 0xa8: Y = A; ZF = ((Y & 0xff) == 0x00); NF = ((Y & 0x80) == 0x80); PC += _currentOP.Bytes; break; // TRB - test and reset bits (Z) // Perform bitwise AND between accumulator and contents of memory case 0x14: case 0x1c: SaveOperand(_currentOP.AddressMode, ~A & oper); ZF = (A & oper) == 0x00; PC += _currentOP.Bytes; break; // TSB - test and set bits (Z) // Perform bitwise AND between accumulator and contents of memory case 0x04: case 0x0c: SaveOperand(_currentOP.AddressMode, A | oper); ZF = (A & oper) == 0x00; PC += _currentOP.Bytes; break; // TSX - transfer SP to X (NZ) case 0xba: X = SP; ZF = ((X & 0xff) == 0x00); NF = ((X & 0x80) == 0x80); PC += _currentOP.Bytes; break; // TXA - transfer X to A (NZ) case 0x8a: A = X; ZF = ((A & 0xff) == 0x00); NF = ((A & 0x80) == 0x80); PC += _currentOP.Bytes; break; // TXS - transfer X to SP (no flags -- some online docs are incorrect) case 0x9a: SP = X; PC += _currentOP.Bytes; break; // TYA - transfer Y to A (NZ) case 0x98: A = Y; ZF = ((A & 0xff) == 0x00); NF = ((A & 0x80) == 0x80); PC += _currentOP.Bytes; break; // The original 6502 has undocumented and erratic behavior if // undocumented op codes are invoked. The 65C02 on the other hand // are guaranteed to be NOPs although they vary in number of bytes // and cycle counts. These NOPs are listed in the OpcodeList.txt file // so the proper number of clock cycles are used. // // Instructions STP (0xdb) and WAI (0xcb) will reach this case. // For now these are treated as a NOP. default: PC += _currentOP.Bytes; break; } } private int GetOperand(AddressModes mode) { int oper = 0; switch (mode) { // Accumulator mode uses the value in the accumulator case AddressModes.Accumulator: oper = A; break; // Retrieves the byte at the specified memory location case AddressModes.Absolute: oper = memory[ GetImmWord() ]; break; // Indexed absolute retrieves the byte at the specified memory location case AddressModes.AbsoluteX: ushort imm = GetImmWord(); ushort result = (ushort)(imm + X); if (_currentOP.CheckPageBoundary) { if ((imm & 0xff00) != (result & 0xff00)) _extraCycles += 1; } oper = memory[ result ]; break; case AddressModes.AbsoluteY: imm = GetImmWord(); result = (ushort)(imm + Y); if (_currentOP.CheckPageBoundary) { if ((imm & 0xff00) != (result & 0xff00)) _extraCycles += 1; } oper = memory[result]; break; // Immediate mode uses the next byte in the instruction directly. case AddressModes.Immediate: oper = GetImmByte(); break; // Implied or Implicit are single byte instructions that do not use // the next bytes for the operand. case AddressModes.Implied: break; // Indirect mode uses the absolute address to get another address. // The immediate word is a memory location from which to retrieve // the 16 bit operand. case AddressModes.Indirect: oper = GetWordFromMemory(GetImmWord()); break; // The indexed indirect modes uses the immediate byte rather than the // immediate word to get the memory location from which to retrieve // the 16 bit operand. This is a combination of ZeroPage indexed and Indirect. case AddressModes.XIndirect: /* * 1) fetch immediate byte * 2) add X to the byte * 3) obtain word from this zero page address * 4) return the byte located at the address specified by the word */ oper = memory[GetWordFromMemory( (byte)(GetImmByte() + X))]; break; // The Indirect Indexed works a bit differently than above. // The Y register is added *after* the deferencing instead of before. case AddressModes.IndirectY: /* 1) Fetch the address (word) at the immediate zero page location 2) Add Y to obtain the final target address 3)Load the byte at this address */ ushort addr = GetWordFromMemory(GetImmByte()); oper = memory[addr + Y]; if (_currentOP.CheckPageBoundary) { if ((oper & 0xff00) != (addr & 0xff00)) _extraCycles++; } break; // Relative is used for branching, the immediate value is a // signed 8 bit value and used to offset the current PC. case AddressModes.Relative: oper = SignExtend(GetImmByte()); break; // Zero Page mode is a fast way of accessing the first 256 bytes of memory. // Best programming practice is to place your variables in 0x00-0xff. // Retrieve the byte at the indicated memory location. case AddressModes.ZeroPage: oper = memory[GetImmByte()]; break; case AddressModes.ZeroPageX: oper = memory[(GetImmByte() + X) & 0xff]; break; case AddressModes.ZeroPageY: oper = memory[(GetImmByte() + Y) & 0xff]; break; // this mode is from the 65C02 extended set // works like ZeroPageY when Y=0 case AddressModes.ZeroPage0: oper = memory[GetWordFromMemory((GetImmByte()) & 0xff)]; break; // for this mode do the same thing as ZeroPage case AddressModes.BranchExt: oper = memory[GetImmByte()]; break; default: break; } return oper; } private void SaveOperand(AddressModes mode, int data) { switch (mode) { // Accumulator mode uses the value in the accumulator case AddressModes.Accumulator: A = (byte)data; break; // Absolute mode retrieves the byte at the indicated memory location case AddressModes.Absolute: memory[GetImmWord()] = (byte)data; break; case AddressModes.AbsoluteX: memory[GetImmWord() + X] = (byte)data; break; case AddressModes.AbsoluteY: memory[GetImmWord() + Y] = (byte)data; break; // Immediate mode uses the next byte in the instruction directly. case AddressModes.Immediate: throw new InvalidOperationException("Address mode " + mode.ToString() + " is not valid for this operation"); // Implied or Implicit are single byte instructions that do not use // the next bytes for the operand. case AddressModes.Implied: throw new InvalidOperationException("Address mode " + mode.ToString() + " is not valid for this operation"); // Indirect mode uses the absolute address to get another address. // The immediate word is a memory location from which to retrieve // the 16 bit operand. case AddressModes.Indirect: throw new InvalidOperationException("Address mode " + mode.ToString() + " is not valid for this operation"); // The indexed indirect modes uses the immediate byte rather than the // immediate word to get the memory location from which to retrieve // the 16 bit operand. This is a combination of ZeroPage indexed and Indirect. case AddressModes.XIndirect: memory[GetWordFromMemory((byte)(GetImmByte() + X))] = (byte)data; break; // The Indirect Indexed works a bit differently than above. // The Y register is added *after* the deferencing instead of before. case AddressModes.IndirectY: memory[GetWordFromMemory(GetImmByte()) + Y] = (byte)data; break; // Relative is used for branching, the immediate value is a // signed 8 bit value and used to offset the current PC. case AddressModes.Relative: throw new InvalidOperationException("Address mode " + mode.ToString() + " is not valid for this operation"); // Zero Page mode is a fast way of accessing the first 256 bytes of memory. // Best programming practice is to place your variables in 0x00-0xff. // Retrieve the byte at the indicated memory location. case AddressModes.ZeroPage: memory[GetImmByte()] = (byte)data; break; case AddressModes.ZeroPageX: memory[(GetImmByte() + X) & 0xff] = (byte)data; break; case AddressModes.ZeroPageY: memory[(GetImmByte() + Y) & 0xff] = (byte)data; break; case AddressModes.ZeroPage0: memory[GetWordFromMemory((GetImmByte()) & 0xff)] = (byte)data; break; // for this mode do the same thing as ZeroPage case AddressModes.BranchExt: memory[GetImmByte()] = (byte)data; break; default: break; } } private ushort GetWordFromMemory(int address) { return (ushort)((memory[address + 1] << 8 | memory[address]) & 0xffff); } private ushort GetImmWord() { return (ushort)((memory[PC + 2] << 8 | memory[PC + 1]) & 0xffff); } private byte GetImmByte() { return memory[PC + 1]; } private int SignExtend(int num) { if (num < 0x80) return num; else return (0xff << 8 | num) & 0xffff; } private void Push(byte data) { memory[(0x0100 | SP)] = data; SP--; } private void Push(ushort data) { // HI byte is in a higher address, LO byte is in the lower address memory[(0x0100 | SP)] = (byte)(data >> 8); memory[(0x0100 | (SP-1))] = (byte)(data & 0xff); SP -= 2; } private byte PopByte() { SP++; return memory[(0x0100 | SP)]; } private ushort PopWord() { // HI byte is in a higher address, LO byte is in the lower address SP += 2; ushort idx = (ushort)(0x0100 | SP); return (ushort)((memory[idx] << 8 | memory[idx-1]) & 0xffff); } private void ADC(byte oper) { ushort answer = (ushort)(A + oper); if (CF) answer++; CF = (answer > 0xff); ZF = ((answer & 0xff) == 0x00); NF = (answer & 0x80) == 0x80; //ushort temp = (ushort)(~(A ^ oper) & (A ^ answer) & 0x80); VF = (~(A ^ oper) & (A ^ answer) & 0x80) != 0x00; A = (byte)answer; } private int HexToBCD(byte oper) { // validate input is valid packed BCD if (oper > 0x99) throw new InvalidOperationException("Invalid BCD number: " + oper.ToString("X2")); if ((oper & 0x0f) > 0x09) throw new InvalidOperationException("Invalid BCD number: " + oper.ToString("X2")); return ((oper >> 4) * 10) + (oper & 0x0f); } private byte BCDToHex(int result) { if (result > 0xff) throw new InvalidOperationException("Invalid BCD to hex number: " + result.ToString()); if (result <= 9) return (byte)result; else return (byte)(((result / 10) << 4) + (result % 10)); } private void DoIRQ(ushort vector) { DoIRQ(vector, false); } private void DoIRQ(ushort vector, bool isBRK) { // Push the MSB of the PC Push((byte)(PC >> 8)); // Push the LSB of the PC Push((byte)(PC & 0xff)); // Push the status register int sr = 0x00; if (NF) sr = sr | 0x80; if (VF) sr = sr | 0x40; sr = sr | 0x20; // bit 5 is unused and always 1 if(isBRK) sr = sr | 0x10; // software interrupt (BRK) pushes B flag as 1 // hardware interrupt pushes B flag as 0 if (DF) sr = sr | 0x08; if (IF) sr = sr | 0x04; if (ZF) sr = sr | 0x02; if (CF) sr = sr | 0x01; Push((byte)sr); // set interrupt disable flag IF = true; // On 65C02, IRQ, NMI, and RESET also clear the D flag (but not on BRK) after pushing the status register. if (_cpuType == e6502Type.CMOS && !isBRK) DF = false; // load program counter with the interrupt vector PC = GetWordFromMemory(vector); } private void CheckBranch(bool flag, int oper) { if (flag) { // extra cycle on branch taken _extraCycles++; // extra cycle if branch destination is a different page than // the next instruction if ((PC & 0xff00) != ((PC + oper) & 0xff00)) _extraCycles++; PC += (ushort)oper; } } } } ``` ]
[Question] [ Given an input sentence consisting of one or more words `[a-z]+` and zero or more spaces , output an ASCII-art histogram (bar graph) of the letter distribution of the input sentence. The histogram must be laid out horizontally, i.e. with the letter key along the bottom in alphabetical order from left to right, with a Y-axis labeled `1-` and every 5 units. The Y-axis must be the smallest multiple of five that is at least as tall as the tallest bar, and must be right-aligned. The X-axis is labeled with the input letters, with no gaps between. For example, input `a bb dd` should have label `abd` and not `ab d`, skipping the `c`. The bars themselves can be made of any consistent ASCII character -- I'll be using `X` here in my examples. ``` test example 5- X X X 1-XXXXXXXX aelmpstx ``` Since there are three `e`, two `t`, and one of `almsx`. **More examples:** ``` the quick brown fox jumped over the lazy dogs 5- X X X X XX X X X XX 1-XXXXXXXXXXXXXXXXXXXXXXXXXX abcdefghijklmnopqrstuvwxyz now is the time for all good men to come to the aid of their country 10- X X X X X X X 5- X X X X X X X X XX XXXX X XXXXX XXXXXXX X 1-XXXXXXXXXXXXXXXXXX acdefghilmnorstuwy a bb ccc dddddddddddd 15- X X 10- X X X X X 5- X X XX XXX 1-XXXX abcd a bb ccccc 5- X X X XX 1-XXX abc ``` ## I/O and Rules * Input can be taken in any reasonable format and [by any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). This also means you can take input in all-uppercase, if that makes more sense for your code. * Leading/trailing newlines or other whitespace are optional, provided that the characters line up appropriately. * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * Output can be to the console, returned as a list of strings, returned as a single string, etc. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. [Answer] # [Stax](https://github.com/tomtheisen/stax), 37 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ü╣úwóΓµ┐Wh0íJ▌Ñìs┤►ï╖öz<à↔/Ü@τ|:╢Ω$‼φ ``` [Run and debug it](https://staxlang.xyz/#p=81b9a377a2e2e6bf576830a14adda58d73b4108bb7947a3c851d2f9a40e77c3ab6ea2413ed&i=test+example%0Athe+quick+brown+fox+jumped+over+the+lazy+dogs%0Anow+is+the+time+for+all+good+men+to+come+to+the+aid+of+their+country%0Aa+bb+ccc+dddddddddddd%0A&a=1&m=2) [Answer] # [R](https://www.r-project.org/), ~~239~~ 230 bytes ``` K=table(el(strsplit(gsub(" ","",scan(,"")),"")));m=matrix(" ",L<-sum(K|1)+1,M<-(M=max(K))+-M%%5+1);m[2:L,M]=names(K);m[1,M-g]=paste0(g<-c(1,seq(5,M,5)),"-");m[1,]=format(m[1,],j="r");for(X in 2:L)m[X,M-1:K[X-1]]=0;write(m,1,L,,"") ``` [Try it online!](https://tio.run/##JY7dioMwEIVfZQgUJphAs@BN2zyBei@IF7FNbRZjukmkLey7u6N7M3/fmTMT18kN0cQPepsf4Zb4WulshsminTDlmJ6TyzimZUAGTDAm0tXMSAXne@Bnr73J0b13QX2RafFY/SpeKNFcJDaE31hxXsjmcCgLRRvd16kWTa9n420iRhMSy7HXT5OyPeJ4kVdUItkfLEUjyu2YZP@6Xt9DpJO4N@Jbs0iEZtiCm4Gsue9aslOnqmul6nt9PL@iyxa9UKIW298rm8MLXIL8sJCdt0AGYKYJxhBu4O0MOcA1EKC8iYy7QbhvpYsEljnHD1v/AA "R – Try It Online") `table` does the heavy lifting here, uniquifying the characters, sorting them, and returning their counts. Everything else is just ensuring the offsets are right for printing, which is the "real" work of an ascii-art challenge. Thanks to [@dylnan](https://codegolf.stackexchange.com/users/75553/dylnan) for pointing out a bug. Thanks to [@rturnbull](https://codegolf.stackexchange.com/users/59052/rturnbull) for the `scan` approach, dropping 2 bytes. [Answer] # [Dyalog APL](https://www.dyalog.com/), ~~109~~ ~~97~~ ~~96~~ ~~95~~ ~~93~~ 88 bytes ``` {⊖(⍉r),⍨⍕↑(⊂'')@{1@0~⍵∊1,5×⍵}⍳≢⍉↑r←↑r,⍨⊂' -',' - '⍴⍨5×⌈5÷⍨≢1↓⍉↑r←↓{⍺,∊⍕¨0×⍵}⌸⍵[⍋⍵]∩⎕A} ``` [Try it online!](https://tio.run/##jY4xT8JQFIV3f8XdHiQlaQd22teC1bZPSyuicSAxuJBo2EyDg0PTVp7REHBnwlmNxlH@yf0j9bZoUo2Db3jn5p37nfMGF6PG6eVgdH6W4@3cFhjfqfmQ7gizRQ1lOq4rKFco5xjf1zC7ZqzeirSWeoXyBZNMU5rrBxonKJ8wXRJAe2PiCylJQqDBFAYADWAon@mxYKZJc/1aLKRLDeNZlZxFKN8VSqfaj5X6VTB9IzlGeUNygskj/Vef5PkQWLBtwX5o810wfNHzoC0OYSd09ywTxIHlQ@E7@lEfTNHpsi0iPNEDu1sage1aRPigOw50hDDBtTwIBHBBBmmxpNsU1S5G2ycj9AK/Xwb9qN50i0r77/rv/j@xf3A6GAZwzsGsnI1jcPYJ "APL (Dyalog Unicode) – Try It Online") Requires `⎕IO←0` *Way* too many bytes saved thanks to [Adám](https://codegolf.stackexchange.com/users/43319/ad%C3%A1m) and [Cows quack](https://codegolf.stackexchange.com/users/41805/cows-quack)! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~58~~ 47 bytes ``` áê©S¢Z5‰`Ā+L5*1¸ì'-«ð5×ý#À¦Áí.Bís'X×ζ‚ζJR»,®3ú, ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8MLDqw6tDD60KMr0UcOGhCMN2j6mWoaHdhxeo657aPXhDaaHpx/eq3y44dCyw42H1@o5HV5brB5xePq5bY8aZp3b5hV0aLfOoXXGh3fp/P@fkV@ukFuanKFQnp@fAiRKc1IUEsGc5IzS5GwFCJmZhioIVgZhg0TtAQ "05AB1E – Try It Online") -11 bytes thanks to @Emigna [Answer] # gnu [sed](https://www.gnu.org/software/sed/) -r, ~~516~~ ~~490~~ ~~278~~ 249 + 1 bytes ``` s/$/:ABCDEFGHIJKLMNOPQRSTUVWXYZ / :a s/(.)(:.*\1)/\2\1/I ta s/[A-Z]+/ /g h z :b s/ \w/ /g G s/:/&I/g /:II{5}+ *$/M!bb s/[a-z]/X/g G s/:(I{5}+|I)\b/0\1-/g s/:I*/ /g s/ (\w)\1*/\1/g s/$/; 10123456789I0/ :c s/(.)I(.*\1(I?.))|;.*/\3\2/ /\nI/s/^/ /Mg tc ``` [Try it online!](https://tio.run/##TY5ZU8IwFIXf8yuuM4zTwrSXgriUBwc3jIr7ghCcadNQq6XBNsgi/nVriqNjXnLud05yTyYCK0wmeZ5hCd3W3v7B4VH7mJ6cnnXOLy6vrm9u7@4fuo89QOJ6JEPDNg3XLjPHRFZjDlKiCtxvWb1BBQFD8kwWxPU1AzZdgbbWLq5TLdGl9KPxWYFyCTtrfpHqe9ZigN3fnLHyl9RkPlaZY2muKS0jwEqCwaYmc8qodxdzCZvgVJ1afaOxubW9Q6u6J//pSY2ip0F3bdNcNm39pM5qSJAlFDN80t06IVE8z5XIFIiZNxrHgqhnAW@TiL@Cn8ppAkM5g5fJaCwCkO8ihcKPvcUcAhlmJJFTiLIVVNFI6HQKXhxDKGUAI5GAksClNvRdhLxIfzMsZJRqY5KodE488H3gnEPw7/xRzr/kWEUyyXIr/QY "sed – Try It Online") --- I am sure this can be improved~~, but for now, this should be good considering it is made in sed, where you don't have native arithmetic or sorting.~~ So I lied, this wasn't good enough, so I improved (rewrote) it by another 212 bytes, with a tip regarding the sorting algorithm from [Cows quack](https://codegolf.stackexchange.com/users/41805/cows-quack), which gave me a idea to make the unary to decimal conversion shorter too. Description of inner workings: ``` s/$/:ABCDEFGHIJKLMNOPQRSTUVWXYZ / :a s/(.)(:.*\1)/\2\1/I ta s/[A-Z]+/ /g h z ``` This sorts the input and separates the groups with spaces. This works by first appending an uppercase alphabet plus space separated by a colon to the end. Then it moves each character in front of the colon to a matching character behind the colon using a case-insensitive substitution in a loop. The uppercase letters are then replaced by spaces and the string is copied to the holding space. ``` :b s/ \w/ /g G s/:/&I/g /:II{5}+ *$/M!bb ``` This loop works by reducing each character group size by one, appending the sorted original line and incrementing unary counters after the colon that remained from the sorting. It loops until an empty line with a number of 5\*n + 1 is reached (since the last line ultimately results in whitespace). The pattern space looks something like this after the loop: ``` :IIIIII :IIIII :IIII :III e :II ee t :I a eee l m p s tt x ``` Then the formatting follows: ``` s/[a-z]/X/g # makes bars consistent G # appends line that becomes x-axis s/:(I{5}+|I)\b/0\1-/g # moves zero in front of line 1 or 5-divisible # lines for the decimal conversion and adds - s/:I*/ /g # removes numbers from other lines s/ (\w)\1*/\1/g # collapses groups of at least 1 into 1 # character, deleting the space before it # so that only size-0-groups have spaces ``` And finally, the unary to decimal converter remains: ``` s/$/; 10123456789I0/ :c s/(.)I(.*\1(I?.))|;.*/\3\2/ /\nI/s/^/ /Mg tc ``` It basically appends a string where the knowledge of conversion is. You can interprete it as :space:->1 and 0->1->2->3->4->5->6->7->8->9->I0. The substitution expression `s/(.)I(.*\1(I?.))|;.*/\3\2/` works similar to the sorting one, replacing the characters in front of I's [ `(.)I` ] by the character that is next to the one from the front of the I in the conversion string [ `(.*\1(I?.))` ] and if there is no I left, it removes the appended string [ `|;.*` ]. The substitution [ `/\nI/s/^/ /Mg` ] adds padding if needed. Thanks to [Cows quack](https://codegolf.stackexchange.com/users/41805/cows-quack) for reducing the size by 26 bytes and for the shorter sorting algorithm. [Answer] # [Python 2](https://docs.python.org/2/), 192 bytes ``` s=input() d={c:s.count(c)for c in s if' '<c} h=-max(d.values())/5*-5 for y in range(h,-1,-1):print('%d-'%y*(y%5==2>>y)).rjust(len(`-h`))+''.join(('X '[y>v],k)[y<1]for k,v in sorted(d.items())) ``` [Try it online!](https://tio.run/##HY/RioMwEEXf/Yp5kWRadWnBl9L4HQulUEliTasZSaK7Ydlvd5OFgRm4hzv3LjGMZM/77oWxyxo4Fkr8yItvJK02cIkDOZBgLHgwAwN2lb/FKOq5/@aq2fpp1Z4jfrSHui0yGzPrevvUfKzqUxq8LM4kL1aqmpXxwGPZCnHuuojYuNfqA5@05Y96fCAeGWteZCzn7BPYLXbbvXrjLV5P9@z@rrb/LOSCVimACXrO/3HfmaUvMB7CqCGYWUPm@2mCJ5GCWVsIBJKSkHaGeqOAhnyaVDHXdZH9AQ "Python 2 – Try It Online") ## Explanation Line 2 computes the histogram values in a fairly straightforward way, discarding `' '`. Line 3 uses the trick of computing `ceil(x/5)` as `-(-x/5)`: we round the maximal frequency up to the next multiple of 5 using the formula `-x/5*-5`. This is `h`. Line 4 is a loop counting from `h` down to `0` inclusive, printing each row: * If `y%5==2>>y` we print a label. This is when `y` ∈ {1, 5, 10, 15, 20, …} (This formula could maybe be shorter. We just need something that's **1** or **True** for {1, 5, 10, …}, and **0** or **False** or even a negative integer for all other values of `y`.) * We right-justify the label (or empty space) into `len(`-h`)` spaces: this is a neat one-byte saving over `len(`h`)+1`! * Then, we print either `X`'s and spaces for this row (if `y` ≥ 1) or the letters (if `y` = 0), running through key-value pairs in `d` in ascending order. [Answer] # Pyth, 65 bytes ``` J.tm+ed*hd\Xr8S-Qd)=+J*]d%_tlJ5_.e+?q<k2%k5.F"{:{}d}-",klQ*dhlQbJ ``` [Try it here](http://pyth.herokuapp.com/?code=J.tm%2Bed%2ahd%5CXr8S-Qd%29%3D%2BJ%2a%5Dd%25_tlJ5_.e%2B%3Fq%3Ck2%25k5.F%22%7B%3A%7B%7Dd%7D-%22%2CklQ%2adhlQbJ&input=%22now+is+the+time+for+all+good+men+to+come+to+the+aid+of+their+country%22&debug=0) ### Explanation ``` J.tm+ed*hd\Xr8S-Qd)=+J*]d%_tlJ5_.e+?q<k2%k5.F"{:{}d}-",klQ*dhlQbJ J.tm+ed*hd\Xr8S-Qd) Get the bars. =+J*]d%_tlJ5 Round up the height to the next number that's 1 mod 5. _.e+?q<k2%k5.F"{:{}d}-",klQ*dhlQbJ Stick the axis labels on. ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 62 bytes ``` ≔E²⁷⟦⟧ηFθ⊞§η⌕βιι≔⊟ηθ≦LηP⭆β⎇§ηκιω↑↑ΦηιF÷⁺⁹⌈η⁵«≔∨×⁵ι¹ιJ±¹±ι←⮌⁺ι- ``` [Try it online!](https://tio.run/##TY9BSwMxEIXP3V8x9DSB9KBQRD0VRKi0umg9iYfYne4Gs8k2yW5bxN@@TmoEL5nhzcx7X7aN8lunzDguQtC1xbXq8PJKwtu7kNCI22LnPOBeQNmHBhdxaSs6YiPhXtsKPyRoIdJzW2SD0nXYsLRnic2yuiJbx@bXcd2bqDuvbcSXyKVOmey0IW@VP/0P@UzeEg5CpDs3EN68dtyW52vuE4eJ5NOyFn@4Sxvv9KArwtL0Aa8lrNVRt33LZOw4FwK@iklGe/K40S0FnCcLCRf5P5OHvu02Dh@pVpEwybk9B00yw4p2UcIzDeRDzmPi6Wx6Zv4eR@sOoAPEhiByDiRCZQzUzlXQkoXoYOt4wDUtKV2B26VWex70NvpTMc4G8wM "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔E²⁷⟦⟧η ``` Create a list of 27 lists. ``` Fθ⊞§η⌕βιι ``` Push each input character to the list corresponding to its position in the lowercase alphabet. Non-lowercase characters get pushed to the 27th list. ``` ≔⊟ηθ ``` Discard the 27th element of the list. ``` ≦Lη ``` Take the lengths of all the elements of the list. ``` P⭆β⎇§ηκιω ``` Print the lowercase letters corresponding to non-zero list elements. ``` ↑↑Φηι ``` Print the non-zero list elements upwards. Since this is an array of integers, each integer prints as a (now vertical) line, each in a separate column. ``` F÷⁺⁹⌈η⁵« ``` Calculate the number of tick marks on the Y-axis and loop over them. ``` ≔∨×⁵ι¹ι ``` Calculate the position of the next tick mark. ``` J±¹±ι ``` Jump to the next tickmark. ``` ←⮌⁺ι- ``` Print the tickmark reversed and back-to-front, effectively right-aligning it. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 48 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) What a mine-field to traverse! ``` J’⁶D;”-Ɗ%5^ỊƲ?€Uz⁶ZU ḟ⁶ṢµĠ¬;⁶$L%5Ɗ¿€;"@Qz⁶Ç;"$ṚY ``` A full-program printing the result (as a monadic link it would return a list containing characters and integers from `[0,9]`) **[Try it online!](https://tio.run/##y0rNyan8/9/rUcPMR43bXKwfNczVPdalahr3cHfXsU32j5rWhFYBJaJCuR7umA9kPNy56NDWIwsOrbEGclR8VE2PdR3aD1RlreQQCFJ4uN1aSeXhzlmR////z8svV8gsVijJSFUoycxNVUjLL1JIzMlRSM/PT1HITc1TKMlXSM4HSgBpkKLEzBSF/DQQM7MIKFGaV1JUCQA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##TYyxTsMwEIZ3nuJktRuMnTLAwIRYGDoUBJLjuMXBiYvj0KZTy1IpbwASAjF3QiKiAlHJLXmP@EXMhYmTTvfffZ8u5lIW3p@4@YNbVMeBmz8d1GW3d9V8lvXbobtf9WcIzvt7zcczhmb9at93L3YV4NI57fbq0m7QCsjRWStulwHpNOvHgf/52i4RDLBjt/i2la28vyCGZwb4lCZjyck@MdccbnPBbiDUapLCUE0hzpMxj0DdcQ0tl3RWQKRGGfqpmoDI/s5GJBx9DVRKGCkVQcJTMAqYQoCzlajAR8M2Co0gT40u8A2FMATGGET/ilz@Ag "Jelly – Try It Online") ### How? ``` J’⁶D;”-Ɗ%5^ỊƲ?€Uz⁶ZU - Link 1, get y-axis: list of columns (including x-axis & top-spaces) J - range of length [1,2,3,4,5,6,...,height+1] (+1 for x-axis) ’ - decrement [0,1,2,3,4,5,...] (line it up with the content) ?€ - if for €ach... Ʋ - ...condition: last four links as a monad: %5 - modulo by five Ị - insignificant? (1 for 0 and 1, else 0) ^ - XOR (0 for 1 or multiples of 5 greater than 0, else 0) ⁶ - ...then: literal space character Ɗ - ...else: last three links as a monad: D - decimal list of the number, e.g. 10 -> [1,0] ”- - literal '-' character ; - concatenate, e.g. [1,0,'-'] U - upend (reverse each) z⁶ - transpose with a filler of space characters Z - transpose U - upend (i.e. Uz⁶ZU pads the left with spaces as needed) ḟ⁶ṢµĠ¬;⁶$L%5Ɗ¿€;"@Qz⁶Ç;"$ṚY - Main link: list of characters ḟ⁶ - filter out space characters Ṣ - sort µ - start a new monadic chain, call that S Ġ - group indices of S by their values ¬ - logical NOT (vectorises) (getting 0 for the X "characters") ¿€ - while for €ach... Ɗ - ...condition: last three links as a monad: L - length %5 - modulo by five $ - ...do: last two links as a monad: ;⁶ - concatenate a space character Q - deduplicate S (get the x-axis) ;"@ - zip with (") concatenation (;) with swapped arguments (@) z⁶ - transpose a with filler of space characters $ - last two links as a monad: Ç - call last link (1) as a monad (get y-axis) ;" - zip with concatenation (complete the layout) Ṛ - reverse (otherwise it'll be upside-down) Y - join with newlines - implicit print ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 56 bytes ``` ⊖h,⍨{∊⍺'-'/⍨~×5|⍵-⍵<2}⌸⍕⍪⍳≢h←(⊢↑⍨≢+5|1-≢)⍉(⊢,⌸⊣\)∊⍞∘∩¨⎕a ``` [Try it online!](https://tio.run/##TU1NT8JAEL33V8wNiWz8SLh52bYLrrZd3LYCxkuDQUiaYMLJiB6xNC7RA@rJA17QqzExHvWfzB@pU05OMpl58968l1yk7OwySUfnrJcm4/GwV@B8MRzh9H7bwuy2X2D@OKihWV1hlqP5rrDKFqGb36f6BM0no97bvca7LzQLNO9oPnC2HND7BuZLnD6Qlg6b9ckOo1lFMyuJWvmQv55W16YvmD1j9vazouikoNSib0UijEB0uN/yhEVwX8BRLJ1DsLVqB9BQHTiI/ZZwQR0LDSXv8ZMuuKoZkj5QbZDh@hxJX5BeA/c8aCrlgi8CiBQ4igiapYhLMmqUq9RExEGku2TDwbbBcRxw/9Uf "APL (Dyalog Classic) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~250~~ ~~248~~ ~~234~~ ~~188~~ ~~173~~ ~~157~~ 153 bytes ``` ->s{a=s.scan(/\w/).sort|[] m=-(c=a.map{|l|s.count l}).max/5*-5 m.downto(1).map{|i|(i%5<1||i<2?"#{i}-":'').rjust(m)+c.map{|l|l<i ?' ':?X}*''}<<' '*m+a*''} ``` [Try it online!](https://tio.run/##TY9RT4MwFIXf@RUnM6bABsuMS8wC8jdM5h5KKdJJW2yLbK78dgSNiffl3u/ec05yTV9epzqfkmd7o7lNLaMq3L4O2yi12jh/PAUyT0KW01TS7uZbb1Ome@XQjtG8umz3cbIPZFrpQTkd7qJfnfChuN9nO@9F9lCs7m5iTFYHQqLUnHvrQhmt2V9imwkUBORQvIwxIWOWzRDLNV1goshxJI5bB36hsms52YCc63e8aQd5xWdj0TFQVeHSGgy8xEcvvhaV0gOEhWs4nJActTagbTs7dQXJFZwG0/Nh7ouIigq6XkZh8POmuS45FGUJxhiqf0VOAU05ZQ0qDW@d8QHQ9c6iPs502qBI4sengKtq@gY "Ruby – Try It Online") Thanks to: * [dylnan](https://codegolf.stackexchange.com/a/161934/70753) for -16 bytes with less strict padding * [Lynn](https://codegolf.stackexchange.com/a/161943/70753) for -2 bytes by rounding up with `-x/5*-5` * [Kirill L.](https://codegolf.stackexchange.com/questions/161921/alphabet-histogram#comment392424_161978) for -2 bytes by getting unique array elements with `|[]` [Answer] # [Java (JDK)](http://jdk.java.net/), 295 bytes ``` s->{int d[]=new int[26],m=0;char a;for(int c:s.getBytes())m=c>32&&++d[c-=65]>m?(d[c]+4)/5*5:m;String r=m+"-",z=r.replaceAll("."," ");for(;m>0;r+="\n"+(--m%5>0&m!=1|m<1?z:z.format("%"+~-z.length()+"s-",m)))for(a=0;a<26;a++)r+=d[a]>0?m>d[a]?" ":"x":"";for(a=64;a++<90;)r+=d[a-65]>0?a:"";return r;} ``` [Try it online!](https://tio.run/##jZJNj5swEIbv@yumlnZlSnDZdBOpEIjaSiv1UPWw6inl4BiHkPUHtU02yTb969ROcmgvUZHMDH6fGcPLbOiWJpv6eej6pWgZMEGtha@0VfB6A3DZtY46H7a6rUF6DT8506pmUQE1jY1OKMDG9yK9awVZ9Yq5VivyeElm54LROZSwggIGm5SvrXJQL6pC8Rfw@WI8rUaySHO2pgZovtIGB4RlljTcfdo7bnEUyYKV78d3d3FcL1hSTCdVKefY51X8EL2bvJ1kMj8fBaaQMUrQ6FAYYngnKOMfhcCIoBECFJ1OyGWZ5iYu0A@FYpwk8nZSpnfyTXH/S87u54fsQDwmqcPoFsW/kwMRXDVujaMYWd9bRlEU@lD/4nQ2nuY0jiPfr17QqkznsgzJ3B@XoZ1fKD/D04cAzj6k@QVOwoekcxoQw11vFJj8OOQnd0PNNphimuwf2yE8eT/9nTj9veu4@Uwtx1F@kZ/21nFJdO9I5z1xQmH0RXW9ywBBHOquot96F1h0DVoR2nVij0Ova9x/aMebsI7D4H@1A76jshN8cGsOP/uWPcPS6Bfl3djBppcdr0FvuYGgC3rYQ60bOyjtp8meNl0refAOqBDQaO0HmCtwGpj2go8Bon6u9SqkrfFCr5zZDxSWS2CMQf3X9Qc "Java (JDK) – Try It Online") ## Credits * -3 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) * -1 byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 262 256 bytes \*Thanks to @Shaggy for reducing by 2 bytes ``` a=>[...a].map(x=>x>" "&&(d=c[x]=(c[x]||x)+"X")[m]?m=d.length-1:0,c={},m=i=0)&&Object.keys(c).sort().map(x=>[...c[x].padEnd(m)].map((l,j)=>A[m-j-1]+=l),A=[...Array(m+=6-m%5)].map(x=>(++i>=m||((D=m-i)%5&&m-i^1)?"":D+"-").padStart((m+" ").length)))&&A.join` ` ``` [Try it online!](https://tio.run/##hU@7TgMxEOz5ipWlnLy6nEUKKJB8KBLUFDRIURCO7QQffhw@By4Qvj3YvAQVLvahmZ0Zd@JJDDKaPjU@KH1Y84Pg7YIxJpbMiZ6OvB1bAqSqqOJyMS45LXW/H7EmNwQXbnnuuGJW@026b2Znx1PJX9@mjht@jFV1teq0TOxB7wYqkQ0hJorfysWnqLFeqEuvqMNPU2qnHfJ2vnBN18yWNbc4nfPCnscodtTV/LRxkxP8yUjr2rTc7feUXnDXGJycVFXutzM8J@TsoiYNwWJznUROkBXyn/ArNWIOOmddMP7u6O4ggx@C1cyGDV1TkvSQQI/C9VYTxKPf8N@tkO81PG6NfIBVDM8e1mGEbut6rSA86QgFt@JlBypshn/VfHgGM3wcJeN0VosgrIVNCAqc9pACyJCB3AtJmGyzLqOJGdj6FHf/mghYrUBKCerXy1eHdw "JavaScript (Node.js) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~249~~ ~~224~~ ~~219~~ ~~215~~ ~~205~~ ~~197~~ ~~187~~ ~~188~~ ~~182~~ 176 bytes ``` def f(s):S=sorted(set(s)^{' '});C=map(s.count,S);P=max(C)+4;return zip(*(zip(*[('%d-'%y*(y%5==2>>y)).rjust(P)for y in range(P,0,-1)])+[(n*'#').rjust(P)for n in C]))+[[' ']*P+S] ``` [Try it online!](https://tio.run/##dVHLbsMgELznK1aqIljnoTZqL4mcS37AUo6uKxGDE1IbXMBNSNVvd8Htoa/sAQZmdmYRrXcHrRb9DRnzGRn7hPrxQ5ou1muPPRcVVNTicptabZzg1AoXzk9vBMg7rjZpw1pq56XulJtucZWFizPd4OR@ZYTrjIKLbGlChzWn/2Tg3Bw762iGlTbgQSowTO0Fzaa309kdFjjJqUrIDfmpVFG5KTDQeRimSLLJtujbkOo8pFCzZscZ2CWQR0XmRy0VzckXqKUSCNElomgUHxmSonY0ao1UDj6tKGGw20EZi@BV6i/nDgJeOlk@w87oU0jQZzh2TSs46FdhIPI1u3jgem8Jwq92pU8g7aByshHDsKyuYa81h0YocBpKHYiwRxGTwbeKUBoYvsP4q/MC/1YE@w8 "Python 2 – Try It Online") Returns a list of lists of characters representing lines. * Saved some bytes by including a lot of extra whitespace. * Had an unnecessary `map(list,yticks)` in there. * Changed space padding to save some bytes. * I thought I was sorting but I was not: +2 bytes. But I saved one independently at the same time. `y==1` replaced by `y<2`. * -6 bytes thanks to [Lynn](https://codegolf.stackexchange.com/a/161943/75553) by using `'%d-'%y*(y%5==2>>y)` instead of `(`y`+'-')*(not y%5or y<2)`. Slightly ungolfed: ``` def f(s): S=sorted(set(s)^{' '}) # sorted list of unique letters (without ' ') C=map(s.count,S) # count of each unique letter in the input P=max(C)+4 # used for padding and getting highest y tick B=[(n*'#').rjust(P)for n in C] # create bars yticks = [('%d-'%y*(y%5==2>>y)).rjust(P)for y in range(P,0,-1)] # create y ticks at 1 and multiples of 5 yticks = zip(*yticks) # need y ticks as columns before combining with bars return zip(*(yticks+B))+[[' ']*P+S] # zip ticks+bars then add row of sorted unique letters. ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~344~~ ~~340~~ 338 + 18 bytes Includes 18 bytes for `using System.Linq;` Saved 6 bytes thanks to @KevinCruijssen. ``` n=>{var l=n.Where(c=>c!=32).GroupBy(c=>c).OrderBy(c=>c.Key).ToDictionary(k=>k.Key,c=>c.Count());int h=(l.Values.Max()/5+1)*5,o=(h+"").Length+1,m=l.Keys.Count+o,t=h+1,i=0,j;var a=new string[t];for(string p,q;i<t;a[i++]=q)for(q=(p=i>0&i%5<1|i==1?i+"-":"").PadLeft(j=o);j<m;){var c=l.ElementAt(j++-o).Key;q+=i<1?c:l[c]>=i?'X':' ';}return a;} ``` [Try it online!](https://tio.run/##dVJdc9MwEHyuf8XhGYiFXdPA9KWO0imlMAPt0AGGMlPyoMqXRKmtSyQ5rQn57UHKF@UBv9i63Vvvnk7aQ0kGV41VegRfW@uwzi@VnhVRJCthLVwbGhlRwyI6sE44JWFOqoQroXRinfFttwMQZmSZp0RbhfeNlr0NmsGO1Ych8JXm/cVcGKi4zm/GaDCRvC@f8TevWf7BUDN9264rLP9sSjTbU/4JW5Z/o3dKOkVamDa55/37UM7W@Dk12iWMFUo7GPOkyr@LqkGbX4nHhL06Trvs5XFGPBmncczyS9QjN067Wc2rIGI3Ailljoey4kfZpAg@Bdf4sMvgBsWQzDY3TLNZoXquELcqTQd8xgI248mUq/7RC/X8uNf9rTjvnqo0PoxPwn@vRXmJQ5dMOLFi0qsLth6G9C4uKqxRuzMPpukhsWCrmKVc9bqn8qS6lYM@V6edH52TDnSKpUHXGA2iWK78Xe1vwqF1Uli0wOGJ8QEsIHZjhFmj5D3cGXrQMKRHmDT1FEugORoIeCV@tVDSyMYZxJoeQNl13akafYOfR1XBiKgEbxYcgSQP@HcgCb8YNAyfymcKAzVt0BFwdwdSSiifPDEsi8gropBj2I10Zx@U/huFRYsI/LNdrnPSlirMb4xy6HcVk31XCvFPHbNiTd9HN2ibyvmBDPdMln9BH9liErbqzBjRJv@0ATVu2oSmzTn/SH7hg3q21dvS/2tqI@BZyyg6WEbL1R8 "C# (.NET Core) – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/) + coreutils, 332 324 323 318 312 302 298 296 293 291 bytes ``` c()(cut -d\ -f$@) p=printf cd `mktemp -d` grep -o [^\ ]<<<$@|sort|uniq -c|c 7->a sort -k2<a>b r=$[`c 1 <a|sort -n|tail -1`+5] s=${#r} t()($p \ ;((i++<s))&&t;i=) for((;--r;));{ ((r%5&&r>1))&&t||$p %${s}s- $r;IFS=' ' for l in `<b`;{ ((r<=`c 1 <<<$l`))&&$p X||$p \ ;} echo } t c 2 <b|tr -d \\n ``` [Try it online!](https://tio.run/##JY@xbsIwEIb3e4qTaoIt6gEkxGAHMVXq3KUSoXLiEGIFktR2qFDMs6cGttP99@m@v8hdPU2aMqoHj7zMEHlFdgz6tLem9RXoEtWl8cdLH2MFJ3uMQ4f7nwwPUkqyC66zPgyt@UWug8YN3@bw2CFvVjLfFmBTslcalyjz8Ara4HNzRr5Ui/UBXErGN3sHHzVIjxkKSs1iIR1jSeKFSRlUnaVUcG4FY2IESu1snSR2u3yehBCxGRnd3XEkVnx@fKVzmD8oPKNpUclCiREjJtOXSTQ/qwccye8nH9/e4ajrDqIJaFyhLIK3sTVmWTtNU@7KKtb/c@Wpbi@NGW4nb291ca30tR6a938 "Bash – Try It Online") Annotated: ``` c()(cut -d\ -f$@) p=printf # saving a few bytes cd `mktemp -d` # for temp files grep -o [^\ ]<<<$@ # grabs all non-space characters |sort|uniq -c # get character frequency |c 7->a # slightly hacky way of stripping leading spaces; # uniq -c adds 6 spaces in front of each line sort -k2<a>b # store frequencies sorted alphabetically in b r=$[` # r = highest frequency +5: c 1 <a # get frequencies |sort -n|tail -1 # get maximum frequency `+5] # +4 so at least one multiple of 5 is # labeled, +1 because r gets pre-decremented s=${#r} # s = length of r as a string t()($p \ ;((i++<s))&&t;i=) # pad line with s+1 spaces for((;--r;));{ # while (--r != 0) ((r%5&&r>1))&& # if r isn't 1 or a multiple of 5 t|| # then indent line $p %${s}s- $r; # otherwise print right-aligned "${r}-" IFS=' ' # newline field separator for l in `<b`;{ # for all letters and their frequencies: ((r<=`c 1 <<<$l`))&& # if frequency <= current height $p X|| # then print an X $p \ ;} # otherwise print a space echo } t # indent x-axis labels c 2 <b|tr -d \\n # print alphabetically sorted characters ``` Thanks to @IanM\_Matrix for saving 3 bytes. [Answer] # C, 201 bytes ``` char c[256],*p,d;main(int a,char **b){for(p=b[1];*p;p++)++c[*p|32]>d&*p>64?d++:0;for(a=(d+4)/5*5;a+1;a--){printf(!a||a%5&&a!=1?" ":"%3i-",a);for(d=96;++d>0;c[d]?putchar(a?32|c[d]>=a:d):0);puts(p);}} ``` Input is taken from the command line (first argument). Uses exclamation marks instead of X's to further reduce code size. Counter on the left is always three characters long. Tested with GCC and clang. [Answer] # Excel VBA, 316 bytes An Anonymous VBE immediate window function that takes input from cell `[A1]` and outputs to the VBE immediate window. ``` For i=1To 26:Cells(2,i)=Len(Replace([Upper(A1)],Chr(i+64),11))-[Len(A1)]:Next:m=-5*Int(-[Max(2:2)]/5):l=Len(m)+1:For i=-m To-1:?Right(Space(l) &IIf(i=-1Xor i Mod 5,"",-i &"-"),l);:For j=1To 26:?IIf(Cells(2,j),IIf(Cells(2, j) >= -i, "X", " "),"");:Next:?:Next:?Spc(l);:For i=1To 26:?IIf(Cells(2,i),Chr(i+96),"");:Next ``` ### Ungolfed Version ``` Public Sub bar_graph() For i = 1 To 26 '' gather the count of the letter into cells Cells(2, i) = Len(Replace([Upper(A1)], Chr(i + 64), 11)) - [Len(A1)] Next m = -5 * Int(-[Max(2:2)] / 5) '' get max bar height l = Len(m) + 1 '' length of `m` + 1 For i = -m To -1 '' print either a label or free space (y-axis) Debug.Print Right(Space(l) & IIf((i = -1) Xor i Mod 5, "", -i & "-"), l); For j = 1 To 26 '' print 'X' or ' ' IFF the count of the letter is positive If Cells(2, j) Then Debug.Print IIf(Cells(2, j) >= -i, "X", " "); Next Debug.Print '' print a newline Next Debug.Print Spc(l); '' print spaces For i = 1 To 26 '' print the letters that were used (x-axis) Debug.Print IIf(Cells(2, i), Chr(i + 96), ""); Next End Sub ``` [Answer] # [Perl 5](https://www.perl.org/) `-n`, ~~198~~ 168 bytes ``` s/[a-z]/$\<++${$&}?$\=${$&}:0/eg;$\++while$\%5;$;=1+length$\++;printf"%$;s".'%s'x26 .$/,$\%5&&$\-1?"":"$\-",map$$_>=$\?X:$$_&&$",a..z while--$\;say$"x$;,map$$_&&$_,a..z ``` [Try it online!](https://tio.run/##LY3baoQwFEV/5RCOzoPGS8F5MLV@wbwXmjKETtRATMRkmEvprzeN0qe9YC3Yi1x1E4IrPwR9fpbIX7MMvzH96ZF3O7RVKUeGPMtuk9ISedIwZF2daWlGP22CLasyfiAJMkeKQ@IO95cjFFjmW52myGndE9KSCCSfxYJ4fuuQ9@9tpOhJLoriCfsBpciZEw8kd2T/cUzOexKCsTdQDvwkwatZwmBXEFrDaO0FZmnAW/iyUcTdIqEuYIcN1RrF1fj18WsXr6xxgZ6aoqqrQM0f "Perl 5 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 177 bytes ``` lambda s:[[list(("%d-"%i*(i%5==2>>i)).rjust(len(q)))+["* "[s.count(c)<i]for c in q]for i in range(max(map(s.count,q))+4,0,-1)]+[[" "]*len(q)+q]for q in[sorted(set(s)-{' '})]][0] ``` [Try it online!](https://tio.run/##TVBBbsIwELz3FStLCC8JiJb2gho@YnwwjgOLEjvEiwqq@vbUDhxYaTUjzexo7P7Op@A3Y1Ptx9Z0h9pA3CrVUmQpxaxeihktJM2@qupjtyPE1XC@Jq11Xl4QsVBiAULFlQ1Xz9LiN@kmDGCBPFwmSpkOxh@d7MwtbS@f9jIlFJ/luly@oy6UEiD04pFcPG4v6VbFMLCrZXQsIy5/5zD/Q63VWo/sIsdKiYzgbqbrWydKED78AEXgkwOmzkGOMm0LxxBq6JwHDmBDEhJmk6EaQpMppeq52nDPOQYOB7DWQv0yr4K1Qr/ldM6PnOpsoR8ofQUn296L1TmQl@KJEacuMbsbyYgPE47/ "Python 3 – Try It Online") This may not be the most byte-efficient approach in Python, but I really wanted to solve this with a "true one-liner" lambda. Outputs a list of character lists. Abuses multiple leading newlines and spaces just like everybody else. It may actually be further reduced to 174 bytes if it is acceptable to wrap the result in another list, so that we could transfer the final `[0]` indexing to the footer. [Answer] # JavaScript (ES8), 200 bytes Takes input as an array of characters. Returns a string. ``` s=>(s.sort().join``.replace(/(\w)\1*/g,s=>a.push(s[0]+'X'.repeat(l=s.length,h=h<l?l:h)),h=a=[]),g=y=>y--?(y<2^y%5?'':y+'-').padStart(`${h}_`.length)+a.map(r=>r[y]||' ').join``+` `+g(y):'')(h+=5-~-h%5) ``` [Try it online!](https://tio.run/##dY5BTsMwEEX3PcUIUdkmjQtI3VR1ewg2SGkgbuLEKU4cbKetoXD14CCQWNDZzJf@05vZ8wO3uak7F7e6EEPJBsvW2FKrjcOE7nXdZhk1olM8F3iOt0eyvbuZV7OAcdr1VmKb3KYRekQjJbjDilmqRFs5OZNMrtRGLSUhIXOWpGRWMc/WPo432K/un/x0sUFo6SMUI0I7Xjw4Hi5n1@/y4zn78ZCI04Z32LC1SXx6PiNAv79F2SSLKuzJEiGCZcQW8Wcspwsy5Lq1WgmqdIVLnFBKr5ywDsSJN50SVykhk/8YKeC1r/MX2Bl9bKHUJ9j3TScK0AdhYOwVf/NQ6MpekrT6CLX9Zl3diCAxwJWCSusCGtGC05DrUIQ9QrwO9nKMtQlF3zrjL7k57HaQ5zkUf2aEhy8 "JavaScript (Node.js) – Try It Online") ### Commented ``` s => ( // s[] = input array of characters (e.g. ['a','b','a','c','a']) s.sort() // sort it in lexicographical order (--> ['a','a','a','b','c']) .join`` // join it (--> 'aaabc') .replace(/(\w)\1*/g, // for each run s of consecutive identical letters (e.g. 'aaa'): s => a.push( // push in a[]: s[0] + // the letter, which will appear on the X-axis 'X'.repeat( // followed by 'X' repeated L times L = s.length, // where L is the length of the run (--> 'aXXX') h = h < L ? L : h // keep track of h = highest value of L )), // initialization: h = a = [] // h = a = empty array (h is coerced to 0) ), // end of replace() (--> a = ['aXXX','bX','cX'] and h = 3) g = y => // g = recursive function taking y y-- ? // decrement y; if there's still a row to process: ( // build the label for the Y-axis: y < 2 ^ y % 5 ? // if y != 1 and (y mod 5 != 0 or y = 0): '' // use an empty label : // else: y + '-' // use a mark ).padStart( // pad the label with leading spaces, `${h}_`.length // using the length of the highest possible value of y ) + // (padStart() is defined in ECMAScript 2017, aka ES8) a.map(r => r[y] // append the row, || ' ') // padded with spaces when needed .join`` + `\n` + // join it and append a linefeed g(y) // append the result of a recursive call : // else: '' // stop recursion )(h += 5 - ~-h % 5) // call g() with h adjusted to the next multiple of 5 + 1 ``` [Answer] # [PHP](https://php.net/), 180 bytes ``` $c=count_chars($argn,1);unset($c[32]);for($s=max($c)+4;$s;){printf($s%5&&$s>1?$z=' ':'%2d-',$s--);foreach($c as$d)echo$d>$s?X:' ';echo" ";}foreach($c as$a=>$d)$z.=chr($a);echo$z; ``` [Try it online!](https://tio.run/##VZDNTsMwDMfvfQpr8tZVrEgbcFloe@MZkBBCWZKugTYOScq2Il6dkvbEfPDX/2dbsm3s@FjZ6FEUgnoT3kTDnV8jd0ez2WasN16FNYqXu91rxmpya/RFx8@xld3cM/Qs@7ZOm1BHYfmwWqEvtxUORQoA6T5d7mSebtDn@TytuGjiKHCPMlOiIZQl@up5n0LKpnqRLNjPNciLMsI43Baiied5NoM4sHEMygdQZ97ZViWhUfDZa/EBB0cnAzWd4b3vrJJAX8rBpLd8uICko08MnUD7uRl0pyLtgLctHIkkdMpAIBAUhRgniOu4pp5S7WB@lbskHA4HEEKA/Ge/ZIMm48f86Q8 "PHP – Try It Online") ]
[Question] [ **Objective**: Write a program that generates beautiful (?) ASCII-art landscapes and skylines! Your program has just one input: a string composed of any combination/repetition of the chars `0123456789abc`. For each input character, output a vertical line composed as follows: ``` . .. ... oooo ooooo OOOOOO OOOOOOO XXXXXXXX XXXXXXXXX XXXXXXXXXX 0123456789 ``` Letters `abc` instead are followed by one number n, and draw the vertical line n with respectively 1,2 or 3 holes (spaces) at the bottom. **Examples** **The Chrysler Building** Input: `2479742` ``` . . ... ooo ooo OOOOO OOOOO XXXXXXX XXXXXXX XXXXXXX ``` **The Taj Mahal** Input: `0804023324554233204080` ``` . . . . o o o oo o O O OOOO O O O O OO OOOO OO O O X X XXXXXXXXXXXX X X X X XXXXXXXXXXXX X X XXXXXXXXXXXXXXXXXXXXXX ``` **The Eiffel Tower** Input: `011a2b3b5c9c9b5b3a2110` ``` .. .. .. oo oooo OOOO OOOOOO XXX XXX XXX XXX XXX XXX ``` You can assume input is not empty and that it's well-formed. Any language is accepted, from [A+](http://en.wikipedia.org/wiki/A+_%28programming_language%29) to [Z++](http://en.wikipedia.org/wiki/Z++). This is code-golf: **the shortest source code wins**. If anything in the rules is not clear, feel free to ask below in the comments. Have fun, and capture hundred meters high structures in a few bytes! (and don't forget to include your favourite building in your solution) P.S.: no, you can't download/access data from the Internet, use your file name as data and all that stuff. Be fair, and use only your code-golf skills. [Answer] ## GolfScript, 69 ``` 'XXXOOoo...':s\{.96>{96-.' '*\@>+}{47-<' '10*+10<s\}if}%10/zip-1%n*\; ``` Not far off the APL solution. [Test online](http://golfscript.apphb.com/?c=OyIwMTFhMmIzYjVjOWM5YjViM2EyMTEwIgonWFhYT09vby4uLic6c1x7Ljk2Pns5Ni0uJyAnKlxAPit9ezQ3LTwnICcxMCorMTA8c1x9aWZ9JTEwL3ppcC0xJW4qXDs%3D) [Answer] ## Ruby, ~~88~~ 85 Fun challenge! ``` 9.downto(0){|h|puts$*[0].gsub(/(\D?)(.)/){'XXXOOoo... '[h<$1.hex-9||$2.hex<h ?-1:h]}} ``` Takes input on the commandline, eg: ``` ruby landscapes.rb 011a2b3b5c9c9b5b3a2110 ``` Will print out: ``` .. .. .. oo oooo OOOO OOOOOO XXX XXX XXX XXX XXX XXX ``` [Answer] ## Python 2.7 - 186 Probably can be shorter... ``` x=[] l=iter(raw_input()) a="XXX00oo..." for i in l: try:i=int(i);o=0 except:o=" abc".index(i);i=int(next(l)) x.append(" "*o+a[o:i+1]+" "*(9-i)) for i in zip(*x)[::-1]:print''.join(i) ``` Sample run: ``` 08040233245542332040800000247974200000011a2b3b5c9c9b5b3a2110 . .. . . . .. . . ... .. o o ooo oo o oo o ooo oooo 0 0 0000 0 0 00000 0000 0 0 00 0000 00 0 0 00000 000000 X X XXXXXXXXXXXX X X XXXXXXX XXX XXX X X XXXXXXXXXXXX X X XXXXXXX XXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX ``` ## Sydney Harbour Bridge ``` a1a13443a1a2a3a4a5a6a6a7a7a8a8a8a8a9a9a9a9a9a9a8a8a8a8a7a7a6a6a5a4a4a3a2a13443a1a1 ...... .............. .................. oooooooooooooooooooooo oooooooooooooooooooooooo 00 000000000000000000000000000 00 0000 00000000000000000000000000000 0000 XXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XXXX ``` ## Golden gate bridge / Cisco logo ``` a2a0a0a4a0a06a0a0a4a0a0a2a0a0a4a0a06a0a0a4a0a0a2 o o o o 0 0 0 0 0 0 0 0 0 0 0 0 X X X X X X X X X X X X X X X X X X X X ``` Great question by the way! [Answer] # C64 BASIC, 276 PETSCII chars My own solution, golfed down to 276 chars and 10 lines of BASIC V2.0! ``` 0inputa$:dIc$(10):fOi=0to9:rE c$(i):nE:fOr=0to9 1z=1 2c=aS(mI(a$,z,z+1)) 3ifc>57tHgO8 4ifc>=57-r tH?c$(9-r);:gO6 5?" "; 6z=z+1:ifz<=len(a$)gO2 7?:nE:eN 8z=z+1:w=aS(mI(a$,z,z+1)):ifw>=57-r aNc<=73-r tH?c$(9-r);:gO6 9?" ";:gO6:dA"x","x","x","o","o","W","W",".",".","." ``` (copy and paste in an emulator to see the result). And finally, my favourite monument, the Brooklyn Bridge :) ![enter image description here](https://i.stack.imgur.com/NzHew.png) [Answer] ## C, ~~130~~ 126 chars Kinda long compared to the competition, but I blame the language... ``` char*p,b[99];r=10,q;main(o){for(gets(&b);r--;puts("")) for(p=b;q=*p++;)o=q<60?putchar("XXXOOoo... "[o<r&r<q-47?r:10]),-1:q-97;} ``` I don't know about *favourite* building, but one of the more recognizable ones around here is [Globen](http://en.wikipedia.org/wiki/Globen), so here is a poor rendition of it. ``` % ./a.out <<<24556667777776665542 ...... oooooooooooo oooooooooooooooo OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO XXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX ``` [Answer] # [APL](https://dyalog.com), 59 bytes [SBCS](https://github.com/abrudz/SBCS) ``` {⊖⍉↑(-N)↑¨(L/⍨1,2≤/L←A⍸⍵)↓¨(N←⎕D⍳⍵~A←'abc')↑¨⊂'XXXOOoo...'} ``` [Try it on online!](https://razetime.github.io/APLgolf/?h=AwA&c=q37UNe1Rb@ejtokaun6aQOrQCg0f/Ue9Kwx1jB51LtH3edQ2wfFR745HvVuBspOBsn5AkUd9U10e9W4GCtY5ArnqiUnJ6hDNj7qa1CMiIvz98/P19PTUawE&f=e9Q39VHbBIU0BXUDQ8NEoyTjJNNky2TLJNMk40QjQ0MDdQWFR71zFVwz09JScxRC8stTi7gegfWAtFgYmBgYGRsbmZiamoBoINcCpiUkMUvBNzEjMQehHqTOzMzMHAyADJAuoGqIevec/KTUPAA&i=AwA&r=tryAPL&l=apl-dyalog&m=dfn&n=f) Shorter than the other APL answers so far! I think it can probably be further golfed. Will add explanation soon! Thanks to [dzaima](https://codegolf.stackexchange.com/users/59183/dzaima) & [hyper-neutrino](https://codegolf.stackexchange.com/users/68942/hyper-neutrino) for their advice in the [The APL Orchard](https://chat.stackexchange.com/rooms/52405/the-apl-orchard)! [Answer] ## APL (~~69~~ 66) ``` ' XXXOOoo...'[1+⌽⍉⌽↑{z×(z<' abc'⍳⍵)<(1+⍎⍺)≥z←⍳10}/↑2↑¨I⊂⍨⎕D∊⍨I←⌽⍞] ``` Examples: ``` ' XXXOOoo...'[1+⌽⍉⌽↑{z×(z<' abc'⍳⍵)<(1+⍎⍺)≥z←⍳10}/↑2↑¨I⊂⍨⎕D∊⍨I←⌽⍞] 0804023324554233204080 . . . . o o o oo o O O OOOO O O O O OO OOOO OO O O X X XXXXXXXXXXXX X X X X XXXXXXXXXXXX X X XXXXXXXXXXXXXXXXXXXXXX ' XXXOOoo...'[1+⌽⍉⌽↑{z×(z<' abc'⍳⍵)<(1+⍎⍺)≥z←⍳10}/↑2↑¨I⊂⍨⎕D∊⍨I←⌽⍞] 011a2b3b5c9c9b5b3a2110 .. .. .. oo oooo OOOO OOOOOO XXX XXX XXX XXX XXX XXX ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 127 bytes ``` $r=,''*10 $args|% t*y|%{if($_-in97..99){$b=$_-96}else{,' '*$b+'XXXOOoo...'[$b.."$_"]+,' '*(9-"$_")|%{$r[--$i]+=$_} $b=$i=0}} $r ``` [Try it online!](https://tio.run/##jZBrb4IwFIa/91ecYF29QAOIUz6Q7B/wlcQsBrBOErQOMJtBfrtry2VG3OU0wNvn7YX3HPkHy/IdS9Mr3nrlFWeeTsjEMhEOs7f8MoRicr4My2Q7wmsjObgLSl13XOLIE3P3uWJpzkqdAJngaEqCIPB9zimlZIUjSjW81l6nyh65hpyNxWE4WxkGTl6n4owKyaMSz6yEyq4VQi8jRGxn4S4cm@iIAAAVT0@KO1rJOe9LX9a9DOr6QaKxrm43l6Zj2rOZ7cznjvyK6dJs/uBBKYf2Of3L4X2H3zmc3zm@GLJUJiXAv3EEVI40OyeQ46YU@N0JHtZ3iywrtKNZNI/d2I3m0Sy0LeumRZTetObfpA3bEc4b1JEudkt8v0UNkSnqVxNRycZoorU9rSPBBYZQIglwrgNmn0cWF2wDHuB1jTOWn9JCgCe8FYsU1BqqGexd6zZpyht0WwZwOsR8v2eHAopdkkOaHBgUHDZJfkzDM9TrclSh6xc "PowerShell – Try It Online") [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~35~~ 33 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ±{⌐╷≡?┤╵“`Fc|C!‟m]c96- ×11╋╋}})⤢⇵ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JUIxJXVGRjVCJXUyMzEwJXUyNTc3JXUyMjYxJXVGRjFGJXUyNTI0JXUyNTc1JXUyMDFDJTYwRmMlN0NDJXVGRjAxJXUyMDFGJXVGRjREJXVGRjNEJXVGRjQzOTYldUZGMEQlMjAlRDcldUZGMTEldUZGMTEldTI1NEIldTI1NEIldUZGNUQldUZGNUQldUZGMDkldTI5MjIldTIxRjU_,i=JTIyMDExYTJiM2I1YzljOWI1YjNhMjExMCUyMg__,v=8) [Answer] # [PHP](https://php.net/), ~~131~~ 114 bytes ``` for($b=10;$b--;print" ")foreach(str_split($argn)as$a)$c=strpos(' abc',$a)?:!print$a<$b|$b<$c?' ':'XXXOOoo...'[$b]; ``` [Try it online!](https://tio.run/##dU9BasMwEDxXr9gGgWyIE1mWYztOyKmlh0ByNISQaIVbG9JYWO6p7dtd2UnpqSxoZ2d2Fo2pTL/amMoQQrvSdhbWcCAAjIcikvEiSTM2HWYhkyyRgk0fRjXlkosoEjKO5dDdmPLbJg9DJTDCWGc6wxgjJcLwrimhuCs5vIs/@C99c@FwTrpTC3T/STFxIHZEhIKRY07IfA62fv@4qK6EswsDwfX5DK9NC2Mm4lCpdOXBPaOyQFX7dgUfPknvVI/iOuQ5xSDITVtfuwmZ@L8u27Unay51540mX1mqfKrXjjeN9Rgo1GzquM3ycTRTtaL4RXFF9YYBW7KiKHa7ppnNZuxA8Zj3UOqqgf3L/vS02@bku/8B "PHP – Try It Online") ``` $ echo 2479742|php -nF land.php . . ... ooo ooo OOOOO OOOOO XXXXXXX XXXXXXX XXXXXXX $ echo 011a2b3b5c9c9b5b3a2110|php -nF land.php .. .. .. oo oooo OOOO OOOOOO XXX XXX XXX XXX XXX XXX $ echo a2a0a0a4a0a06a0a0a4a0a0a2a0a0a4a0a06a0a0a4a0a0a2|php -nF land.php o o o o O O O O O O O O O O O O X X X X X X X X X X X X X X X X X X X X ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 33 bytes ``` ~kµṪV‘R×ØaiⱮ0xƲ)Ṗz0Ṛị“XXXOOoo... ``` [Try it online!](https://tio.run/##y0rNyan8/78u@9DWhztXhT1qmBF0ePrhGYmZjzauM6g4tknz4c5pVQYPd856uLv7UcOciIgIf//8fD09PYX/jxrmAiUPLeE63B6pmfWocd@hbYe2/f@vZGRibmluYqSko6BkYGFgYmBkbGxkYmpqAqKBXAsDsIyhYaJRknGSabJlsmWSaZJxopGhIVgGpNbMzMwcDIAMkE6QuKWFuZmpibGRoYGhkbGJqZm5haUSAA "Jelly – Try It Online") Full program returning a list of lines. If that isn't acceptable, [+2 bytes](https://tio.run/##HUu9CoJAAH4VuU0Iuf@fpxAawkZPGjLBtRrCpob2kqgXaAgKEiRoUOg97l7k8vyW7z9fFMXGud2qe5v2PrNVPe3PfZ0u7fMB179XaNrTFpr2Yj5HW12TJInjsoyiKLDVbe76Q5jb/bdrusY5gKlQgmIwCQCUkEJMCKaMUc@DlXBsEEqxJpplKlOaaZJihMbGbznnYsQg/NPnSgrOKMEIIkwo40Iq8Ac). Note the trailing space. Included my favourite: ``` . . .. .. ... ... oooo oooo ooooo ooooo OOOOOO OOOOOO OOOOOOO OOOOOOO XXXXXXXX XXXXXXXX XXXXXXXXX XXXXXXXXX XXXXXXXXXXXXXXXXXXX ``` ## How it works ``` ~kµṪV‘R×ØaiⱮ0xƲ)Ṗz0Ṛị“XXXOOoo... - Main link. Takes a string on the left ~ - Bitwise NOT. This maps digits d to ~d and non-digits to 0 k - Partition the string after falsey values This groups the string as we want, with a trailing [] µ ) - Over each element, either [L, x] or [x]: Ṫ - Extract x, modifying the element V - Evaluate as a digit ‘ - Increment R - Create a range Ʋ - Last 4 links as a monad f([L]) or f([]): ØaiⱮ - Index in the alphabet 0x - Get that many zeros If the element was [x], this yields [] If the element was [L, x], this returns 1, 2 or 3 zeros, depending on L × - Multiple elementwise, zeroing the first 1,2 or 3 elements in the range if L is in the element Ṗ - Remove the trailing [] element z0 - Transpose, padding with zeros Ṛ - Reverse ị“XXXOOoo... - Index into "XXXOOoo... " ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 93 bytes ``` {for 9...0 ->\n {say .subst(/(\D)?(.)/,{'XXXOOoo... '.comb[$1>=n>=ord($0//0)-96??n!!10]}):g}} ``` A block that takes in the string and prints to stdout. [Try it online!](https://tio.run/##dY5BC4JAEIXP9SumkFLIdXZdzc3US3evQkXsWnZJN7QOIf52UzpEh3gw73vDMLz7pb75ffmCRRH1baFrEIQQBDs@VNA28gWkearmYTrmYWclJrGcVbvMsixNtR4uYUlyXaq9QeOoiiNdn00DHQctW/hJUs1mFI@dtbl2XR9Ox/dbxtdizRlggByZ6zLueXz0IQYISKlkylVeLnKhPOVKRimCZBIH8XH6X/y7jqGdTsb6xin8wHw@QPGbu/4N "Perl 6 – Try It Online") [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 34 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Rvy.ïi"XXXOOoo..."y>£ëðAykÝǝ])ζRí» ``` Uses the legacy version of 05AB1E to save 2 bytes, since `ζ` also works on strings instead of just lists of characters. [Try it online.](https://tio.run/##MzBNTDJM/f8/qKxS7/D6TKWIiAh///x8PT09pUq7Q4sPrz68wbEy@/Dc43NjNc9tCzq89tDu//@NTMwtzU2MEg1A0MDCwMTAyNjYyMTU1AREA7kWBlA5Q8NEoyTjJNNky2TLJNMk40QjQ0MDAA) **Explanation:** ``` R # Reverse the (implicit) input-string v # Loop `y` over each character: y.ïi # If `y` is a digit: "XXXOOoo..." # Push string "XXXOOoo..." y>£ # And only leave the first `y`+1 characters as substring ë # Else (`y` is a letter): Ayk # Get the index of `y` in the lowercase alphabet Ý # Create a list in the range [0, alphabet-index] ð ǝ # Replace in the string at the top of the stack the characters at # those indices with a space ] # Close the if-else statement and loop ) # Wrap all strings on the stack into a list ζ # Zip/transpose; swapping rows/columns Rí # Reverse this list, as well as each individual line » # And join the strings by newlines # (after which the result is output implicitly) ``` As for my favorite 'building', let's go with this tree. ;) ``` b2b3b4b5b6b7898b7b6b5b4b3b2 . ... ..... ooooooo ooooooooo OOOOOOOOOOO OOOOOOOOOOOOO XXXXXXXXXXXXXXX XXX XXX ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 36 bytes ``` óȦnãÒXÌ î"XXXOOoo..."hSpXÎnD)s9Ãz3 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=88imbsOj0ljMIO4iWFhYT09vby4uLiJoU3BYzm5EKXM5w3oz&input=IjI0Nzk3NDJhMGEwYTAwODA0MDIzMzI0NTU0MjMzMjA0MDgwYTBhMGEwMDExYTJiM2I1YzljOWI1YjNhMjExMCI) ``` óȦnãÒXÌ î"..."hSpXÎnD)s9Ãz3 :Implicit input of string ó :Partition at È :Characters that return true when passed through the following function ¦ : Test for inequality with n : Convert to number à :End function £ :Map each X Ò : Bitwise increment XÌ : Last character of X î : Slice the following to that length "..." : Literal string h : Replace as many characters as necessary at the start of that string with S : Space p : Repeat XÎ : First character of X n : Convert from base D : 14 ) : End repeat s9 : Slice off the first 9 characters à :End map z3 :Rotate clockwise by 90 degrees 3 times :Implicit output, joined by newlines ``` [Answer] # [Pip](https://github.com/dloscutoff/pip) `-l`, 45 bytes ``` Z:R{sXtRAb:Ab%4\,c"XXXOOoo..."@b}MRaC KXL.CXD ``` Takes input as a command-line argument. [Try it here!](https://replit.com/@dloscutoff/pip) Or, here's a 46-byte equivalent in Pip Classic: [Try it online!](https://tio.run/##K8gs@P8/yioorLo4oiTIMcnKMUnVJEYnWSkiIsLfPz9fT09PySGp1jco0VnBO8JHzznC5f///7o5/w0MDRONkoyTTJMtky2TTJOME40MDQ0A "Pip – Try It Online") ### Explanation High-level: ``` R{sXtRAb:Ab%4\,c"XXXOOoo..."@b} Apply this function MR to each match C KXL.CXD of this regex a in the input string Z: Transpose the result Autoprint as lines (-l flag) ``` The regex: ``` XL Lowercase letter [a-z] K Apply Kleene star [a-z]* C Wrap in a capturing group ([a-z]*) XD Digit \d C Wrap in a capturing group (\d) . Concatenate ([a-z]*)(\d) ``` The replacement function takes three arguments: `a` is the full match, `b` is the first capturing group (a letter or empty string), `c` is the second capturing group (a digit). ``` R{sXtRAb:Ab%4\,c"XXXOOoo..."@b} s Space character Xt repeated 10 times Ab ASCII code of the letter (nil if empty string) %4 Mod 4 ("a"->1, "b"->2, "c"->3, ""->nil) \,c Inclusive range from that number to the digit (treats a left argument of nil as 0) b: Assign that value to b RA and replace those indices in the space string "XXXOOoo..."@b with the equivalent indices in this string R Reverse to put the "top" of the building at the left ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 67 bytes ``` {⊖⍉↑(((' '⍴⍨2⊃⊢),'XXXOOoo...'↑⍨1+⊃)∘⌽0,48|⎕UCS)¨'[abc]?\d'⎕S'\0'⊢⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/P@1R24TqR13THvV2PmqbqKGhoa6g/qh3y6PeFUaPupofdS3S1FGPiIjw98/P19PTUweqAUoZagPlNB91zHjUs9dAx8Si5lHf1FDnYM1DK9SjE5OSY@1jUtSBQsHqMQbqQCMe9W6tBdqkoG5kYm5pbmKkzgVkG1gYmBgYGRsbmZiamoBoINfCACJlaJholGScZJpsmWyZZJpknGhkaGigDgA "APL (Dyalog Extended) – Try It Online") Longer than the other answer, but I'll try golfing it later. Proper explanation coming soon. * `'[abc]?\d'⎕S'\0'⊢⍵` - Extract single digits or characters followed by digits * `(((' '⍴⍨2⊃⊢),'XXXOOoo...'↑⍨1+⊃)∘⌽0,48|⎕UCS)¨` - Train to turn each digit or pair into a horizontal string * `⊖⍉↑` - Turn it into a matrix, transpose to make it vertical, and flip it upside-down. ]
[Question] [ ## Introduction A quixel is a quantum pixel. Similar to a classical pixel, it is represented with 3 integer values (Red, Green, Blue). However, quixels are in a super position of these 3 states instead of a combination. This super position only lasts until the quixel is observed at which point it collapses to one of three classical pixels; `RGB(255,0,0)`, `RGB(0,255,0)` and `RGB(0,0,255)`. ## Specification * **Representation** + Each quixel is represented as an array of 3 integers between 0 and 255, `r`, `g` and `b` respectively. * **Super Positions** + Each quixel is in a super position between the Red, Blue and Green states represented by `R`, `G` and `B` respectively. * **Observation** + When each quixel is observed it collapses into one of the three states. The probability of each classical state is `R = (r + 1) / (r + g + b +3)`**,** `G = (g + 1) / (r + g + b + 3)` and `B = (b + 1) / (r + g + b + 3)`. This way each classical state always as a non-zero probability of showing up. * **Input** + The function or program should take a image of quixels. How it does this is flexible. A filename, using a multi-dimensional array, etc are all acceptable. * **Output** + The function or program should produce an image of classical pixels. The data structure for this produced image is also flexible. Note that all of the pixels should be one of these three: `RGB(255,0,0)`, `RGB(0,255,0)` and `RGB(0,0,255)` + The output should not be [deterministic](https://en.wikipedia.org/wiki/Deterministic_system); these are *quantum* pixels! The same input should result in different outputs. + If your language has no way of generating a random number, you can take random bytes as input * **Scoring** + This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so fewest bytes win. --- ## Images **Mona Lisa** by **Leonardo da Vinci** [![Mona Lisa](https://i.stack.imgur.com/DvxTX.jpg)](https://i.stack.imgur.com/DvxTX.jpg) **Starry Night** by **Vincent van Gogh** [![enter image description here](https://i.stack.imgur.com/IanmW.jpg)](https://i.stack.imgur.com/IanmW.jpg) **Persistence of Memory** by **Salvador Dali** [![enter image description here](https://i.stack.imgur.com/NOoRY.jpg)](https://i.stack.imgur.com/NOoRY.jpg) **Teddy Roosevelt VS. Bigfoot** by **[SharpWriter](http://sharpwriter.deviantart.com)** [![enter image description here](https://i.stack.imgur.com/H3eHq.jpg)](https://i.stack.imgur.com/H3eHq.jpg) [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), ~~23~~ ~~21~~ 19 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) Takes table of (R, G, B) triplets. ### [Inspired by miles' algorithm](https://codegolf.stackexchange.com/a/91753/43319) Returns table of indices into {(255, 0, 0), (0, 255, 0), (0, 0, 255)}. Horribly wasteful. ``` (?∘≢⊃⊢)¨(⊂⍳3)/¨⍨1+⊢ ``` `(`  `?∘≢` random index  `⊃` selects  `⊢` from `)¨` each of `(`  `⊂` the entire  `⍳3` first three indices `)/¨⍨` replicated by each of `1+⊢` the incremented triplets [TryAPL!](http://tryapl.org/?a=f%u2190%28%3F%u2218%u2262%u2283%u22A2%29%A8%28%u2282%u23733%29/%A8%u23681+%u22A2%20%u22C4%20%u22A2pic%u2190%3F%283+%3F3%203%29%u2374%u22823/256%20%u22C4%20%2C%A8f%20pic&run) --- ### Old version Returns table of 0-based indices into {(255, 0, 0), (0, 255, 0), (0, 0, 255)} ``` {+/(?0)≥+\(1+⍵)÷3++/⍵}¨ ``` `{`...`}`¨ for each quixel in the table, find the:  `+/` the sum of (i.e. count of truths of)  `(?0)≥` a random 0 < number < 1 being greater than or equal to  `+\` the cumulative sum of  `(1+⍵)÷` the incremented RGB values divided by  `3+` three plus  `+/⍵` the sum of the quixel Note: Dyalog APL [lets you chose](http://help.dyalog.com/15.0/Content/Language/System%20Functions/rl.htm) between the [Lehmer linear congruential generator](https://en.wikipedia.org/wiki/Lehmer_random_number_generator), the [Mersenne Twister](https://en.wikipedia.org/wiki/Mersenne_Twister), and the Operating System's RNG[¹](https://en.wikipedia.org/wiki//dev/random) [²](https://en.wikipedia.org/wiki/CryptGenRandom). For example, the image: ``` ┌──────────┬──────────┬───────────┬───────────┬─────────┐ │52 241 198│148 111 45│197 165 180│9 137 120 │46 62 75 │ ├──────────┼──────────┼───────────┼───────────┼─────────┤ │81 218 104│0 0 255 │0 255 0 │181 202 116│122 89 76│ ├──────────┼──────────┼───────────┼───────────┼─────────┤ │181 61 34 │84 7 27 │233 220 249│39 184 160 │255 0 0 │ └──────────┴──────────┴───────────┴───────────┴─────────┘ ``` can give ``` ┌─┬─┬─┬─┬─┐ │1│0│2│2│1│ ├─┼─┼─┼─┼─┤ │2│2│1│1│2│ ├─┼─┼─┼─┼─┤ │0│2│1│2│0│ └─┴─┴─┴─┴─┘ ``` Notice how the three "pure" quixels collapsed to their respective colors. [TryAPL online!](http://tryapl.org/?a=%u2395IO%u21901%20%u22C4%20f%u2190%7B+/%28%3F0%29%u2265+%5C%281+%u2375%29%F73++/%u2375%7D%A8%20%u22C4%20%u22A2pic%u2190%3F%283+%3F3%203%29%u2374%u22823/256%20%u22C4%20%2C%A8f%20pic&run) [![Collapsed Mona Lisa](https://i.stack.imgur.com/CGA9P.png)](https://i.stack.imgur.com/CGA9P.png) [Answer] # Mathematica, 53 bytes ``` RandomChoice[255#+1->IdentityMatrix@3]&~ImageApply~#& ``` Anonymous function. Takes a Mathematica `Image` as input and returns an `Image` as output. Note that the input image must have an RGB color space. [Answer] ## C#, ~~366~~ 243 bytes Huge thanks to @TheLethalCoder for golfing this! ``` var r=new Random();c=>{double t=c.R+c.G+c.B+3,x=(c.R+1)/t,d=r.NextDouble();return d<=x?Color.Red:d<=x+(c.G+1)/t?Color.Lime:Color.Blue;};b=>{fo‌​r(int x=0,y;x<b.Width;x++)for(y=0;y<b.Height;y++)b.SetPixel(x,y,g(‌​b.GetPixel(x,y)));re‌​turn b;}; ``` Basic idea: ``` using System; using System.Drawing; static Random r = new Random(); static Image f(Bitmap a) { for (int x = 0; x < a.Width; x++) { for (int y = 0; y < a.Height; y++) { a.SetPixel(x, y, g(a.GetPixel(x, y))); } } return a; } static Color g(Color c) { int a = c.R; int g = c.G; double t = a + g + c.B + 3; var x = (a + 1) / t; var y = x + (g + 1) / t; var d = r.NextDouble(); return d <= x ? Color.Red : d <= y ? Color.Lime : Color.Blue; } ``` --- Examples: Mona Lisa [![enter image description here](https://i.stack.imgur.com/7i3fT.png)](https://i.stack.imgur.com/7i3fT.png) Starry Night [![enter image description here](https://i.stack.imgur.com/DRPsg.png)](https://i.stack.imgur.com/DRPsg.png) Persistence of Memory [![enter image description here](https://i.stack.imgur.com/cv2tE.png)](https://i.stack.imgur.com/cv2tE.png) Teddy Roosevelt VS. Bigfoot [![enter image description here](https://i.stack.imgur.com/MuS3q.png)](https://i.stack.imgur.com/MuS3q.png) [Here's](https://i.stack.imgur.com/N2kvh.jpg) an updated imgur album with a few more examples, to show that this is nondeterministic. [Answer] # Python 2, ~~172~~ ~~166~~ 162 bytes The second and third indent levels are a raw tab and a raw tab plus a space, respectively; this plays *really* badly with Markdown, so the tabs have been replaced by two spaces. ``` from random import* i=input() E=enumerate for a,y in E(i): for b,x in E(y): t=sum(x)+3.;n=random() for j,u in E(x): n-=-~u/t if n<0:i[a][b]=j;break print i ``` Uses a similar input/output format to [Adám's APL answer](https://codegolf.stackexchange.com/a/91722/56755). Input is a 2D array of RGB tuples; output is a 2D array of `0`, `1`, or `2`, representing red, green, and blue respectively. For example: ``` $ echo "[[(181,61,34),(39,184,160),(255,0,0)],[(84,7,27),(123,97,5),(12,24,88)]]" | python quixel.py [[2, 2, 0], [0, 0, 0]] ``` Below is my older Python 3 answer using PIL. ## Python 3 + PIL, ~~271~~ ~~250~~ ~~245~~ 243 bytes ``` import random as a,PIL.Image as q i=q.open(input()) w,h=i.size for k in range(w*h): m=k//h,k%h;c=i.getpixel(m);t=sum(c)+3;n=a.random() for j,u in enumerate(c): n-=-~u/t if n<0:z=[0]*3;z[j]=255;i.putpixel(m,tuple(z));break i.save('o.png') ``` Iterates over every pixel and applies the quixel function to it. Takes the filename as input and saves its output in `o.png`. Here are some results: ``` $ echo mona-lisa.jpg | python quixel.py ``` [![Mona Lisa, quixelized](https://i.stack.imgur.com/1kbsm.png)](https://i.stack.imgur.com/1kbsm.png) ``` $ echo starry-night.jpg | python quixel.py ``` [![Starry Night, quixelized](https://i.stack.imgur.com/sNjY9.png)](https://i.stack.imgur.com/sNjY9.png) ``` $ echo persistence-of-memory.jpg | python quixel.py ``` [![Persistence of Memory, quixelized](https://i.stack.imgur.com/pB2yg.png)](https://i.stack.imgur.com/pB2yg.png) ``` $ echo roosevelt-vs-bigfoot.jpg | python quixel.py ``` [![Teddy Roosevelt vs Bigfoot, quixelized](https://i.stack.imgur.com/qUMtq.png)](https://i.stack.imgur.com/qUMtq.png) [Answer] # R, 58 bytes ``` mapply(function(r,g,b)rmultinom(1,1,c(r+1,g+1,b+1)),r,g,b) ``` Input consists of three numeric vectors held in `r`, `g` and `b` respectively. We don't need to normalise the probabilities to sum to one, that happens automatically in `rmultinom`. Output is of the form ``` [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 0 0 0 0 0 0 0 0 0 0 [2,] 0 0 0 1 0 0 1 1 1 0 [3,] 1 1 1 0 1 1 0 0 0 1 ``` Where there is a single `1` in each column. The `1` is in the first row for "R" pixels, the second row for "G" and the third row for "B". [Answer] # Pyth - ~~11~~ 10 bytes Takes RGB 2d bitmap and outputs bitmap with indexed 3-bit color. ``` mLOs.emkbk ``` That level of nesting is hurting my head. [Try it online here](http://pyth.herokuapp.com/?code=mLOs.emkbk&input=%5B%5B%5B1%2C2%2C3%5D%2C%5B3%2C4%2C5%5D%5D%2C%5B%5B1%2C2%2C3%5D%2C%5B3%2C4%2C5%5D%5D%2C%5B%5B1%2C2%2C3%5D%2C%5B3%2C4%2C5%5D%5D%5D&debug=1). [Answer] # J, ~~20~~ ~~18~~ 17 bytes ``` (>:({~?@#)@##\)"1 ``` The image is input as an array with dimensions *h* x *w* x 3 representing the RGB values as integers in the range 0 - 255. The output is a table with dimensions *h* x *w* where 1 is an rgb value of (255, 0, 0), 2 is (0, 255, 0), and 3 is (0, 0, 255). ## Explanation The `()"1` represents that this verb is to be applied to each array of rank 1 in the input, meaning that it will apply to each *pixel*. ``` >:({~?@#)@##\ Input: array [R G B] >: Increment each, gets [R+1, G+1, B+1] #\ Gets the length of each prefix of [R G B], forms [1 2 3] # Make a new array with R+1 copies of 1, G+1 copies of 2, and B+1 copies of 3 ( )@ Operate on that array # Get the length of the array of copies, will be R+G+B+3 ?@ Generate a random integer in the range [0, R+G+B+3) {~ Select the value at that index from the array of copies and return ``` ![Example](https://i.stack.imgur.com/RIMcE.png) [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~8~~ 7 bytes ``` Jx‘Xµ€€ ``` The input is a 3d list with dimensions *h* x *w* x 3. The output is a 2d list with dimensions *h* x *w* where 1 represents the rgb value (255, 0, 0), 2 is (0, 255, 0), and 3 is (0, 0, 255). The sample input below is the top-left 4 x 4 region of the Mona Lisa image. [Try it online!](http://jelly.tryitonline.net/#code=SnjigJhYwrXigqzigqw&input=&args=W1tbOTcsMTIxLDEyMV0sWzY1LDg4LDg0XSxbODMsMTA1LDkzXSxbODQsMTA1LDkwXV0sW1s4NywxMTMsMTA3XSxbMTAwLDEyNCwxMTZdLFsxMDgsMTI5LDEyMF0sWzY0LDg0LDcyXV0sW1s3MywxMDIsODZdLFs2Nyw5Myw4MF0sWzgwLDEwMSw5M10sWzg4LDEwMyw5OV1dLFtbODEsMTExLDg2XSxbODksMTE1LDk5XSxbOTcsMTE3LDExMl0sWzk2LDExMSwxMTNdXV0) ## Explanation ``` Jx‘Xµ€€ Input: The 3d list of rgb pixels µ Begin a monadic chain (Will operate on each pixel, input: [R, G, B]) J Enumerate indices to get [1, 2, 3] ‘ Increment each to get [R+1, G+1, B+1] x Make R+1 copies of 1, G+1 copies of 2, B+1 copies of 3 X Select a random value from that list of copies and return €€ Apply that monadic chain for each list inside each list ``` [Answer] # Python 3, 119 bytes Where `m` is the input taken as a 2-d array of pixels where each pixel is a list of the form `[r,g,b]`. At each pixel's position, returns `0,1,2` to represent `(250,0,0), (0,250,0), and (0,0,250)` respectively. ``` import random lambda m:[map(lambda x:x.index(sum((((i+1)*[i])for i in x),[])[random.randint(0,sum(x)+2)]),i)for i in m] ``` ]
[Question] [ Given a string, return that string's "luck". A string's luck, as I completely just made up for the purpose of this challenge, is an integer, determined as so: * The base luck for a string is 1. * For each consecutive letter it shares with the word "lucky" (case insensitive), multiply the luck by 2. For instance, if your string was "**lu**mberjack" or "sma**ck**" you'd multiply by 4. (More specifically, 2^number of consecutive characters shared.) + The shared letters have to be in the same consecutive order it appears in "lucky" but can start anywhere in the word for the same value ("luc" has the same 8\* multiplier as "cky"). + If the word has multiple occurrences where it shares consecutive characters with lucky, use the longest consecutive string of the characters. * For ANY letter it shares with the word "omen" subtract 2 from the luck. + It can match a character any amount of times, in any order. For instance the string "nnnnnomemenn" loses 24 luck (12 matching letters) Example: ``` luck("lucky") >>32 ``` 2^5 (5 consecutive letters) = 32 ``` luck("firetruck") >>6 ``` 2^3 - 2 (3 consecutive letters from *uck*, *e* shared with omen) ``` luck("memes") >>-7 ``` 1 - 8 (base amount, 4 shared with "omen") This is code golf, so the answer with the fewest bytes wins. You can input and output any way you'd like - write a function, use standard input, etc. For functions, assume whatever data type would make sense for that language. (For example, in JavaScript, you'd be passed a `String` and return a `Number`) Edit: You can assume any input is lowercase. [Answer] ## [05AB1E](https://github.com/Adriandmen/05AB1E/), ~~36~~ ~~32~~ ~~28~~ 26 bytes ``` Œv'¸éyåiyˆ}}¯é¤go¹'ƒÖ¦Ãg·- ``` **Explanation** ``` Œv } # for each substring of input '¸éyåi } # if substring is part of "lucky" yˆ # add it to global array ¯é¤ # get the longest such substring go # raise 2 to its length ¹'ƒÖ¦Ã # remove all chars from input that isn't in "omen" g· # get length and multiply by 2 - # subtract # implicitly display ``` [Try it online](http://05ab1e.tryitonline.net/#code=xZJ2J8K4w6l5w6VpecuGfX3Cr8OpwqRnb8K5J8aSw5bCpsODZ8K3LQ&input=b21lbnM) Saved 2 bytes thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan) [Answer] ## JavaScript (ES7), ~~123~~ ~~112~~ 107 bytes ``` s=>2**[5,4,3,2,1,0].find((i,_,a)=>a.some(j=>s.includes("luckyL".substr(j,i))))-2*~-s.split(/[omen]/).length ``` Edit: Saved 11 bytes thanks to @Titus by assuming that the letter `L` does not appear in the input. Saved 5 bytes thanks to @Oriol. ES6 version for ~~125~~ ~~114~~ 109 bytes: ``` f= s=>(1<<[5,4,3,2,1,0].find((i,_,a)=>a.some(j=>s.includes("luckyL".substr(j,i)))))-2*~-s.split(/[omen]/).length ; ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o></pre> ``` [Answer] # Pyth, ~~27~~ ~~26~~ 28 bytes ``` -^2le+k}#"lucky".:Q)yl@"omen ``` 1 byte saved thanks to OP :-) Explanation: ``` Implicit Q as input .:Q Find all substrings of input +k}#"lucky" Filter for substring of "lucky", prepend "" in case of [] e Take last element, which is longest l Get its length ^2 Raise two to that @"omen"Q Filter Q for characters in "omen" l Get length; counts how many characters in "omen" there are y Double that - Find the difference ``` [Test it here](http://pyth.herokuapp.com/?code=-%5E2le%2Bk%7D%23%22lucky%22.%3AQ%29yl%40%22omen&test_suite=1&test_suite_input=%22lucky%22%0A%22firetruck%22%0A%22memes%22&debug=1). [Answer] # Ruby, ~~91~~ 87 bytes `String#count`'s finnicky usage strikes again! (When passed a String, it counts all occurrences of each letter in the function argument instead of all occurrences of the entire string.) [Try it online](https://repl.it/C9sa/1) ``` ->s{2**(z=0..5).max_by{|j|z.map{|i|s[b="lucky"[i,j]]?b.size: 0}.max}-2*s.count("omen")} ``` A version that takes in lines from STDIN and prints them: 89 bytes (86 +3 from the `-n` flag) ``` p 2**(z=0..5).max_by{|j|z.map{|i|$_[b="lucky"[i,j]]?b.size: 0}.max}-2*$_.count("omen") ``` [Answer] ## Ruby: 100 bytes ``` ->s{2**(m=0;4.times{|j|1.upto(5){|i|m=[i,m].max if s.match"lucky"[j,i]}};m)-s.scan(/[omen]/).size*2} ``` [Answer] # Javascript - 206 Bytes ``` r=>{var a="lucky";r:for(var e=5;e>0;e--)for(var n=0;6>n+e;n++){var o=a.substring(n,e+n);if(r.includes(o))break r}for(var t=0,e=0;e<r.length;e++)('omen'.indexOf(r[e])+1)&&t++;return Math.pow(2,o.length)-2*t} ``` [Answer] # Ruby, 57 bytes ``` b=gets.count'omen' $.+=1while/[lucky]{#$.}/ p 2**$./2-2*b ``` `gets` sets `$.` to 1 as a side effect, then we increment it until the regular expression matching `$.` consecutive lucky characters no longer matches. [Answer] # Haskell, 99 Another approach... I just learned about function aliasing ``` import Data.List s=subsequences i=intersect l=length f n=2^(l$last$i(s"lucky")$s n)-2*l(i n$"omen") ``` ### Usage ``` f"lucky" 32 f"firetruck" 6 f"memes" -7 ``` [Answer] # Mathematica, 86 bytes Code: ``` 2^StringLength@LongestCommonSubsequence[#,"lucky"]-2StringCount[#,{"o","m","e","n"}]& ``` Explanation: `LongestCommonSubsequence` returns the longest contiguous substring common to the input and `"lucky"`. `StringLength` gives its length. `StringCount` counts the number of occurrences of the characters of `"omen"` in the input. [Answer] ## Python (139 Bytes) ``` import itertools as t s=input() print 2**max([j-i for i,j in t.combinations(range(6),2)if'lucky'[i:j]in s]+[0])-2*sum(_ in'omen'for _ in s) ``` [Answer] # TSQL, 233 bytes **Golfed:** ``` DECLARE @t varchar(99)='oluck' ,@z INT=0,@a INT=0,@ INT=1,@c INT=0WHILE @a<LEN(@t)SELECT @a+=IIF(@=1,1,0),@z=IIF('LUCKY'LIKE'%'+x+'%'and @>@z,@,@z),@c+=IIF(x IN('O','M','E','N'),2,0),@=IIF(@+@a-1=LEN(@t),1,@+1)FROM(SELECT SUBSTRING(@t,@a,@)x)x PRINT POWER(2,@z)-@c ``` **Ungolfed:** ``` DECLARE @t varchar(99)='oluck' ,@z INT=0 ,@a INT=0 ,@ INT=1 ,@c INT=0 WHILE @a<LEN(@t) SELECT @a+=IIF(@=1,1,0), @z=IIF('LUCKY'LIKE'%'+x+'%'and @>@z,@,@z), @c+=IIF(x IN('O','M','E','N'),2,0), @=IIF(@+@a-1=LEN(@t),1,@+1) FROM(SELECT SUBSTRING(@t,@a,@)x)x PRINT POWER(2,@z)-@c ``` [Try it online](https://data.stackexchange.com/stackoverflow/query/509344/determine-the-luck-of-a-string) [Answer] # Haskell (134 132 Bytes) ``` import Data.List c[]=[] c s@(_:x)=inits s++c x l=length g q=2^(maximum$map(\z->l q-l(q\\z))$c"lucky")-2*(l$intersect q"omen") ``` Not a code golfer nor a Haskell programmer, so would love some tips on this one. (Example: `g "firetruck"`) [Answer] # Python 3, ~~168~~ ~~157~~ ~~152~~ ~~139~~ ~~144~~ 136 bytes EDIT: Really obvious things I should have seen easier have been changed, and some slightly less obvious. Edit 2: stoopid (˚n˚). The program threw errors. I fixed it up. not actually 153 :( Thanks to Leaky Nun for saving 5 bytes, and to jmilloy for saving ~~13~~ 8 bytes. ``` s=input() p=q=k=len(s) m=0 while-~p: while-~q:m=(m,q-p)[(s[p:q]in"lucky")*q-p>m];q-=1 p-=1;q=k print(2**m-2*sum(i in"omen"for i in s)) ``` The program runs through all possibly possible substrings in input (possibly possible, because it computes impossible substrings as well, 8 to 7, for example), checks if the substring is in "lucky", then sets the exponent of 2 to the length of the substring should it be greater than the current value. Possibly could be improved by using only one while loop. Could possibly use some improvement; I'm still getting the hang of this. [Answer] # PHP program, ~~139~~ 135 ~~108~~ bytes quantum leap fails for multiple substrings where the first occurence is shorter. :( actually I could save another 7 bytes in PHP<5.4 with register\_globals on ``` <?for($s=$argv[1];$i<5;$i++)for($j=6;--$j;)$r=max($r,strstr($s,substr('lucky*',$i,$j))?2**$j:1);echo$r-2*preg_match_all('/[omen]/',$s); ``` usage: `php -d error_reporting=0 <filename> <string>` +5 for a function: ``` function f($s){for(;$i<5;$i++)for($j=6;--$j;)$r=max($r,strstr($s,substr('lucky*',$i,$j))?2**$j:1);return$r-2*preg_match_all('/[omen]/',$s);} ``` **tests** (on the function) ``` echo '<table border=1><tr><th>input</th><th>output</th><th>expected</th><th>ok?</th></tr>'; foreach([ 'lumberjack'=>0, 'smack'=>2, 'nnnnnomemenn'=>-23, 'lucky'=>32, 'omen'=>-7, 'firetruck'=>6, 'memes'=>-7, 'determine the “luck” of a string'=>0, 'amazing'=>-3, 'wicked'=>2, 'chucky'=>16, 'uckyuke'=>14, 'ugly'=>2, 'lucy'=>8, 'lukelucky'=>30 ] as $x=>$e){ $y=f($x); echo"$h<tr><td>",$x,'</td><td>',$y,'</td><td>',$e,'</td><td>',$e==$y?'Y':'N',"</td></tr>"; }echo '</table>'; ``` [Answer] # Scala, 155 bytes ``` def f(w:String)=(1::List.fill((for(a<-1 to 5;s<-"lucky".sliding(a))yield if(w.contains(s)) a else 0).max){2}).product-2*w.filter("omen".contains(_)).length ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc) with flag `/u:System.Text.RegularExpressions.Regex`, 99 bytes ``` n=>(1<<Matches(n,"l?u?c?k?y?").OrderBy(x=>x.Value).Last().Length)-n.Count(x=>"omen".Any(c=>c==x))*2 ``` [Try it online!](https://tio.run/##ZY9fS8MwFMWf108Rgg@J66JOUFj/oUNBmAhu6MPYQ8luu7AuGUmqLaVf3ZoOdaJPl3s453fP5WbEjejuS8lDY7WQuS@kjbOok1FMLsLwMbV8A4ZIHxdJmfBkm9QJpuxJr0Hf1qSK4oq9pEUJlM1SY4kbIHO7oSPJpqqUtrdgtQOJ2Y2sCY9iHkUVpafjzgu8t1QjC8ZOUwMGRUjCOyLHJnS5ajyCi5Jva@xfjqnvtkxosNpJ2L86CDvYgcH@6Jq2gedlShMXRcLhzgM3wuOFr3JOHQ6p13iDqZJGFcBetbBATnAj2gnCNPAGfTN96JSRn/xSrNiDhd3FtyNXau0s/wzj4A97JmTPh2oP3MIaNX2SLdT88Cuhre9YFjXu5G@1r9J2H2pvhaN1Z@VkXhvHZwuoLHuGvCxSfVftXcz0jl6C6hM "C# (Visual C# Interactive Compiler) – Try It Online") ]
[Question] [ Given an input integer, output the volume corresponding to the value. The value will always be in the range \$[0,100]\$. ## Examples If the input \$=0\$: ``` _/| | |\/ |_ |/\ \| ``` If the input \$>0\$ and \$<33\$: ``` _/| | |\ |_ |/ \| ``` If the input \$\ge33\$ and \$<66\$: ``` _/| \ | |\ \ |_ |/ / \| / ``` If the input \$\ge66\$, \$\le100\$: ``` _/| \ \ | |\ \ \ |_ |/ / / \| / / ``` ## Rules * Input/output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * You can print it to STDOUT or return it as a function result. * Either a full program or a function are acceptable. * Any amount of extraneous whitespace is permitted, provided the characters line up appropriately. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. [Answer] # JavaScript (ES6), 98 bytes ``` n=>` _/|2 | |\\0 |_ |/1 \\|3`.replace(/\d/g,k=>n?(k&1?' /':' \\').repeat(n/33^n>98):['/\\'[k]]) ``` [Try it online!](https://tio.run/##dcoxDoIwFADQvaf4k@2PSgtNiJIAB6EIDRaikJYAcerdK44OzO@99Uev3fKat6t1TxP6PNi8aKHhPiEewCsliG/A85gAKOVlGy1mnnRnGFdPPlzGvLAlG09xSYHTjO6J4u8YvTHLpXzY4n7DrKJ8l2qsawyds6ubTDS5gfVMIMAZqLIUyb/IBI9EHkmaHkksBGL4Ag "JavaScript (Node.js) – Try It Online") ### How? We use the following template: ``` _/|2 | |\0 |_ |/1 \|3 ``` If \$n=0\$ (volume muted): * \$0\$ is replaced with `/` and \$1\$ is replaced with `\` * the other digits are removed If \$n\neq 0\$: * odd digits are replaced with the string `" /"` repeated \$k\$ times * even digits are replaced with the string `" \"` repeated \$k\$ times where \$k\$ is defined as: $$k=\cases{\left\lfloor n/33\right\rfloor&\text{$n<99$}\\ 2&\text{$n\ge 99$} }$$ [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~65~~ 64 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` „ /SõD‚„\ ‚D4δ∍D)T•4a֙镓| 0\ 1/“ÅвJrI33÷IĀ+©è‡∊'_1•uтÄ•22в®è‚ǝ ``` When I started I thought I would be able to make this pretty short with the approach I had in mind, but it had some annoying edge cases to fix.. Can definitely be golfed, though. Will take another look later on. [Try it online](https://tio.run/##yy9OTMpM/f//UcM8Bf3gw1tdHjXMArJjFA43AVkuJue2POroddEMedSwyCTx8LRHLYsOrwSyHzXMqVEwiOEy1AeyDrde2ORV5GlsfHi755EG7UMrD6941LDwUUeXerwhUK1@CNAQoJampgubDq0Dyc06Pvf/fwMA) or [verify some more test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLh6fx/1DBPQT/48FaXRw2zgOwYhcNNQJaLybktjzp6XTRDHjUsMkk8PO1Ry6LDK4HsRw1zahQMYrgM9YGsw60XNnkVVRobH95eeaRB@9DKwyseNSx81NGlHm8IVKsfAjQEqKWp6cKmQ@tAcrOOz/2vc2ib/f9oAx1DHWMjHWNjHWMTHTNTHTMzHTNzHUsLHUtLHUMDg1gA). **Explanation:** ``` „ / # Push string " /" S # Convert it to a list of characters: [" ","/"] õD‚ # Push an empty string "", duplicate it, and pair them together: ["",""] „\ # Push string "\ "  # Bifurcate it (shorter for duplicate and reverse copy) ‚ # Pair them together: ["\ ","\ "] D # Duplicate it 4δ∍ # Extend both inner strings to size 4: ["\ \ ","\ \ "] D # Duplicate it ) # Wrap all lists on the stack into a list: # [[" ","/"],["",""],["\ ","\ "],["\ \ ","\ \ "],["\ \ ","\ \ "]] T # Push 10 •4aÖ™é• # Push compressed integer 17523821317 “| 0\ 1/“ # Push string "| 0\\n1/" Åв # Convert the integer to custom base-"| 0\\n1/" J # And join these characters together to a single string: # " /| 1\n # | |\0" r # Reverse the items on the stack (list, 10, string to string, 10, list) I33÷ # Push the input, and integer-divide it by 33 IĀ # Push the input again, and truthy it (0 if 0; else 1) + # And add them together (0→0; 1..32→1; 33..65→2; 66..98→3; 98..100→4) © # Store it in variable `®` (without popping) è # And index it into the list we created at the start ‡ # Then transliterate the ["1","0"] of 10 to the strings in this pair ∊ # Now vertically mirror the entire string # (i.e. " /| \n # | |\/" becomes: # " /| \n # | |\/\n # | |/\\n # \| " •/Tδ• # Push compressed integer 7095187 ₂в # Converted to base-26 as list: [15,13,17,21,21] ® # Push variable `®` again è # Index it into this list 1 ‚ # Pair it with a leading 1 '_ ǝ '# And insert a "_" at those 0-based positions inside the string # (after which the result is output implicitly) ``` [See this 05AB1E tips of mine (section *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•4aÖ™é•` is `17523821317`; `•/Tδ•` is `7095187`, and `•/Tδ•₂в` is `[15,13,17,21,21]`. [Answer] # [Python 2](https://docs.python.org/2/), ~~111~~ ~~101~~ 90 bytes ``` n=input() for s in'\ _/|','\| |\/','/|_ |/\\','/ \|':print s[1:6+0**n],s[:n>32],s[:n/66] ``` [Try it online!](https://tio.run/##Jc2xCsIwEIDh/Z7i6BKthaQJ3lCoizr7AE3pIBWzXEMbQeHePba6fcMPf/yk58Q2n2@XazsXRZG5DRxfabeHxzTjgoGVx0GLqpQXRPF6lZYBRXu/EdGLauIcOOHS1Q0dTFlyXy1dwydn/9BEff41sE5gfI933J4lZQPOgnNARyCC2pgv "Python 2 – Try It Online") -11 bytes, thanks to xnor [Answer] # [Lua](https://www.lua.org/), ~~308 259 246 242 219~~ 180 bytes ``` i=io.read("*n") print(i<1 and[[ _/| | |\/ |_ |/\ \|]]or i<33 and[[ _/| | |\ |_ |/ \|]]or i<66 and[[ _/| \ | |\ \ |_ |/ / \| /]]or[[ _/| \ \ | |\ \ \ |_ |/ / / \| / /]]) ``` [Try it online!](https://tio.run/##XcqxCoAgFAXQ3a@4NGVDEoFTfUlGCDU8CA2p7f27EVZGZz7rYWOknnwdFjuXReUKKbZAbi@pa2DdPAyYFAsG2CjBE1gZARgeRx9AXdv@V0rfo3U@MGnhfkgT6rpPySm3N15Vxqj1CQ "Lua – Try It Online") New to code golf and coding in general. Thanks to all comments for their help! [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 113 bytes ``` param($n)' _/|'+($y=' \'*($x=($n-ge33)+($n-ge66))) '| |\'+($y,'/')[!$n] '|_ |/'+(($z=' /'*$x),'\')[!$n] " \|$z" ``` [Try it online!](https://tio.run/##NYzNCsIwEITveYq1LG62rUQM5JYnMVJ6SPVQa6kH@xOfPYYULzPDN8OMr4@f3g/f9xE7u4k4tlP7lDgwQaMCVRIXS@ColDjbxE93rzVXezKGmQUFgODytCZFfD3gcEu0gaASlbimB0UlzlyT@/cFgAu4FlF8hThiB@es@rKbzmZM/AE "PowerShell – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) (`-p`), 86 bytes inspired from @Arnauld's solution ``` $_=' _/|3 | |\\1 |_ |/0 \|2'=~s,\d,$_?" $&"x($_/33-$_/99):$&<2&&$&^1,ger;y;0213;//\ ``` [Try it online!](https://tio.run/##DczfCoIwFIDx@/MUBxmzYLY/B0e2pCfoDUYjSEQQHepFwejRW958v7svdstY58xCW2KQiSAhJu81pIBJKkD0yZTtdxX@JVi4Fch48T6wIImqvU1zvDB@NZwz/tCi7xb3ccpoclL6nBVoIANEYGuwFpozaKV@c9yGeVpzNT5jru71SemdYdq6ffAH "Perl 5 – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~94~~ 92 bytes ``` param($n)33,66-le$n|%{$y+=' \';$z+=' /'} " _/|$y | |\$y"+'/'*!$n "|_ |/$z"+'\'*!$n " \|$z" ``` [Try it online!](https://tio.run/##LcjBCsIwEITh@z7FGkajVokYyEX6JoHSQ4qHGEs9SNrts8davcw/fP3zHYbXPcRY0NUTlb4d2sce6WDtyblzDEiynZCrWrPXN4zfY/RMihsjyCTM4pFVpY0@bpBIScNiMC7i/8LsZYFCM9EOHV/Wtddf7Brnygc "PowerShell – Try It Online") [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~32~~ ~~27~~ 26 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ┤#Mi‾‟⁸?⁸‾{÷u2m2\×+] ¶/+}═ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXUyNTI0JXVGRjAzTWkldTIwM0UldTIwMUYldTIwNzgldUZGMUYldTIwNzgldTIwM0UldUZGNUIlRjcldUZGNTUldUZGMTIldUZGNEQldUZGMTIldUZGM0MlRDcldUZGMEIldUZGM0QlMjAlQjYvJXVGRjBCJXVGRjVEJXUyNTUw,i=MzM_,v=8) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes ``` NθF AF›θ℅ι \C¹¦¹⸿\F¬θ/‖M↓⸿←P↑⁴←↖¹←_↑² _/ ``` [Try it online!](https://tio.run/##XY7NCsIwEITvPsWSUwIVW/FUT6Iggq1F8FYotaYYiElc0opPH5vWn@Jtdr@Z2a2uJVa6lM7tlGls2tzOHOmdLSe1RqAEVoRBL7fIS@tZAAe8CFVKKhhjkKFQtjPmOelSa22eNAog6vSb5DigviXVtmv/pmYeHHkteWUTgaiRxhv9UOO0tyS65TTe89r6oZFWmB7HJxPA4t@QfZifx7/Ew4IUZOwKYP67B4X/ybkoDN20lS8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input the volume. ``` F AF›θ℅ι \ ``` Output a space and a `\` for each character ordinal in space and `A` that the volume is greater than. In other words, output once for inputs of 33 or more and twice for inputs of 66 or more. ``` C¹¦¹ ``` Copy the `\`s one square diagonally. ``` ⸿\ ``` Output an extra `\` at the start of the second line. ``` F¬θ/ ``` If the volume was zero then add a `/`. ``` ‖M↓ ``` Reflect to complete the volume. ``` ⸿←P↑⁴←↖¹←_↑² _/ ``` Draw the speaker symbol. [Answer] # [Keg](https://github.com/JonoCode9374/Keg), `-hd` 167 bytes ``` ¿:0=[` _/|\n| |\\/\n|_ |/\\\n \\|`|:1\!"∂[` _/|\n| |\\\n|_ |/\n \\|`|:\!B"∂[` _/| \\\n| |\\ \\\n|_ |/ /\n \\| /`|` _/| \\ \\\n| |\\ \\ \\\n|_ |/ / /\n \\| / /` ``` [Try it online!](https://tio.run/##y05N////0H4rA9voBIV4/ZqYvBoFhZqYGH0gI16hRj8mJiZPQSEmpiahxsowRlHpUUcTqkKYOriqGEUnhCoFsAKwQgW4WgWYagX9hBqYMlSVyIqRlAM1/P9vZvZfNyMFAA "Keg – Try It Online") Definitely golfable by using variables and string formatting. That's what Imma go do now. Anyhow, it acts as a sort of switch statement to determine which range the volume is in and prints the corresponding string. Nevermind. Variables only make the program longer. [Answer] # [Python 3](https://docs.python.org/3/), 109 bytes ``` lambda n:'\n'.join(i[:5+0**n]+(n//33*(' '+j))[:4]for i,j in zip([' _/|','| |\\/','|_ |/\\',' \|'],'\\\//')) ``` [Try it online!](https://tio.run/##FYtBCoMwEADvfcXeNolLE5uaQ6AvcUUsJTRSVxEvLfm71dvAzCzf7T2L39OD988wPV8DSEQWvI5zFpXb2FTOGOkqJdZ6bxQCVqPWbbx3aV4h0whZ4JcX1SL0tiBhASjM9qQeimU@CIALdoR8CIta7@cs5@qoJn8j7yk0FALVzsULLGuWTSUlR/oH "Python 3 – Try It Online") [Answer] # [Lua](https://www.lua.org/), 196 bytes ``` i=tonumber(io.read()) t=[[ _/|%s | |\%s |_ |/%s \|%s]] t=(i==0 and t:format("","/","\\","")) or t while i>=33 do t=t:format(" \\%s"," \\%s"," /%s"," /%s");i=i-34 end t=t:gsub("%%s","") print(t) ``` [Try it online!](https://tio.run/##RYxBCsIwEEX3OcUQKCSgRqgoKPEiTSktiTrQJpJOcZO7x9SFXcx/8Hl/xqXPGTUFv0yDiwLDIbreCikZ6aaBTqVqZgkgmZUdJFUIYErdtsURqPURem@Bro8Qp54E5zuuyhlTgksJIQKxzwtHB3jXdQ02AOnNB1OeF/dPtUHeUOO@PoHzlq2j57wMglc/g0v2juhJkMz5fPkC "Lua – Try It Online") A bit shorter (below 200) than the [other Lua answer](https://codegolf.stackexchange.com/a/195519/63068). ]