text
stringlengths
180
608k
[Question] [ Given a string containing only letters, output the length of the longest run of consecutive alphabetical letters the word contains, where order does not matter. An example algorithm may sort the word, remove duplicates, and then output the length of the longest run. ## Test Cases ``` watch -> 1 stars -> 3 antidisestablishmentarianism -> 3 backdoor -> 4 a -> 1 tutorials -> 4 ``` For example, `antidisestablishmentarianism` contains the letters `abdehilmnstr`. The longest runs are `lmn` and `rst`, both of length 3. ## Notes You may take all lowercase, all uppercase, or mixed-case letters as input, but the case cannot encode information about the word (i.e. you cannot make the first `n` characters capitalized where `n` is the length of the longest run). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10 9 8 7~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` OṬṣ0ZL ``` **[Try it online!](https://tio.run/##y0rNyan8/9//4c41D3cuNojy@f//f2JeSWZKZnFqcUliUk5mcUZual5JYlFmYl5mcS4A "Jelly – Try It Online")** 9 was using [Sok's method](https://codegolf.stackexchange.com/a/168433/53748): `ṢQẆẇƇØaṪL` ### How? ``` OṬṣ0ZL - Link: list of (single-case) characters e.g. codegolf O - ordinal (vectorises) [99,111,100,101,103,111,108,102] Ṭ - untruth (1s at those indices) [0,0,0,...,1,1,1,1,1,0,0,0,0,1,0,0,1] - ^ ^ ^ ^ ^ - i.e. indices: 1 99 103 108 111 0 - literal zero ṣ - split at [[],[],[],...,[1,1,1,1,1],[],[],[],[1],[],[1]] Z - transpose [[1,1,1],[1],[1],[1],[1]] L - length 5 ``` [Answer] # [R](https://www.r-project.org/), ~~44~~ 43 bytes Works on an array of lowercase characters. Edit: changed it from testing True values to multiplying by the T/F for a byte. ``` function(x,r=rle(letters%in%x))max(r$l*r$v) ``` [Try it online!](https://tio.run/##hY4xDsIwDEVnOEWHVklQFwRrDpO2qWrhJsh2S24fIgaEAhKe3/P7lGeb5y2MAjHo1JMl9Bq9iCfuIHTJmNUlTS2eqN1NnrVHzUJ8RxCtHk7GRfVKGWOaQzlrm/OxglgccQVdasgFgQnYF3hA4GX1oWjgAvD6dn@JgxtvU4xUBa5fgX8zZZNYgvg59fUoPwE "R – Try It Online") Does a run length encoding on letters that are in the supplied characters then return the max value for the trues. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~10~~ 9 bytes -1 byte thanks to H.PWiz ``` ≢⍉↑⊆⍨⎕a∊⍞ ``` [Try it online!](https://tio.run/##JY3NSsNQEIX3eYrZjUILFrtyl/5Ag20CTcT1JeaWYJobbm4RKd1JbKK36MKlgl35AiIUfJl5kTjq7pz5Ps6IIute3YpMLbpxJsoyjVvavaSKqqcTh7b3sqV6T7am6pmaiuwHU0Hbhuxby7iVLJLd9ejxGzdr7CADZEdz@ERq9ky@uMcaJQLZVzArnUOslkWWmAQKrRZaLCHNjQIBcpXHJlU5lApuEohFDiYpDaTGMfxpzaNUv2uOkuzhDNU10sMdSpFm/PDAWG8cvHSj4QQN9BwMI3cecjx10PUjb@SFYz4Npl44mY19hp7re@Hs3xi4w/NREMy59Z2jDrp4/DcSXUQBi9Pfof4P "APL (Dyalog Classic) – Try It Online") `⍞` inputs a string `⎕a` is the uppercase English alphabet `⎕a∊⍞` a boolean length-26 vector - which letters occur in the string? `⊆⍨` form vectors of consecutive 1s `≢⍉↑` mix into a matrix, transpose, and return its height - effectively, find the length of the longest vector of 1s [Answer] # [Perl 6](https://perl6.org), 41 bytes ``` {max values bag .ords.sort.squish Z-0..*} ``` [Test it](https://tio.run/##TY9BTgMxDEX3OYVVVQjKNJRSdTMq4hCsQCw8SaARmWSInbao6snYcbEhaUBil/z//rc9mOjWYyIDu7VUrRD9J1yooA1sxmOPB9ihS4agwzeQIWqSFCJL@kiWtvA0X0g5O4059MCGGDbgrDf0/SX3BX6etYtm@ZJry4THTLRicOjhuuI3sMzea4i/8fk9TK0fEjcwNYfBKDYajgLAEpSlLqt79c9uYFLFc/hPnYjTuEdW26LeCmKMVJ53Aj1bbSlPw87lG3rjs2nRW@or0aF61yHvlH8rgbWBE4dMuXPL6gc "Perl 6 – Try It Online") ## Expanded: ``` { # bare block lambda with implicit param $_ max # find the max values # get the values from the following Bag (repeat counts) bag # find the repeats .ords.sort.squish # get the unique ordinals (method call on $_) Z- # zip subtract with 0 .. * # Range starting with 0 } ``` Given `'stars'`, `.ords.sort.squish Z-0..*` would return `(97,113,113,113)` [Answer] # [Haskell](https://www.haskell.org/), 35 bytes ``` f[]=0 f s=1+f[c|c<-s,elem(succ c)s] ``` [Try it online!](https://tio.run/##FcrBCsMgEATQe75ikR5amkJ7r18iOWw2iktWDa6hl/67tYdhGN5E1N2L9B7cYp9TALWve3D0pfdDZy8@XfUkArrp0sU688FG0cxGG1YdjbnxxurHXoU1Jp@HMGbWNHhF2rdS6v850s5WBoqaZUrIGSwclXODCyQ8IID0Hw "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), 50 bytes ``` f s=maximum$scanl(\x c->sum[x+1|elem c s])0['a'..] ``` [Try it online!](https://tio.run/##FcpBCsIwEAXQvacYQqGKWvQA9SK1i2makqEzackk2IV3j3Hx@Xze96irYy5lAe0FD5IsjVoMfH4fYO8vzTIc1@fXsROwoOPlMbTYdt1YuB/MB5P15mY0YdTaGBLNpK7uiUm9uFCFMJBK5QntOm9b/D9rUk5bRVYzngQpQA97pJCgAcEdFuDyAw "Haskell – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 51 bytes The case of the input string doesn't matter. ``` s=>(g=_=>s&&1+g(s&=s*2))(Buffer(s).map(c=>s|=1<<c)) ``` [Try it online!](https://tio.run/##dY69DoIwFEZ3n4IwkFYjBGWkDL6IuZQWqv0hvUUX3712wAXDfM538j3gBci9msPZukFEySKyjozszjosivo0EiwYHi@UktsipfAEaWlgJjwJH1a3Lac0cmfRaVFqNxJJ8jcEPuWUZlWV1YcNxAAeV3jdQrBBDQpFknqtcDLCJl2BVWj2Nj3w5@CcX3nz19x7EpbgUlv/3jTxCw "JavaScript (Node.js) – Try It Online") ### How? We first convert the input string into a bitmask of encountered letters with: ``` Buffer(s).map(c => s |= 1 << c) ``` The bitwise shift is processed with an implicit modulo 32. Example: ``` "feedback" --> 100001111110 kjihgfedcba- ``` We then 'reduce' runs of consecutive 1's in the bitmask by repeatedly AND'ing it with a left-shifted copy of itself until all bits are cleared: ``` 0100001111110 AND 1000011111100 --> 0000001111100 0000001111100 AND 0000011111000 --> 0000001111000 0000001111000 AND 0000011110000 --> 0000001110000 0000001110000 AND 0000011100000 --> 0000001100000 0000001100000 AND 0000011000000 --> 0000001000000 0000001000000 AND 0000010000000 --> 0000000000000 ``` The number of consecutive letters in alphabetical order is the number of iterations of the above process. Hence the recursive function: ``` g = _ => s && 1 + g(s &= s * 2) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 9 bytes ``` le}#G.:S{ ``` Input is assumed to be a lower case string. Try it out online [here](https://pyth.herokuapp.com/?code=le%7D%23G.%3AS%7B&input=%22stars%22&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=le%7D%23G.%3AS%7B&test_suite=1&test_suite_input=%22watch%22%0A%22stars%22%0A%22antidisestablishmentarianism%22%0A%22backdoor%22%0A%22a%22%0A%22tutorials%22&debug=0). ``` le}#G.:S{Q Q=eval(input()), G=lowercase alphabet. Trailing Q inferred. {Q Deduplicate input string S Sort it .: Take all substrings (these are generated in length order) }#G Filter out those that aren't found in the alphabet le Find the length of the last remaining element ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` 2Y2imY'*X> ``` Input is in lowercase. [Try it online!](https://tio.run/##y00syfn/3yjSKDM3Ul0rwu7/f/WS0pL8oszEnGJ1AA) Or [verify all test cases](https://tio.run/##FcpLCoAwDATQvRcJuOwBXHkEF3Zn@oEGmxaaiMevcTEMwxtGrfOazjtiD@u5zf2Y8KLGAguI4hBrbEqJJNsOlaRwbiaEjYSNA8Y79T7@p0Uf7YZV4AM). This uses a mix of [@Sundar's](https://codegolf.stackexchange.com/a/168431/36398) (old) and [@ngn's](https://codegolf.stackexchange.com/a/168430/36398) approaches. ### Explanation Consider input `'tutorial'` as an example. ``` 2Y2 % Push predefind literal 'abcdefghijklmnopqrstuvwxyz' % STACK: 'abcdefghijklmnopqrstuvwxyz' i % Push input % STACK: 'abcdefghijklmnopqrstuvwxyz', 'tutorials' m % Ismember: true for letters present in the input % STACK: [1 0 0 0 0 0 0 0 1 0 0 1 0 0 1 0 0 1 1 1 1 0 0 0 0 0] Y' % Run-length encoding % STACK: [1 0 1 0 1 0 1 0 1 0], [1 7 1 2 1 2 1 2 4 5] * % Multiply, element-wise % STACK: [1 0 1 0 1 0 1 0 4 0] X> % Maximum. Implicitly display % STACK: 4 ``` [Answer] # [Python 3](https://docs.python.org/3/), 55 bytes ``` f=lambda s:s and-~f({*s}&{chr(ord(c)+1)for c in s})or 0 ``` [Try it online!](https://tio.run/##HYq7CsIwAEVn/YpMJvEBilvBIX1Ag31Ak@IgDrEltKBpSbpIqb8eE5fL4Zw7fqZuUGdr5eUl3s9WABMYIFR7@Eo0b82ymZtOo0G3qMG7E5aDBg3oFTALdni0Xhgv7vBGeJTCPYCMk4p5IAWnMWWJE2FGWZonhUuUFJTlvockusZlWf2/fnjNS9czBh/BejXqXk1IIoOx/QE "Python 3 – Try It Online") --- # [Python 2](https://docs.python.org/2/), 58 bytes ``` f=lambda s,c=99,r=0:c and max(r,f(s,c-1,-~r*(chr(c)in s))) ``` [Try it online!](https://tio.run/##HY09C4MwGITn9le8W5ISoe2m4BA/wFA/wKR0KB3SiCjUKNGhXfrXbexy3N1zcNNn6UZzXtc2fKnh2SiYqQ59n9rwGGhQpoFBvbGlLXbAO1Hvaw9YdxZr0huYCSFrO1qYwaU7ujEZZ4gCEpLVYjOslDzhInVFlHORFWnpEGclF8XGIxZfkqqq/9tN5FVWjucCPYL9brK9WcCdk/UH "Python 2 – Try It Online") --- # [Python 2](https://docs.python.org/2/), 63 bytes ``` n=t=0 for c in input():n|=2**ord(c) while n:n&=n/2;t+=1 print t ``` [Try it online!](https://tio.run/##DcJBCoMwEAXQfU4RXIjahTVLZQ6TakoG9Cckv5RC75728fKHMcG1BqHczTMVu1vFf35xGFd8xU1TKsewj@Yd9QwWK3rB7DbeZDG5KGjZWudBPbSGSv84tcYrgL6oh9ar@wE "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes Saved 1 byte thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan): taking the contiguous substrings, then sorting by length (`Œ...é`) \$\to\$ using the powerset built-in instead (`æ`). ``` êæAÃθg ``` [Try it online!](https://tio.run/##MzBNTDJM/V9TVmmvpKBrp6BkX/n/8KrDyxwPN5/bkf7ftvZ/eWJJcgZXcUliUTFXYl5JZkpmcSqQl5STWZyRm5oHFM9MzMsszuVKSkzOTsnPL@JK5CopLckHCucUAwA "05AB1E – Try It Online") ### Also 6 bytes Saved 2 bytes, again thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan): using `ASå` instead `êÇ¥Θ`, thus also removing the need to increment the maximum at the end. See [the revision history](https://codegolf.stackexchange.com/revisions/168458/2) to compare the beviours of the two methods. ``` ASåγOà ``` [Try it online!](https://tio.run/##MzBNTDJM/V9TVmmvpKBrp6BkX/nfMfjw0nOb/Q8v@G9b@788sSQ5g6u4JLGomCsxryQzJbM4FchLyskszshNzQOKZybmZRbnciUlJmen5OcXcSVylZSW5AOFc4oB "05AB1E – Try It Online") ### How those works I like challenges like this one which lead to a variety of different approaches. ``` êæAÃθg | Full program. ê | Push a sorted and without duplicates version of the input. æ | Powerser. Aà | Keep those that also occur in the lowercase alphabet. θg | Take the length of the last one. θ and ` can be used interchangeably. -------+------------------------------------------------------------------------------- ASåγOà | Full program. A | Push the lowercase alphabet. S | Listify it (i.e. convert it to a sequence of characters). å  | Replace each char in the alphabet by 1 if its in the input, else by 0. γ | Split into chunks of equal adjacent elements. O | Sum each part. à | Extract the maximum of this list. Again, à and Z can be used interchangeably. ``` [Answer] # TSQL (Microsoft SQL Server), 206 bytes ``` WITH C AS (SELECT 1p,SUBSTRING(@,1,1)c UNION ALL SELECT p+1,SUBSTRING(@,p+1,1)FROM C WHERE p<LEN(@)),R AS(SELECT c d,1r FROM C UNION ALL SELECT c,r+1FROM R JOIN c ON ASCII(d)+1=ASCII(c))SELECT MAX(r)FROM R ``` For input, use the following `DECLARE` statement before the code: ``` DECLARE @ varchar(200) = 'propinquities'; ``` It is expected that input is all the same case (upper or lower doesn't matter, but mixed case would not work). **Ungolfed:** ``` DECLARE @data varchar(200) = 'propinquities' ;WITH CTE AS ( SELECT 1 as CharacterPosition, SUBSTRING(@data,1,1) as Character UNION ALL SELECT CharacterPosition + 1, SUBSTRING(@data,CharacterPosition + 1,1) FROM CTE WHERE CharacterPosition < LEN(@data) ), Runs AS ( SELECT Character, 1 rc FROM CTE UNION ALL SELECT b.Character, rc + 1 FROM Runs r JOIN CTE b ON ASCII(r.Character) + 1 = ASCII(b.Character) ) SELECT max(rc) from runs ``` **Explanation:** Splits the string into a a row for each character (adapted from <https://stackoverflow.com/a/27623321/1474939>) in the `CTE` cte. Then, finds runs of consecutive letters by converting to the ASCII code in the `Runs` cte. Lastly, it picks the largest run and reports back in the select statement. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~58~~ 56 bytes *Saved 2 bytes thanks to @gastropner* Uses the same approach as [my Node.js answer](https://codegolf.stackexchange.com/a/168434/58563). The case of the input string doesn't matter. ``` m,i;f(char*s){for(i=0;*s?m|=1<<*s++:(i++,m&=m*2););s=i;} ``` [Try it online!](https://tio.run/##XY3LDoIwFET3fsUNRtMCPlBXFvRbagtyI21Nb4kL9NuxCzHRZFZnTmbU6qrUOEerul7XUFLQ6NbtaTQ5ioapVvqU@NA4z7DaipTO5lkVZZlSlh0ZZllulpVJd1xwQRWK14g2gJFoGYdhBnD3ETQsWWj4TZLHFiBWDxlUm/AcNhsoJkhBevrA/QSlDaiR6lheOqTW1DZqKC2S@XcvUt20c/7DD9@N/6fQBxc3uvg2iVzMXuMb "C (gcc) – Try It Online") ### Commented ``` m, // m = bitmask of encountered letters i; // i = counter of max. consecutive letters f(char *s) { // f = function taking the input string s for( // main loop: i = 0; // start with i = 0 and assume m = 0 on first call // (it is forced back to 0 when the program terminates) *s ? // if we haven't reached the end of the string: m |= 1 << *s++ // update m by setting the appropriate bit for this character // (with implicit modulo 32) and advance the string pointer : ( // else: i++, // increment i m &= m * 2 // 'reduce' runs of consecutive 1's in m by AND'ing it with a ); // left-shifted copy of itself (e.g. 11101 & 111010 -> 11000; // 11000 & 110000 -> 10000); we stop when m = 0 ); // end of for() s = i; } // return i ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 100 bytes ``` c,o,u;n(t,e,r)char*r,*e,*t;{for(u=0,e=t;c=*t++;u=u<o?o:u)for(o=0,r=e;*r;*r++-c||(c++,r=e,++o));o=u;} ``` [Try it online!](https://tio.run/##RU5LasMwEF03pzAqxvqMoaVdRRW@RFbGG0WWY9FYKtKILpKc3ZWTQmAY5n0Z056MWVcDAbL0FMFCZGbWkUfgFjjKyxQizeoNrEJpFEchZFb5K3Rhn9kmhiJGZSWPZYRozfVKjRAbB0IExmRQWd7W19FOztvqQHuw7Cc6jxMlng6kTgNhlarqserum9aGDZ5AD572rDxl2@3omqnZN9gwuVu085Rddi8HSn41mplA9c7uMKGOqcCPB9Qe3eiSLfTx7NK8WF8MTnuXlqfrqM33GEIszOd/7tmIGUNJnNNDva1/ "C (gcc) – Try It Online") # Explanation ``` c,o,u;n(t,e,r) // setup, function declaration char*r,*e,*t;{ // K&R style for(u=0,e=t; // initialize global maximum u to 0, write string start to e c=*t++; // look at every character in the string u=u <o?o: u) // funny face for(o=0,r=e;*r; // initialize local maximum o to 0, look at entire string again *r++-c||(c++, // equal character found, search for next one r=e,++o)); // reset local pointer, increment local maximum o=u;} // return maximum character streak ``` [Try it online!](https://tio.run/##XZLBcpswEEDP5St26LhGIE/SSU6hjD@gt05OHl9ksRiNQeuKVRM3ybe7i03spDqApGWf3q6wi621x6PVpGPpM9aogwIZNzcwIMe9hiZ6y4481Gg7E8w4T2xrQh50jjrn8mVK@PntFwx86DCBhkIWq1uNFZcwhZ137Ezn/iJsO9qYDnrz7PrYQwQmuNXwFByjIILzW3mZwGNAcLbKuSjOpHdcR7QDw4B/MBxgFDKWMcgxwO07JYFYRYAftKQHgKjOqVKSP0BjrKBPqiSqocIyD@V/ph3ZD6I0iV7O9uzCxdhsjfNCzENRLOzra2aLQp9PxN9RMFfJhqKvtbTYBNuOCuDxmYH8aASioouClLr0LqDcxiSzJ@eFoUXTBuzF4bNlQlUs3@DjOBE4Bn@p5Koi8mh2x681Ns4jPGYrjWovBXGTpT5bp7NhnSqoYFbD8vTMZlatfapX2mcrJb8MLsbJct7MH@Y8V2XSSyMy9ZJ8eczSJ8O2TTV8V6fleK2DLO/OSyMdrN2Asr3p3NCO5ZjgjHdDf/1qY@yuJgqycz/lXYkcmSSjG87Rt@M/ "C (gcc) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~12~~ 10 bytes ``` 91:wX-dX>q ``` [Try it online!](https://tio.run/##y00syfmf8N/S0Ko8Qjclwq7wv0vIf/VwxxBnD3UudUe/EE8Xz2DX4BBHJx/PYA9fV78QxyBPRz/PYF@gNFA4KBhIOzk6e7v4@weBdABxSGiIP1CRT7A6AA "MATL – Try It Online") ### Explanation: `91:` - Create the list of numbers from 1 to 91. 91 is character '[', which comes after 'Z'. So this effectively creates the list of all characters from '\x1' to '['. (We mainly want those in the range ['A'-1 : 'Z'+1], but having the rest doesn't hurt, and needs less bytecount.) `w` - Implicit input, bring input to top of stack (assume 'TUTORIALS') `X-` - Set difference. This leaves only the characters that were *not* found in the input string, in their original order ('stable'). Stack: `' !"#$%&'()*+,-./0123456789:;<=>?@BCDEFGHJKMNPQVWXYZ['` `d` - Difference between successive elements in that list. Stack: `[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 1 1 1 1 1 1 1 2 1 1 1 1 1 1 2 1 2 1 2 1 5 1 1 1 1 1]` `X>` - Get the maximum of those differences i.e. the max number of consecutive alphabets missing from the set difference. `q` - Decrement to get actual character count --- Older: ### 12 bytes ``` Sud1=Y'*X>sQ ``` [Try it online!](https://tio.run/##y00syfmf8D@4NMXQNlJdK8KuOPC/S8h/9fLEkuQMdS71xLySzJTM4tTiksSknMzijNzUvJLEoszEvMziXKA0ULioGEgnJSZnp@TnF4F0AHFJaUk@UFFOsToA "MATL – Try It Online") [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), ~~17~~ 15 bytes ``` #1_{x^x^x+1}\-: ``` [Try it online!](https://tio.run/##NYzLDoIwFET3foWpLjTKotFV76cAyuVRaQpt0l4jhOCv19aEzOrMmYzOzMuEIMWBP5fpEXPha5GJQGI55vPXCbmfoLIaTpVENcAEM7hzue4oZx@kpmfAywSe0HkGtz@gIdUq38WyHpTvx85ErdAoP26bGhvdWusY3BNfGW5X9CYbx4NPKvwA "K (ngn/k) – Try It Online") `-` is there only to convert the chars to numbers (it doesn't matter if they are negative) `{` `}\` applies a function until convergence, preserving intermediate results `x+1` add 1 to each number in `x` `^` "without" - the list on the left without elements that occur in the list on the right `x^x^x+1` means `x` intersected with `x+1` `1_` drop the first element `#` count [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 54 bytes ``` O`. D`. . $&$&¶ T`l`_l`¶. (.)¶\1 $1 .(.+) $.1 O#^` 1G` ``` [Try it online!](https://tio.run/##DYtBCsMgFAX37xq1wVD44B0KXWbTZUn9SYR8ahSipTfzAF7MupjFDMzpsgRuV/2wbbKEe4egBjXUgqf19u1tLQRNYy0vA2VAmm4jFBlMl9nC9LP9OK87UuYzgUOWTZLrtnhJ@@FC78JB0oGF188W4wlG/ubYs09/ "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` O`. ``` Sort the letters into order. ``` D`. ``` Deduplicate the letters. ``` . $&$&¶ ``` Duplicate each letter on separate lines. ``` T`l`_l`¶. ``` Decrement the first of each pair. ``` (.)¶\1 $1 ``` If this now matches the previous character, join them back together. ``` .(.+) $.1 ``` Count the lengths of all the runs. ``` O#^` ``` Sort them in reverse numerical order. ``` 1G` ``` Take the first (largest). [Answer] # J, 16 bytes *-7 bytes thanks to FrownyFrog* ``` [:>./a.#;._1@e.] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o63s9PQT9ZSt9eINHVL1Yv9rcqUmZ@QrGCrYKqQpqJcnliRnqEOEjCFCxSWJRcWoQol5JZkpmcWpQKmknMzijNzUPKCizMS8zOJcqEoTiMqkxOTslPz8InUuEPgPAA "J – Try It Online") ## explanation ``` [: >./ a. #;._1@e. ] a. ( )e. ] is the ascii alphabet an element of the input: this will transform the alphabet into a 1-0 array, the ones representing the letters in the input #;._1@ split that 1-0 list up into pieces, using 0 as the delimiter, and transforming each chunk into its length. now we have a list of ints [: >./ take the max ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 98 92 bytes Thanks to Jonathan Frech for the suggestions. Uppercase-only. ``` f(char*s){int a[99]={0},i,j,k=j=i=0;for(;*s;a[*s++]++);for(;i<99;j=!!a[i++]*++j,k=j>k?j:k);} ``` [Try it online!](https://tio.run/##JY27DoIwGIV3n6JiTHrT6Ii1GIwmNlEGYSMMTRH9QdGAuhCevQJuJ9@5mdnVGDuB0tw/6QWt63cKz/nNsxk2N13RmjRQvpGOXTeRzaLlwHNeyFyCXIjsWWFBa6FjWjOWMEb@CNauK3I5HusYOk4ZGzpesclXBRGt7ScfGko8bFdXw/szRGmnvwQ1I4Qgw73hLQl6VV0sw840dTga8DdeJoSIUWutH0Rqp8J9GPnbowoPp30Q@WflByo8/QA "C (gcc) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) `-h`, 9 bytes Case insenstive, takes input as a string or an array of characters. ``` ;CôkU mÊn ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=O0P0a1Ugbcpu&input=InR1dG9yaWFscyIKLWg=) or [run multiple tests](https://ethproductions.github.io/japt/?v=1.4.6&code=O0P0a1UgbcpuCmcxbg==&input=Wwoid2F0Y2giCiJzdGFycyIKImFudGlkaXNlc3RhYmxpc2htZW50YXJpYW5pc20iCiJiYWNrZG9vciIKImEiCiJ0dXRvcmlhbHMiCiJhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5eiIKIiIKIlVQUEVSQ0FTRSIKIjgiCl0KLW1S) (the second line serves as a replacement for the `-h` flag so the flag can be used to process multiple inputs instead) --- ## Explanation ``` :Implicit input of string/array U ;C :The lowercase alphabet ô :Partition at characters returning truthy kU : Remove all characters in U from the current letter : This will return a non-empty string (truthy) if the current letter ISN'T in U m :Map Ê : Length n :Sort :Implicitly output the last element in the array ``` [Answer] ## Perl 5, 68 bytes ``` $"=<>;map{$"=~/$_/i&&++$$_||last for$_..z;$.=$$_ if$$_>$.}a..z;say$. ``` [Try it online](https://tio.run/##K0gtyjH9/19FydbGzjo3saAayKrTV4nXz1RT09ZWUYmvqclJLC5RSMsvUonX06uyVtGzBYoqZKYBSTsVvdpEkGBxYqWK3v//iU7JKalp6RmZWdk5uXn@BYVFxSWlZeUVlVX/8gtKMvPziv/r@prqGRgaAAA). Ungolfed: ``` use feature 'say'; my $s = <>; my $r; for ('a' .. 'z') { my $c = 0; for ($_ .. 'z') { last if $s !~ /$_/i; $c++; } $r = $c if $c > $r; } say($r); ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~66~~ ~~65~~ 63 bytes Assumes input only contains lowercase letters. First, it loops over the string and sets bits in an integer according to which letters are seen. Next, it counts the longest streak of 1 bits in the integer. Edit: `a` is global, so will be initialised to 0 at first call. The second loop makes sure it is reset to 0 before returning. Therefore, we can avoid resetting it manually. ``` a,l;f(char*s){for(l=0;*s;)a|=1<<*s++-97;for(;a;l++)a&=a*2;s=l;} ``` [Try it online!](https://tio.run/##PY3NbsIwEITP9VNYkUB2fqTSS1WZ8CRcNnacuDg29RpogTx7aiIlt535Zmdk1Uk5TVBaoZnsIeTIH9oHZut3kaPg8Kx3@32ORVF9fYoXESBsUXDY1pB/CKytGKerN4p2cwFNDeRB3s7BuKhZtkFaHehGHV1WUiypZsi5ICMhidMBjGNzvmPZDaLsswRfAiMEXAS4aJTBNpmNNdgPrUvYgDM4LJkG5El5H9af5bivTiNVq7vefJ/s4Pz5J2C8XG@/f2siXqJPtXYeHqd/ "C (gcc) – Try It Online") [Answer] ## Perl 5, 62 + 2 (`-nF` flag) = 64 bytes ``` $c[ord lc$_]=1for@F;$y[y///c]++for"@c "=~/((1 )+)/g}{say@y/2|0 ``` [Try it online](https://tio.run/##DchLCsMgEADQq0hwkSDpaCGrEnCVXU8QQrHGtgNGg7qRfo7ead/y7S75gYjbOaaVecsvy6huMenpxOtcAcAuQvyj0ZY14wfaVrFOdHB/P7OpusLxJYlMKLhidrmYq8f82FwoJqEJmLdv3AvGkKk/DwepJPVh@gE). ## Perl 5, 68 bytes ``` <>=~s/./$c[ord lc$&]=1/gre;$y[y///c]++for"@c "=~/((1 )+)/g;say@y/2|0 ``` [Try it online](https://tio.run/##BcHRCoMgFADQ932FhIxC1rVBT@XoB/YF0YMz1y6YhtcXYfTpc@ccNrq@lPGhToIWuJlDXJkz/LqoDrZoB57nDABmEeIdYjUZVqkT6rpjjWhgG0jnKcP9K0vRPuGKZCnpl0P67NYnHVF7pP3yC0fC4Kncnn0rO/kH). [Answer] # [SQLite](https://sqlite.org/lang.html) 265 ``` WITH w AS(SELECT'a'w),n AS(SELECT 1 n UNION ALL SELECT n+1 FROM n LIMIT(SELECT length(w)FROM w)),l AS(SELECT substr(w,n,1)l FROM n,w)SELECT max(v)FROM(SELECT min(n)v FROM(SELECT*FROM l,n EXCEPT SELECT l.l,unicode(l.l)-unicode(b.l)d FROM l,l b WHERE d>0)GROUP BY l); ``` Ungolfed: ``` WITH w AS (SELECT 'antidisestablishmentarianism' w) , n AS (SELECT 1 n UNION ALL SELECT n+1 FROM n LIMIT (SELECT length(w) FROM w) ) , l AS (SELECT DISTINCT substr(w,n,1) l FROM n,w ORDER BY l) , d AS ( SELECT l,n FROM l,n EXCEPT SELECT a.l l, unicode(a.l) - unicode(b.l) d FROM l a, l b WHERE d > 0 ) SELECT max(v) FROM ( SELECT min(d.n) v FROM d GROUP BY d.l ); ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~14~~ ~~13~~ 12 bytes ``` {⊇pS∧ẠsSl}ᶠ⌉ ``` [Try it online!](https://tio.run/##ATEAzv9icmFjaHlsb2cy//974oqHcFPiiKfhuqBzU2x94bag4oyJ//8idHV0b3JpYWxzIv9a "Brachylog – Try It Online") ``` { }ᶠ % Find all values that satisfy this predicate ⌉ % And get their maximum % The predicate being: ⊇pS % There exists a permutation of a subset of the input % Call it S ∧ % And, sS % S is a substring of Ạ % the set of alphabets, Ạ, l % Then, the length of that substring is the return value of the % predicate ``` Slow enough that it doesn't finish for input "antidisestablishmentarianism" on TIO. Relatively much faster one for +1 byte: ### 13 bytes ``` {dosS∧ẠsSl}ᶠ⌉ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vzolvzj4Ucfyh7sWFAfn1D7ctuBRT@f//0pJicnZKfn5RUr/owA "Brachylog – Try It Online") Use `dos` instead of `⊇p`: S is a `d`eduplicated s`o`rted `s`ubstring of the input, instead of just some permutation of some subset. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` CÞǔ0€∩L ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJDw57HlDDigqziiKlMIiwiIiwiYW50aWRpc2VzdGFibGlzaG1lbnRhcmlhbmlzbSJd) Port of Jelly. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~63~~ 59 bytes Not very golfy. -4 bytes thanks to [manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) ``` ->s{s.bytes.uniq.sort.slice_when{_2!=_1+1}.map(&:size).max} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3rXXtiquL9ZIqS1KL9UrzMgv1ivOLSvSKczKTU-PLM1LzquONFG3jDbUNa_VyEws01KyKM6tSNYHsilqoEcoFCm7RSol5JZkpmcWpxSWJSTmZxRm5qXkliUWZiXmZxblKsRClCxZAaAA) [Answer] # Ruby, 43 characters ``` ->s{(?a..?z).map{$.=s=~/#{_1}/?$.+1:0}.max} ``` Sample run: ``` bash-5.1$ ruby -e 'p ->s{(?a..?z).map{$.=s=~/#{_1}/?$.+1:0}.max}["backdoor"]' 4 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XVDLSsNAFMVl8hUXbBilSdpQF1KYZmVBXBTishSZTEYSmhe5E6ym8UfcBNGP0q9x8mgDbu7jnHsO996Pr6L0X5vPNf0u5bN1-zO1Vlhducy23bdrO2F5NbEp0vfZZfXk1DN3Yk-d5bxWzKHuJb8XD3kpEYhhLeYIhnMOSMCALblPFU9MIJ7AMu6qu0MuuBRBWz-WnAtEstMrXSMvTPKQAF2BY6oWJSuwaxdty1IZBREKBftxhGEiUjUQsTTCZJzyGd8HWVZ0yE2nGx1lKTOliPHE1rZgPIQgg2PUbmqCGLY76lrRrQwU1tuO3Onav2ODIfTHDg69bHQ6IUDpGQMXyGZPYKne4XkbTz1ApEH_06bp8x8) [Answer] # [Haskell](https://www.haskell.org/), 87 bytes ``` import Data.List maximum.map length.filter(`isInfixOf`['a'..'z']).subsequences.nub.sort ``` [Try it online!](https://tio.run/##DcxBCsJADADAu68IRVi95Ae9eREEHyBCU8na4CbWTRaKn1@dB8xC/uJSehdd3zXgREF4EY9dHpU20aaotEJhe8aCWUpwPUziZ8uyXfN0S5QQ0zfdj@htdv40tgc7WpvR/2VXEoMR1ioWsIcMgwdVH/oP "Haskell – Try It Online") Expects lowercase characters Explanation: ``` maximum.map length.filter(`isInfixOf`['a'..'z']).subsequences.nub.sort sort {- sort the characters -} nub {- remove duplicates -} subsequences {- all subsequences -} filter(`isInfixOf`['a'..'z']) {- all characters are adjacent -} map length {- length of filtered subsequences -} maximum {- maxmimum length -} ``` [Answer] # [Python 2](https://docs.python.org/2/), 95 bytes ``` lambda s:max(reduce(lambda(p,v),c:(c,v+[v[-1]*(c==p+1)+1]),map(ord,sorted(set(s))),(0,[0]))[1]) ``` [Try it online!](https://tio.run/##JY1LbsQgEETXySnY0cQ90jhLS56LEC8wYBnFfET3OMnpCU42pVK9J1X54T2n97bNH@0wcXVG0BTNN1TvntbD/wYFT4V2AovnoE99G5c3sPNchlEN46IwmgK5OqRc2Tsgz0BKKYQ76vuilO5S23IVJEISWn4ZtrtEIYlNpauYxMEF8n1Yj0B79KmjYFKgePHV2E@Xc/1zr@An584Pksv0@lJqSCwI5e0hcevnrf0C "Python 2 – Try It Online") [Answer] # Pyth - 11 bytes ``` le@.:G).:S{ ``` Input must be wrapped in quotes. If not allowed: # Pyth - 12 bytes ``` le@.:G).:S{z ``` Explanation: ``` l( e( @( .:(G), .:( S( {(Q) ) ) ) ) ) length( last element( intersection( all positive length substrings(the alphabet as string), all positive length substrings( sorted( uniquified(input) ) ) ) ) ) ``` ]
[Question] [ In as few bytes as possible, sort the input, *a delimited string OR list/vector/array of words, words contain printable ASCII except space (ASCII values 33-126)* into a numbered list, table, or something resembling a table, by length. Table rules are as follows: * Order is mandatory, direction is optional, either labelled rows from shortest to longest or vice versa, * Formatting is not the challenge. So as long as the output is some form of numerically labelled rows of words, a numbered list, or a list of lists, or similar output, then it is a satisfactory answer. * including/excluding gaps (NA values, see below examples for both methods of output) * Word case is untouched. How the word appears in input should be shown in output. **Input 1:** ``` Code Golf and Coding Challenges Meta ``` **or** ``` ("Code","Golf","and","Coding","Challenges","Meta") ``` **or similar** **Output 1:** ``` 1. NA 2. NA 3. and 4. Code Golf Meta 5. NA 6. Coding 7. NA 8. NA 9. NA 10. Challenges ``` **or** ``` 3. and 4. Code Golf Meta 6. Coding 10. Challenges ``` **or** ``` [[3, ['and']], [4, ['Code', 'Golf', 'Meta']], [6, ['Coding']], [10, ['Challenges']]] ``` **Input 2:** ``` My v3ry 3xc3113nt m0th3r ju5t 53rv3d u5 nin3 pizz@5 #JusticeForPluto ``` **Output 2:** ``` 1. NA 2. My u5 3. NA 4. v3ry ju5t nin3 5. NA 6. m0th3r 53rv3d pizz@5 7. NA 8. NA 9. 3xc3113nt 10. NA 11. NA 12. NA 13. NA 14. NA 15. NA 16. #JusticeForPluto ``` **or** ``` 2. My u5 4. v3ry ju5t nin3 6. m0th3r 53rv3d pizz@5 9. 3xc3113nt 16. #JusticeForPluto ``` **or** ``` [[2, ['My', 'u5']], [4, ['v3ry', 'ju5t', 'nin3']], [6, ['m0th3r', '53rv3d', 'pizz@5']], [9, ['3xc3113nt']], [16, ['#JusticeForPluto']]] ``` More examples can be provided if necessary but I think this should suffice for now. Please ask questions if you have them, this is my second attempt at a challenge. (the first failed dramatically) [Answer] # [R](https://www.r-project.org/), 28 bytes ``` split(w<-scan(,""),nchar(w)) ``` [Try it online!](https://tio.run/##BcFNCoMwEAbQq3zoJgGFypBdF111URB6BYmCKXaUyST@XD6@J6XEbQlq9mcb/cCmqSrbsJ8HMbu1pT@RSU7Q4anriBX/h84k@CWncCSZRiQHDkzYwnW9HOpPihr89F7luyRdyw0 "R – Try It Online") `split` does the trick; results in a `list()` where the element names are the lengths and the elements are `vectors` containing the words. [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), ~~12~~ 14 bytes ``` {x@=#'x@:<#'x} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqrrCwVZZvcLBygZI1v5PU9BQ8q1UslYqMy4CUcYVycaGhsZ5JUB2rkFJhnERkJFVagrimxoXlRmnABmlpkAiLzPPGEgVZFZVOYD4yl6lxSWZyalu@UUBOaUl@Uqa/wE "K (ngn/k) – Try It Online") this returns a k dictionary. lengths are key, words are value. let me know if this output format is acceptable. in q (wrapper around the k4 dialect), we can evaluate using the k interpreter and get q output formatting: ``` q)k){x@=#:'x@:<#:'x}("Code"; "Golf"; "and"; "Coding"; "Challenges"; "Meta") 3 | ,"and" 4 | ("Meta";"Golf";"Code") 6 | ,"Coding" 10| ,"Challenges" ``` note the extra colons, which aren't required for "eached" monads in the ngn implementation [Answer] # [Japt](https://github.com/ETHproductions/japt), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Input as an array of words, output as a 2D-array. ``` üÊËiDÎÊ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=/MrLaUTOyg&input=WyJDb2RlIiwiR29sZiIsImFuZCIsIkNvZGluZyIsIkNoYWxsZW5nZXMiLCJNZXRhIl0KLVE) ``` üÊËiDÎÊ :Implicit input of array ü :Group and sort by Ê : Length Ë :Map each sub-array D i : Prepend DÎÊ : Length of first element of D ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 19 bytes ``` *.classify(*.chars) ``` [Try it online!](https://tio.run/##DcrRCsIgGIbh813FB0FUB6MhdhJBMCgIBt2CTN0Mp@NXV@7mbWfvA@@syF7KlLHXuKGc6t6KEIzOhy1HQeFYrlUQGfXXkwz1tmlPsMapUFovFZ7eaggnscm4Ae0orFVuUAGdiqLqMhZGGezXs6ZhLmI6x5ERPolHcEYLk0gczjiG2azrnWP3SiGaXj08vW2K/g8 "Perl 6 – Try It Online") Pretty much does exactly as asked. ``` *.classify( ) # Classify the list *.chars # By number of characters ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 18 bytes ``` $args|group Length ``` [Try it online!](https://tio.run/##fVJdT8IwFH3fr2i0WBaHASsmPpAsMZHEgPHdGLJs3Ycp7Ww7QGC/HdtubA6Ifdi9t@f03HNvlvM1ETIllB5gPNkdYCASuU8EL3IwIyxR6aF0HL/vAH28Kpjj99Ezjwjy0JTTWIeARfqr7zKWmCQNKNXvidTFnKgAuV77eNek5iCMJlrPKLhd4MEC3UaVWJf3eOSZ5ifYaFiBraGWUNrMvTDc/Ee3WmFhAt6EeDTCTOl8OVQpFjr5KsamHmOxwmbyYqw/LGNYhzzbbn1TX78WUmUheeHinRaK/7eEe2vT9tVaFxdR@6lb22YXF9GYbNzVjk7YT5bdjne6Oa12PsLZ8lywBz1QTQPXXETSA5BschIqEoEJgIsKEkQWVOmLGxgD3xIdi/RraN9rV9IIzDJGjMix/oCLu7dgST4bKkK3@m5qf9lBSL7BVefxlSWWLhgwrkLOVJAxCWAcUEn@GnPKwy8 "PowerShell – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 147 129 bytes Thanks to girobuz and ceilingcat for the suggestions. This routine first finds the maximum string length of an input array of strings, then prints the words by length in reverse. ``` m,*t;f(int**s){for(t=s;*s;m=fmax(m,strlen(*s++)+1));for(;--m;)for(printf("\n%d",m),s=t;*s;)printf(" %s"+3*(strlen(*s++)!=m),*s);} ``` [Try it online!](https://tio.run/##XVHLSgMxFN3PV8SUQpJJxRK6iiOCoCCtuHFVuwiZV2SSKUmm1Jb5dccboaBucs85uY@TG71otJ4my1mUNTEuMhboue49iUWQLEhb1FYdieUh@q5yhIU8p/mSUpmS5GJhJU1o76G4JvjdzUvMLeWhiKmeXi7QPOBcMPK7z1UBiTBQjtPMON0NZYVuQyxNf93eZRkUIquMS76Q8o3mSLfKI8aAHCg6Z@gihO2uSBQhkhS23dEzfujLCnP81Hc1BOXAWNKMaxJoVQdGmioA2VRRYf7ytl6P/H@XzSckHIRPQRy1WC6Fi4DtTWyFB/AxrBJfCX8QacSwgsMZJyDszel0n/jseQjR6Oqx96/dEPs/0xIEMHJ4CUuLz4D97BfBv6D9EAPBmFJUExZhbzIbpy9dd6oJ06Kz3w "C (gcc) – Try It Online") [Answer] # JavaScript, 50 bytes Input as an array of words, output as an object where the keys are the word lengths and the values are arrays of words. ``` a=>a.map(w=>o[l=w.length]=[...o[l]||[],w],o={})&&o ``` [Try it Online!](https://tio.run/##FYw9DsMgDEbvwhCBRLmBs3To1BMgBisBksrFUYnC0PTs1Fm@nze8Fx5Yp8@67bfCc@wJOsKI7o2bbjCyJ2iOYsn7EsA754SE8/TBtmAZvj8zDNwnLpUpOuKsk/bqLipl1YMpSWGZJYWtJV9jQbqMscp5xh1VMKb/AQ) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 37 bytes ``` S` .+ $.& $& O#` r`(?<=\1.+)¶(.+ ) ``` [Try it online!](https://tio.run/##K0otycxL/P8/OEGBS0@bS0VPTUFFjctfOYGrKEHD3sY2xlBPW/PQNg09bQVNLoX//53zU1IV3PNz0hQS81IUgLzMvHQF54zEnJzUvPTUYgXf1JJEAA "Retina 0.8.2 – Try It Online") Explanation: ``` S` ``` Split the input on spaces. ``` .+ $.& $& ``` Precede each word by its length. ``` O#` ``` Sort numerically. ``` r`(?<=\1.+)¶(.+ ) ``` If two lines start with the same length, delete the newline and the length. [Answer] # [Python 2](https://docs.python.org/2/), ~~76~~ ~~74~~ 72 bytes ``` lambda a:sorted((l,[d for d in a if len(d)==l])for l in set(map(len,a))) ``` [Try it online!](https://tio.run/##FYs9DsMgDIWvYjEZialjJaYOnXqCtoMrmwTJAURYenpilvf36bX/2Gu5zRQ/U@n4MQHdz9qHMKKGN0OqHRhyAYKcQKUg@xj16xfQBU4ZeFBDY4G897P1XAYkRPeoLC64Z9VkRoVNbctlW2Entc8mp5WXDHL2vQA "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~9~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` €gêεùy‚ ``` -2 bytes thanks to *@Grimy*. Outputs a list of lists from lowest to highest, with the label at the right side instead of left. I.e. `[[["and"],3],[["Code","Golf","Meta"],4],[["Coding"],6],[["Challenges"],10]]`. [Try it online](https://tio.run/##yy9OTMpM/f//UdOa9MOrzm09vLPyUcOs//@jlZzzU1KVdJTc83PSgFRiXgqQBIpl5qWDGBmJOTmpeempxUCOb2pJolIsAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLjHVr5/1HTmvTDq85tPbSu@PDOykcNs/7X6hzaZv8/OlrJOT8lVUlHyT0/Jw1IJealAEmgWGZeOoiRkZiTk5qXnloM5PimliQqxeooRCv5VgK5ZcZFIMq4ItnY0NA4rwTIzjUoyTAuAjKySk1BfFPjojJjkIGlpkAiLzPPGEgVZFZVOYD4yl6lxSWZyalu@UUBOaUl@UqxsQA). **Explanation:** ``` €g # Get the length of each string in the (implicit) input-list ê # Sort and uniquify this list of lengths ε # Map each length `y` to: ù # Keep strings from the (implicit) input-list equal to this length y‚ # And pair it with the current length `y` # (after which the result is output implicitly) ``` [Answer] # [jq](https://stedolan.github.io/jq/), 53 bytes ``` map({l:length,s:.})|group_by(.l)|.[]|[.[0].l,[.[].s]] ``` [Try it online!](https://tio.run/##FYdNC4MgGID/i7sUiBQvXjrttMNg0F1kbC3KMHV@xGrutzu9PB/LO6X1Yaqv7OSoJj9j15FfHSerg7k/94rIOhLGIyOs4UTibE4c5ykxdNsRRhvYIvgM0LagfO618TPYHEug5SnYDV45As1QQkGWEcdxLn@6BufFMF607WXwGvE/ "jq – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 15 bytes ``` (⍋⊃¨⊂)≢¨{⊂⍺⍵}⌸⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X@NRb/ejruZDKx51NWk@6lx0aEU1kPWod9ej3q21j3p2POpa9D/tUduER719j/qmevqD1K43ftQ2EcgLDnIGkiEensH/0xTUnfNTUtUV1N3zc9KAVGJeijpYLDMvHcTISMzJSc1LTy0GcnxTSxLVAQ "APL (Dyalog Unicode) – Try It Online") APL is not particularly good at simply sorting. ### How it works ``` (⍋⊃¨⊂)≢¨{⊂⍺⍵}⌸⊢ ≢¨ ⌸⊢ Group the arg's elements by their lengths {⊂⍺⍵} Wrap each list of items, paired with the length (⍋⊃¨⊂) Idiom for sorting: ⍋ Grade up; gives indexes that will make the array sorted ⊃¨⊂ Map the indexes to the items ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~22~~ 28 bytes ``` ->w{w.group_by(&:size).sort} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1668ulwvvSi/tCA@qVJDzao4sypVU684v6ik9n@BQlp0tJJzfkqqko6Se35OGpBKzEsBkkCxzLx0ECMjMScnNS89tRjI8U0tSVSKjf0PAA "Ruby – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~31~~ ~~27~~ 23 bytes Takes input as a newline-separated list of words (I haven't noticed that's allowed at first). ``` .+ $.& $& N` D`\d+ ¶ ``` I'll add the explanation later (for now, the previous revision's explanation without the first line works perfectly). [Try it online!](https://tio.run/##K0otycxLNPz/X0@bS0VPTUFFjcsvgcslISZFm@vQNgUuhf//A4ry04sSc3Mz89K5AkqrqnJSi7kS81K4nPNTUrnc83PSYDyQAueMxJyc1Lz01GIA "Retina – Try It Online\"PSFQJKq6pyUosVEvNSFJzzU1IV3PNz0mA8kALnjMScnNS89NRiAA \"Retina – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes ``` lᵍ{hl}ᶻ¹o ``` [Try it online!](https://tio.run/##DcfBCoIwGADgV/lZ14JqeK1AKAiE7tFh6dLF2mJumoqHPBQdgh6li4F1603mi1jf7dsq4kcZl@G4K1IEgwmgdGqba1ud28uzrSr7vpW2fnTc1vci4qV9fb6N7Lo1cmVAYSH5DogI4D8mQnAjwjkVIY3Bo5qgPvIySLDKAJ98PBphoeEw1BFWsDeOBgerBAdgHBBMYDiyPJ850FuaWDOfzqVacaMl2vwA "Brachylog – Try It Online") Takes input as a list of words (the testing header converts from space-separated for convenience). Output is as a list of pairs `[length,words]`, sorted in ascending order of length. Two alternative solutions of the same length, `lᵒlᵍ{hl}ᶻ` and `lᵍ{hl}ᶻtᵒ`, output pairs reversed. [Answer] # [Haskell](https://www.haskell.org/), ~~59~~ 56 bytes ``` l=length f s=[(n,[x|x<-s,l x==n])|n<-[1..maximum$l<$>s]] ``` [Try it online!](https://tio.run/##FY3NasMwEITveQqh5pCAY2qEb1YJFFooGHIXpohEjtWs1kY/QQl5d3d1mZlvYXYmHW4GYHXaIpPM6aX/ZbvFW4ysZuOeqQ1T/HO@GF7x7xlGMo0XUrpZvJYwaQCDVxMIehM1H6pS6h/Ed@GLiXwWTSMwUnbvcRKewl9qC7fC30X5mFoStCjIFvt8Hgu//aQQ7dl8zf4EKc58GFaQZS9Om5EFqXZYqfzK3SFUwLKUOOxf2B1UU9dOZ@uS20K3/QhUXP8B "Haskell – Try It Online") * -3 bytes by using a list comprehension instead of a lambda, thanks to [79037662](https://codegolf.stackexchange.com/questions/195807/sort-and-table-a-sentence-by-word-lengths/195892?noredirect=1#comment466596_195892) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 9 bytes ``` m+lhdd.gl ``` [Try it online!](https://tio.run/##K6gsyfj/P1c7JyMlRS895/9/DSXn/JRUJR0l9/ycNCCVmJcCJIFimXnpIEZGYk5Oal56ajGQ45takqikCQA "Pyth – Try It Online") Port of [@Shaggy](https://codegolf.stackexchange.com/a/195808/90146)'s answer, so I cant really take credit for this (lol) # [Pyth](https://github.com/isaacg1/pyth), 14 bytes ``` m+dfqdlTQSleol ``` [Try it online!](https://tio.run/##K6gsyfj/P1c7Ja0wJSckMDgnNT/n/38NJef8lFQlHSX3/Jw0IJWYlwIkgWKZeekgRkZiTk5qXnpqMZDjm1qSqKQJAA "Pyth – Try It Online") Saves a few bytes by mapping a filtered list to each number in a 1-indexed range. This only saves 2 bytes due to the fact that the last two bytes can be implicit (would be `m+dfqdlTQSleolNQ` otherwise) ## How it works ``` m+dfqdlTQSleol m - Map +d - The sum of the element and... fqdlTQ - The filtered input where each element of the input is length d Sl - To the range [1, length] eol - of the last element of the ordered list by key=length - Print implicitly ``` # [Pyth](https://github.com/isaacg1/pyth), 16 bytes ``` FkSleolNQkfqklTQ ``` [Try it online!](https://tio.run/##K6gsyfj/3y07OCc1P8cvMDutMDsnJPD/fw0l5/yUVCUdJff8nDQglZiXAiSBYpl56SBGRmJOTmpeemoxkOObWpKopAkA "Pyth – Try It Online") 16 bytes seems a bit high for a challenge like this but oh well. Would be 14 bytes but it looks like the last 2 bytes cant be implicit due to how filter works in pyth ## How it works ``` FkSleolNQkfqklTQ Fk - For k in... Sl - The range [1, length] eolN - Of the last element of the sorted list by key=length Q - Of the input k - Print k fqklT - Filter by key k == length... Q - The input (prints implicitly) ``` Sorry if this answer is too long, I can cut it a bit if needed [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 8 bytes ``` ẈẈḢ,Ɗƙ⁸Ṣ ``` [Try it online!](https://tio.run/##y0rNyan8///hrg4Q2rFI51jXsZmPGnc83Lno/@H2o5Me7pzx/7@Sc35KqpKOknt@ThqQSsxLAZJAscy8dBAjIzEnJzUvPbUYyPFNLUlUAgA "Jelly – Try It Online") A monadic link which takes a list of Jelly strings and returns a list of lists where the first member of each list is the length and the second is a list of Jelly strings of that length. Plus 2 bytes now it’s been clarified that ordering of the list is mandatory. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~63~~ 53 bytes ``` $a=@{};$args|%{$a[$_.length]+=" $_"};$a|% *or|sort N* ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyXR1qG61lolsSi9uEa1WiUxWiVeLyc1L70kI1bbVklBJV4JJFujqqCVX1RTnF9UouCn9f//f3Xn/JRU9f/q7vk5aUAqMS9FHSyWmZcOYmQk5oAMSS0GcnxTSxLVAQ "PowerShell – Try It Online") *(-10 bytes thanks to mazzy)* Takes arguments via [splatting](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting?view=powershell-6), which on TIO manifests as separate command-line arguments. We first construct an empty hashtable `$a`, then loop through the input arguments. Each item is tacked onto `$a` in the appropriate `$_.length` slot. Then comes the lengthy `.GetEnumerator()` followed by a `sort` to get the hashtable to print out in order. That's left on the pipeline and output is implicit. [Answer] # [Japt](https://github.com/ETHproductions/japt), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` üÊ®uZÎl ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=/MqudVrObA&input=WyJDb2RlIiwiR29sZiIsImFuZCIsIkNvZGluZyIsIkNoYWxsZW5nZXMiLCJNZXRhIl0KLVE) ``` üÊ®uZÎl // input as array of words üÊ // group by length ® // for each group uZÎl // append length of 1st word ``` [Answer] # [Perl 5](https://www.perl.org/) (`-040n`), ~~45~~, ~~40~~, 34 bytes -5 bytes thanks to Xcali ``` $a[y///c].=" $_"}{say$b++,$_ for@a ``` [Try it online!](https://tio.run/##K0gtyjH9/18lMbpSX18/OVbPVklBJV6ptro4sVIlSVtbRyVeIS2/yCHx/3/n/JRUBff8nDSFxLwUBSAvMy9dwTkjMScnNS89tVjBN7Uk8V9@QUlmfl7xf10DE4O8nP@6vqZ6BoYA "Perl 5 – Try It Online") [Answer] # [PHP](https://php.net/), 62 bytes ``` for(;$w=$argv[++$i];ksort($a))$a[strlen($w)][]=$w;print_r($a); ``` [Try it online!](https://tio.run/##FYtBCoAgEAA/swelJ1h08NCpF4jEQqaSqKySz9/qMjAMU0Plea0fr0JCwVgAyT9mmiBadbdCXQBKCWhap@SygCGtsQsMVSnmftDfFTPrcjreSroY8/lbzJ51wPRd3jXeXccX "PHP – Try It Online") [Answer] # [J](http://jsoftware.com/), 22 bytes -2 bytes thaks to FrownyFrog If the output can be a table with some empty boxes: ``` [:/:~#@>(,~#&.>@{.)/.] ``` [Try it online!](https://tio.run/##VctNC4IwAIfxu5/iT0JLsKkML0IiCAaREF2jg@h8w7bQTdLAr25eOzyH3@Fp1x0lJU4BCGy4CLaOFPH9mqyPwAkWMwoP9mLuaRh9qeXQ52oZMHheS5TItQKJZcFxll2JTBTY1IgKcZ11HRcVH5BylZG/I50wsn4C@@TM85hQeLmqZj1a7Sv4rB9ZAe1DNILh3cxz5MO86EE1OU9kf@u0kmT9AQ "J – Try It Online") # [J](http://jsoftware.com/), 24 bytes ``` /:~@(#@><@(#@>@{.;])/.]) ``` [Try it online!](https://tio.run/##VYvNCoJAAAbvPsVHHjah/GHxYj8IgkEkRPcOsq66Yruhu5IGvbpJtw4zMIdp5pVLShwiEGzgI1rYukhul3T2ok@8tuPj/uf47e7ujufendmxYHFWK5RgRoMkquA4qbZELgssJWSFpM7blsuK98i4zsnfkY0YaDeCvhgNAio1Hr6uaYfGhBoh7QZawISQQlI8xTTFIeyz6bVgPFXdtTVakfkL "J – Try It Online") Just made it work - no doubt it can be golfed further. [Answer] # RPL, 60+10 bytes Let's explore more creative output formats: ``` DUP«SIZE»DOLIST SWAP 2«STR→ X ROT ^ *»DOLIST ΣLIST EXPANDMOD ``` turns the list {"Code" "Golf" "and" "Coding" "Challenges" "Meta"} into the polynomial Challenges·X10+Coding·X6+(Code+Golf+Meta)·X4+and·X3 thanks to EXPANDMOD. Sadly to allow exotic names like pizz@5 – just for you to know, `@` introduces comments – `STR→` must be replaced by `#5B15h SYSEVAL` adding 10 bytes to the source code, and obfuscating the call. That does however allow printable and even non printable chars, the latters only displayed as black squares but not lost. So the garbage resistant code is ``` DUP«SIZE»DOLIST SWAP 2«#5B15h SYSEVAL X ROT ^ *»DOLIST ΣLIST EXPANDMOD ``` (EXPANDMOD is present in HP50g at least. Tested with [Emu48](https://play.google.com/store/apps/details?id=org.emulator.forty.eight) in 50g mode. The code page is documented [here](https://en.wikipedia.org/wiki/RPL_character_set#Code_page_layout)). [Answer] # SimpleTemplate, 136 bytes Yeah, it's a long one... The order of the output is what made it longer :/ ``` {@setM 0}{@eachargv.0}{@callstrlen intoR _}{@setL.[R]L.[R],_}{@ifM is lowerR}{@setM R}{@/}{@/}{@forfrom 1toM}{@echo_}.{@echojl" " L.[_]} ``` Incredibly, it is easier (and shorter) to output that to return. You can try it on <http://sandbox.onlinephpfunctions.com/code/ec4bf4b3efa93c63c6c5c9f1458330da0178b6cd> (Line 974 has the words, line 976 has the golfed/ungolfed version variable) --- **Ungolfed**: ``` {@set results} {@set max 0} {@each argv.0 as word} {@call strlen into length word} {@set results.[length] results.[length], word} {@if max is lower than length} {@set max length} {@/} {@/} {@for i from 1 to length} {@echo i}.{@echo separator " " results.[i], "\n"} {@/} ``` Most of it should be easy to understand. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 30 bytes ``` KeySort@*GroupBy[StringLength] ``` [Try it online!](https://tio.run/##RU@9CsIwEN59CombOFhCR6EoWFALhY6lQ2hTE0mTkl6KrfjsMZfF5b6f@/m4gYHgAwPZMt@f/J0vlbGQ7XNr3Hhe6gqs1M8H108QjS@DgLqvP@RiOk4OW5Ib1SMy3SEEO4xHJphSYY1PqAoOjHybZvO/UCzYmKmNSN8tTRKqAcVwBEEtspdLo5NSO9OY4FKsWmqKOMp1zaKzu7kpfMGvxpbKgcE0/wM "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Scala](https://www.scala-lang.org/), 30 42 bytes Correction thanks to Value Ink ``` (s:String)=>s.split(" ").groupBy(_.length) ``` [Try it online!](https://scastie.scala-lang.org/buVNQluwRumhzpeCJ1K5Qw) [Answer] # JavaScript (ES6), 53 bytes Takes input as a list of words. Returns an object whose keys are the lengths and whose values are the lists of corresponding words. ``` a=>a.map(w=>(o[n=w.length]=o[n]||[]).push(w),o={})&&o ``` [Try it online!](https://tio.run/##Fcw9DsIgFADgqxCGhpcoN6BLBydP0DC8tPwZ5BGhMljPjjh@y/fAN5btFXK9JtpNt6qjmlE@MYumZkFrUk1Gk1z1Wg3p81w1yHwULxpcSH2@ME3UN0qFopGRnLCCLyNjN4qWYdrZUEiOLR7jvzKF3U1FLkuOoQrOOAD0Hw "JavaScript (Node.js) – Try It Online") [Answer] # [Red](http://www.red-lang.org), 107 bytes ``` func[a][m: copy#()foreach w sort a[k: length? w unless m/:k[put m k copy[]]append m/:k w]sort/skip to[]m 2] ``` [Try it online!](https://tio.run/##NY5PS8QwEMXv/RSP7kVP6xp66UVBUBAE8RpyiMl0G5smIX@2dr98TRe8zJt5w@/NRNLbF2kumqHfhuIUl4LPPZQP6@HufvCRpBqxIPmYIfnUw5I75/EJS1OcpZQwH/uJh5IxY7qBXAgZAjl9W2ERO3xMkwnInosZj2IL0X8TBvD2xWtq0b55O1SRTtdaPePOezNKux@kVIcPyrIVzT@agjW5uisuLK5gv4qdTszVPx7yyCJ@SpfRsXhhGqWDM44hmOv1ucPhvaRsFL36@GlL9m0Nk4q2Pw "Red – Try It Online") [Answer] [JULIA](https://julialang.org) Some 55 bytes: ``` H(l,L=length.(l))=sort([(v,l[L.==v]) for v in Set(L)]) ``` [Try](https://tio.run/##PU49a8MwEN31Kw5liAQi1AiPgkKhDcGBQkfjQcRKrKCejHwSSf68Ky9d3he8u3fPwdvmsa5HEVRngsMbTQcRpDRLTCR6UVTou4MxZZBwjQkKeIQfR6KTg2SMjZas6RlAzz/i6LjiXzFcK1kcK9bM420Tkw3bebdUc3Zk@aBqa5mDJ8HPTyg6PUE/LrppNBL8vtGkE9xzS9DqVPQIuQX0qGH2r9d7C7tTXshf3GdM3yFT5GoPe8kGxv53buPqkzl5pIDiKIqUzOG4rn8) it online ]
[Question] [ # Input A string that contains at most one of each of the letters `A`, `B`, and `C`. They may be in any order. The empty string is valid input. **Note:** A previous version of this challenge used the letters `LEJ` instead of `ABC` and they may still be used if desired. # Output A string of the `A`, `B`, `C` letters that were not present in the input. They may be in any order. If the output would be the empty string then simply giving no output is valid, if that makes sense for your implementation. (e.g. you don't need to actually call `print` on an empty string.) # Examples * If the input is `B` then the output should either be `CA` or `AC` since `A` and `C` are not present in the input. * If the input is the empty string then the output should be `ABC` or any permutation since none of the three letters are present in the input. * If the input is `CAB` then the output should be the empty string because all three letters are present in the input. # Test Cases There are so few input cases that we can enumerate all of them: ``` in -> out1 | out2 | out3 | ... ABC -> "" ACB -> "" BCA -> "" BAC -> "" CAB -> "" CBA -> "" AB -> C AC -> B BC -> A BA -> C CA -> B CB -> A A -> BC | CB B -> CA | AC C -> AB | BA "" -> ABC | ACB | BCA | BAC | CAB | CBA ``` All valid outputs for each input are given, separated by `|`'s. `""` represents the empty string # Scoring The shortest code in bytes wins. But keep in mind that you may get more recognition for solving the challenge in a [unique](https://esolangs.org/wiki/Language_list) way rather than in a short way ;) [Answer] # Python 3, ~~29~~ ~~27~~ 22 bytes ``` lambda x:{*"ABC"}-{*x} ``` -2 bytes thanks to Jonathan Allan -5 bytes thanks to Rod [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes Thanks to @DuctrTape for the prod about the change and the presence of "ABC" in Jelly's dictionary. ``` “ḃ»ḟ ``` **[Try it online!](https://tio.run/nexus/jelly#@/@oYc7DHc2Hdj/cMf9/uHU0kKtr96hhbqz14fZwFa7D7Y@a1rj//x@t7ujkrK6j7ujsBCSdnB1BpCNIxNkRJOLsBBIBM8GiYMVgMbBSsC6wHhAHiNVjAQ)** `“ḃ»` looks up the entry "ABC" in Jelly's dictionary, `ḟ` is the filer discard dyad which discards the characters found in the input from that list of characters. The result is implicitly printed. --- For a lower case version the dictionary entry to use can be either of "abac" (`“c»`) or "abaca" (`“i»`). --- When the challenge was "LEJ" only **6** bytes could be achieved in the upper case variant, since no dictionary entries exist with that set of characters, leaving us to create the list of characters `“LEJ”` (or a permutation thereof). The lowercase variant faired better at **5** bytes due to the presence of the word "jell" (`“ẎṄ»`). [Answer] # [Bash](https://www.gnu.org/software/bash/) + coreutils, 15 bytes ``` tr -d x$1<<<LEJ ``` [Try it online!](https://tio.run/nexus/bash#@19SpKCbolChYmhjY@Pj6vX//38vVwA "Bash – TIO Nexus") I'd like to omit the `x`, but then `tr -d` would be missing an argument when the input string was empty. (The `x` doesn't do any harm, since there aren't any x's in the here-string LEJ.) I'd normally write `tr -d "$1"`, but doing it the way I did is one byte shorter than that. [Answer] # [Retina](https://github.com/m-ender/retina), 14 bytes Byte count assumes ISO 8859-1 encoding. ``` $ ¶ABC D`. A1` ``` [Try it online!](https://tio.run/nexus/retina#FYrBDcAwEML@zJFKeUXqCEClrnFTdoAudiEvbJlrvtUD/0cZTy3wru4jtCATomEKFpGJJYaT8kiHsQE "Retina – TIO Nexus") ### Explanation ``` $ ¶ABC ``` Append a second line containing `ABC`. ``` D`. ``` Deduplicate the characters. This deletes every character from the second line which already appears in the first line. ``` A1` ``` Discard the first line. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~6~~ 4 bytes Saved 2 bytes using the new `žR` command as suggested by *Kevin Cruijssen* ``` žRsм ``` [Try it online!](https://tio.run/##yy9OTMpM/f//6L6g4gt7/v93cgYA "05AB1E – Try It Online") or as a [Test Suite](https://tio.run/##yy9OTMpM/X90X9DhZY@a1hydfHrO4ZVllS72SgqP2iYpKNmDpIov7Pmv8x8A) **Explanation** ``` м # remove the character of s # the input žR # from the string "ABC" ``` [Answer] # Java 7, ~~73~~ 58 bytes ``` String c(String s){return"EJL".replaceAll("[ "+s+"]","");} ``` 15 bytes saved thanks to *@KritixiLithos*. **Test code:** [Try it here.](https://ideone.com/bHBU8m) ``` class M{ static String c(String s){return"EJL".replaceAll("[ "+s+"]","");} public static void main(final String[] a) { System.out.print("LEJ=" + c("LEJ") + "; "); System.out.print("LJE=" + c("LJE") + "; "); System.out.print("EJL=" + c("EJL") + "; "); System.out.print("ELJ=" + c("ELJ") + "; "); System.out.print("JLE=" + c("JLE") + "; "); System.out.print("JEL=" + c("JEL") + "; "); System.out.print("LE=" + c("LE") + "; "); System.out.print("LJ=" + c("LJ") + "; "); System.out.print("EJ=" + c("EJ") + "; "); System.out.print("EL=" + c("EL") + "; "); System.out.print("JL=" + c("JL") + "; "); System.out.print("JE=" + c("JE") + "; "); System.out.print("L=" + c("L") + "; "); System.out.print("E=" + c("E") + "; "); System.out.print("J=" + c("J") + "; "); System.out.print("\"\"=" + c("")); } } ``` **Output:** ``` LEJ=; LJE=; EJL=; ELJ=; JLE=; JEL=; LE=J; LJ=E; EJ=L; EL=J; JL=E; JE=L; L=EJ; E=JL; J=EL; ""=EJL ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 7 bytes ``` "LEJ"-Σ ``` [Try it online!](https://tio.run/nexus/actually#@6/k4@qlpHtu8f//Sj5OSgA "Actually – TIO Nexus") ``` "LEJ"-Σ "LEJ" the letters - exclude letters present in input Σ concatenate ``` [Answer] # Pyth, 5 bytes ``` -"ABC ``` [Test it here](http://pyth.herokuapp.com/?code=-%22ABC&input=%22ab%22&test_suite=1&test_suite_input=%27ABC%27%0A%27ACB%27%0A%27BCA%27%0A%27BAC%27%0A%27CAB%27%0A%27CBA%27%0A%27AB%27%0A%27AC%27%0A%27BC%27%0A%27BA%27%0A%27CA%27%0A%27CB%27%0A%27A%27%0A%27B%27%0A%27C%27%0A%27%27&debug=0) Expands to ``` -"ABC"Q - # Filter on absence "ABC" # Literal string Q # Input ``` [Answer] # MATL, ~~10~~ 8 bytes Saved two bytes thanks to Suever. `setdiff` is shorter than `ismember`. ``` 'ABC'iX- ``` [**Try it here!**](https://matl.suever.net/?code=%27ABC%27iX-&inputs=%27BA%27&version=19.7.4) **Explanation** ``` 'ABC' % Create a string literal i % User input X- % Set difference, between two elements of the stack ``` Yes, this might have been a trivial task, but I'm quite satisfied I managed to solve it with MATL all by myself. I never said it was the shortest solution... Thanks Suever! [Answer] # JavaScript ES6, 41 39 38 Bytes ``` s=>eval(`'ABC'.replace(/[${s}]/g,'')`) ``` Saved 2 bytes thanks to Arnauld. Saved 1 bytes thanks to LarsW. ``` f=s=>eval(`'ABC'.replace(/[${s}]/g,'')`) console.log(f("AB")); ``` [Answer] # [V](https://github.com/DJMcMayhem/V), 10 bytes ``` CLEJ<ESC>Ó[<C-r>"] ``` [Try it online!](https://tio.run/nexus/v#@@/s4@olfXhytJBS7P//rj4A "V – TIO Nexus") Hexdump: ``` 00000000: 434c 454a 1bd3 5b12 225d CLEJ..[."] ``` ### Explanation Input is on the first line of the buffer. So something like: ``` EL ``` and the cursor is on the first character. So we delete the input (which stores it in register `"`) and enter insert mode simultaneously using `C`. Once in insert mode, the characters `LEJ` are inserted, after which I return to normal mode using `<ESC>`. Now we have to remove all the characters that are present in the input. ``` Ó " remove every [<C-r>"] " character that appears in the input " synonym of Vim's :s/[<C-r>"]//g ``` And once this happens, we are left with the remaining letters in the buffer. [Answer] ## Ruby, ~~27 19~~ 18 bytes ``` ->s{"ABC".tr s,""} ``` -1 byte thanks to Martin Ender [Answer] # [Haskell](https://www.haskell.org/), ~~27~~ 26 bytes ``` import Data.List ("ABC"\\) ``` [Try it online!](https://tio.run/nexus/haskell#@5@ZW5BfVKLgkliSqOeTWVzyPzcxM0/BViEzryS1KDG5REFDydHJWSkmRvO/kyMA "Haskell – TIO Nexus") Usage: `("ABC"\\) "CB"` yields `"A"`. `\\` is the set difference operator, the parenthesis form a so called *section* which is a short form for the lamda `(\x -> "ABC" \\ x)`. --- **Without import:** (same byte count thanks to @nimi) ``` f x=[c|c<-"ABC",all(/=c)x] ``` [Try it online!](https://tio.run/nexus/haskell#@5@mUGEbnVyTbKOr5OjkrKSTmJOjoW@brFkR@z83MTNPwVYhM68ktSgxuUQh7b@TIwA "Haskell – TIO Nexus") Usage: `f "CB"` yields `"A"`. --- Other approaches: ``` f x=filter(`notElem`x)"ABC" (`filter`"ABC").flip notElem f x=[c|c<-"ABC",notElem c x] ``` [Answer] # [GNU sed](https://www.gnu.org/software/sed/), ~~34~~ 29 bytes Includes +1 for `-r` -5 thanks to [Digital Trauma](https://codegolf.stackexchange.com/users/11259/digital-trauma) ``` s/^/ABC/ : s/(.)(.*)\1/\2/ t ``` [Try it online!](https://tio.run/nexus/bash#DckxDoAgEATAfl9BB5jIRUu7u/0GodIPiP/HbWfmc6f9TXlNG@ZBw4VppdXSttoP66fhW3lBB2cg6Agn6AGGy8VSoUwEPfgD "Bash – TIO Nexus") For some reason TIO doesn't work with extended regex (`-r`), so I had to wrap it in BASH. --- ``` s/^/ABC/ # put ABC at the beginning of the string : # nameless label s/(.)(.*)\1/\2/ # remove a duplicate letter t # branch to the nameless label if something changed ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 120 + 3 = 123 bytes ``` <>((((((((()()){}){}){}){}){}())())())<>{({}(<()>)){(([({})]<>({}))){(<({}<>{})<>([{}]{}<>)>)}{}}{}{}<>{}{({}<>)<>}{}}<> ``` It is run with the `-c` flag, adding 3 bytes [Try it online!](https://tio.run/nexus/brain-flak#TYvRCcAwCETXOT@6gQidI@SrY4iz25eEQuVA73zXHvrGZJb1F8GRRwrrsoCRBs4mXdYKnAOmADWy5nKglYXOKzcCsEKP7ruv5wU "Brain-Flak – TIO Nexus") ## Explanation Overall this program pretty much does the right stack set minus the left stack with the right stack initialized to `CBA` and the left stack initialized to the input. ### Annotated Code ``` <>((((((((()()){}){}){}){}){}())())())<> # Switch to right stack, push CBA, switch back {({}(<()>)){(([({})]<>({}))){(<({}<>{})<>([{}]{}<>)>)}{}}{}{}<>{}{({}<>)<>}{}}<> ``` *More explanation to come...* [Answer] ## Mathematica, 37 bytes ``` Complement@@Characters@{"ABC",#}<>""& ``` [Answer] ## [CJam](https://sourceforge.net/p/cjam), 7 bytes ``` "ABC"l- ``` [Try it online!](https://tio.run/nexus/cjam#K/TTr7bysf6v5OjkrOSj@z82r1b/P5cjl7Mjl5OjMwA "CJam – TIO Nexus") (As a linefeed-separated test suite.) [Answer] # MATLAB / Octave, 20 bytes ``` @(x)setdiff('ABC',x) ``` [Online Demo](http://ideone.com/6S3TMi) [Answer] # Octave, ~~29~~ 27 bytes Saved two bytes thanks to Suever, by creating the string `'ABC'`, inside the `ismember` call. ``` @(s)x(~ismember(x='ABC',s)) ``` We use `~ismember()` as logical indices to the variable `x`. The peculiar thing is, we create `x='ABC'` *inside* `ismember`, not in front of it. The order Octave sees this: ``` @(s) % Anonymous function that takes a string s as input x='ABC' % Create a variable x with the characters 'ABC' ismember(x='ABC',s) % True for elements that are in both x and s. False otherwise. ~ismember(x='ABC',s) % Negate this, so that we keep the characters that aren't in s @(s)x(~ismember(x='ABC',s)) % Use the logical vector as indices to x and return the result ``` [Answer] # C#, 50 Bytes 32 Bytes 47 Bytes 35 Bytes where `i` is the input: ``` i=>string.Join("","ABC".Except(i)); ``` **Full app tested in LINQPad** ``` void Main() { var testcases = new Dictionary<string,string[]> { ["ABC"] = new[]{""}, ["ACB"] = new[]{""}, ["BCA"] = new[]{""}, ["BAC"] = new[]{""}, ["CAB"] = new[]{""}, ["CBA"] = new[]{""}, ["AB"] = new[]{"C"}, ["AC"] = new[]{"B"}, ["BC"] = new[]{"A"}, ["BA"] = new[]{"C"}, ["CA"] = new[]{"B"}, ["CB"] = new[]{"A"}, ["A"] = new[]{"BC","CB"}, ["B"] = new[]{"CA","AC"}, ["C"] = new[]{"AB","BA"}, [""] = new[]{"ABC","ACB","BCA","BAC","CAB","CBA"}, }; var output = ""; foreach(var input in testcases.Keys) { var expect = testcases[input]; var actual = GetResult(input); if(!expect.Contains(actual)) throw new ApplicationException($"{input}:{string.Join(",",expect)}:{actual}"); output+=$"{input} -> {actual}\n"; } output.Dump(); } // Define other methods and classes here private string GetResult(string input){ return string.Join("","ABC".Except(i)); } ``` **Test results** > > ABC -> > > ACB -> > > BCA -> > > BAC -> > > CAB -> > > CBA -> > > AB -> C > > AC -> B > > BC -> A > > BA -> C > > CA -> B > > CB -> A > > A -> BC > > B -> AC > > C -> AB > > -> ABC > > > [Answer] # [Carrot](https://github.com/kritixilithos/Carrot), 15 bytes *I found a bug with returning matches and empty strings. So I just fixed it* ``` ABC^//[^#]/gS"" ``` [Try it online!](http://kritixilithos.github.io/Carrot/) (copy & paste) ### Explanation ``` ABC^ //sets stack (just a string, not an array) to "ABC" / //return match(es) of: /[^#]/g // `#` is the placeholder for the input // so effectively, this returns the matches of any character not present in the input // applied on the stack //this returns an array of all the matches of the regex S"" //join all the elements of the array using "", the empty string ``` [Answer] # APL, 7 bytes ``` 'ABC'∘~ ``` `~` is set subtraction, `∘` is compose, so this is a function that returns `ABC` minus the characters in its input. [Answer] ## [Jellyfish](https://github.com/iatorm/jellyfish), 9 bytes ``` PNI "ABC ``` [Try it online!](https://tio.run/nexus/jellyfish#@x/g58mloOTo5Pz/v6MTAA "Jellyfish – TIO Nexus") In more conventional notation, this program translates to: ``` P(N("ABC", I)) ``` `I` is the input, `N` is list difference, and `P` is output. [Answer] # Perl 5.9.9 ~~79 38 37~~ 35 bytes ``` perl -le '$_="ABC";eval"y/$ARGV[0]//d";print' ``` (not sure of the counting rules here - have included switches but not the perl command). ``` > perl -le '$_="ABC";eval"y/$ARGV[0]//d";print' AB C > perl -le '$_="ABC";eval"y/$ARGV[0]//d";print' ABC ``` (adjusted counts after adjudication comment below) [Answer] ## Common Lisp, 71 bytes The largest entry at the moment, but at least it is readable ;-) ``` (lambda(s)(coerce(set-difference'(#\A #\B #\C)(coerce s'list))'string)) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 13 12 bytes ``` "ABC"r"[{U}] ``` Saved a byte thanks to ETHproductions. [Try it online!](https://tio.run/nexus/japt#@6/k6OSsVKQUXR1aG/v/v5KjEgA "Japt – TIO Nexus") [Answer] ## Pyth, 4 bytes ``` -<G3 ``` [Try it here!](http://pyth.herokuapp.com/?code=-%3CG3&input=%22a%22&debug=0) ``` <G3 - alphabet[:3] - - input-^ ``` Note this uses lower case which might not be acceptable [Answer] # C, 53 bytes ``` b=64;c(char*a){while(b<67)putchar(++b*!strchr(a,b));} ``` If implicit declarations of string.h are not allowed, **72 bytes**, to add `#include<string.h>` [Try it online!](https://tio.run/nexus/c-gcc#U87MS84pTUm1KS4pysxL18uw@59ka2ZinayRnJFYpJWoWV2ekZmTqpFkY2auWVBaAhLV0NZO0lIEakjOKNJI1EnS1LSu/Z@ZV6KQm5iZpwFiVOkogLVrVWoqVHMpKCgkayg5Kmlac9X@BwA) --- or something a bit more fun at **75 bytes** ``` a[128]={};b=64;c(char*d){while(*d)++a[*d++];while(b<67)putchar(b*!a[++b]);} ``` [Try it online!](https://tio.run/nexus/c-gcc#@58YbWhkEWtbXWudZGtmYp2skZyRWKSVolldnpGZk6oBZGlrJ0ZrpWhrx1pDhJJszMw1C0pLQAo1krQUE6O1tZNiNa1r/2fmlSjkJmbmaYAYVToKYKO0KjUVqrkUFBSSNZQcnZU0rblq/wMA) [Answer] ## Batch, 101 bytes ``` @set/ps= @for %%c in (L E J)do @call set d=%%s:%%c=%%&call:c %%c :c @if "%d%"=="%s%" set/pd=%1<nul ``` Takes input on STDIN, which means that `%1` is empty when the code falls through into the helper subroutine and nothing gets printed. [Answer] # [R](https://www.r-project.org/), ~~47~~ 40 bytes ``` gsub(paste0("[",scan(,""),"]"),"","ABC") ``` [Try it online!](https://tio.run/##K/r/P724NEmjILG4JNVAQylaSac4OTFPQ0dJSVNHKRZEKOkoOTo5K2n@V3d0Vv8PAA "R – Try It Online") Replaces any letters in the input string with the empty string. ]
[Question] [ Your task is pretty simple, calculate the n-th element of [A190810](https://oeis.org/A190810). Elements of A190810 are calculated according to these rules: 1. The first element is 1 2. The sequence is increasing 3. If `x` occurs in the sequence, then `2x+1` and `3x-1` also do You can use 1-based or 0-based indexing, but if you use 0-based indexing, please say it in the answer. Test cases ``` a(1) = 1 a(2) = 2 a(3) = 3 a(4) = 5 a(5) = 7 a(10) = 17 a(20) = 50 a(30) = 95 a(55) = 255 ``` Since this is code-golf, the shortest answer in bytes wins! [Answer] # Python 2, ~~88~~ ~~83~~ 72 bytes You may want to read the programs in this answer in reverse order... Slower and shorter still, thanks to Dennis: ``` L=1,;exec'L+=2*L[0]+1,3*L[0]-1;L=sorted(set(L))[1:];'*input() print L[0] ``` [**Try it online**](http://ideone.com/wPYat6) --- This doesn't run as fast, but is shorter (**83 bytes**.) By sorting and removing duplicates each iteration, as well as removing the first element, I remove the need for an index into the list. The result is simply the first element after `n` iterations. I may have out-golfed Dennis. :D ``` L=[1] n=input() while n:L+=[2*L[0]+1,3*L[0]-1];n-=1;L=sorted(set(L))[1:] print L[0] ``` [**Try it online**](http://ideone.com/FI4XPA) --- This version below (**88 bytes**) runs really fast, finding the 500000th element in about two seconds. It's pretty simple. Compute elements of the list until there are three times more elements than `n`, since every element added may add at most 2 more unique elements. Then remove duplicates, sort, and print the `n`th element (zero-indexed.) ``` L=[1] i=0 n=input() while len(L)<3*n:L+=[2*L[i]+1,3*L[i]-1];i+=1 print sorted(set(L))[n] ``` [**Try it online**](http://ideone.com/DdAPnZ) [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ×3’;Ḥ‘$; 1Ç¡ṢQ³ị ``` *Very* inefficient. [Try it online!](http://jelly.tryitonline.net/#code=w5cz4oCZO-G4pOKAmCQ7CjHDh8Kh4bmiUcKz4buL&input=&args=MTA) ### How it works ``` 1Ç¡ṢQ³ị Main link. Argument: n (integer) 1 Set the return value to 1. Ç¡ Execute the helper link n times. Ṣ Sort the resulting array. Q Unique; deduplicate the sorted array. ³ị Retrieve its n-th element. ×3’;Ḥ‘$; Helper link. Argument: A (array) ×3 Multiply all elements of A by 3. ’ Decrement the resulting products. $ Combine the two links to the left into a monadic chain. Ḥ Unhalve; multiply all elements of A by 2. ‘ Increment the resulting products. ; Concatenate 3A-1 and 2A+1. ; Concatenate the result with A. ``` [Answer] # Python 2, 59 bytes ``` t={1} exec'm=min(t);t=t-{m}|{2*m+1,3*m-1};'*input() print m ``` Based on [@mbomb007's Python answer](https://codegolf.stackexchange.com/a/85414). Test it on [Ideone](http://ideone.com/9Vi8Mq). [Answer] ## Haskell, ~~76~~ ~~73~~ 69 bytes ``` a#b=mod a b<1&&t(div a b) t x=x<2||(x-1)#2||(x+1)#3 (filter t[1..]!!) ``` Uses a 0-based index. Usage example: `(filter t[1..]!!) 54` -> `255`. Instead of building the list by repeatedly inserting `2x+1` and `3x-1` as seen in most other answers, I go through all integers and check if they can reduced to `1` by repeatedly applying `(x-1) / 2` or `(x+1) / 3` if divisible. [Answer] # Haskell, ~~77~~ 74 bytes ``` import Data.List i=insert f(x:y)=x:f(i(2*x+1)$i(3*x-1)y) a=(!!)(nub$f[1]) ``` This provides a function `a` for the n-th entry. It's zero indexed. Alternatively, `a=nub$f[1]` will create the whole list (lazily). It's a list-variant of Reinhard Zumkeller's `Set` code. [Answer] # Python 2, ~~88~~ 84 bytes ``` g=lambda k:g(k%2*k/2)|g(k%3/2*-~k/3)if k>1else k f=lambda n,k=1:n and-~f(n-g(k),k+1) ``` Test it on [Ideone](http://ideone.com/6tPaoZ). [Answer] # Pyth, ~~20~~ 19 bytes ``` hutS{+G,hyhGt*3hGQ0 ``` [Try it online.](http://pyth.herokuapp.com/?code=hutS%7B%2BG%2ChyhGt%2a3hGQ0&input=54&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=hutS%7B%2BG%2ChyhGt%2a3hGQ0&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A9%0A19%0A29%0A54&debug=0) Uses zero-based indexing. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 45 bytes ``` :1-I,?:?*:1ydo:Im. 1.|:1-:1&I(:3*:1-.;I*:1+.) ``` Computes `N = 1000` in about 6 seconds on my machine. This is 1-indexed, e.g. ``` run_from_file('code.brachylog',1000,Z). Z = 13961 . ``` ### Explanation * Main predicate: ``` :1-I, I = Input - 1 ?:?* Square the Input :1y Find the first Input*Input valid outputs of predicate 1 do Remove duplicates and order :Im. Output is the Ith element ``` * Predicate 1: ``` 1. Input = Output = 1 | Or :1-:1&I I is the output of predicate 1 called with Input - 1 as input ( :3*:1-. Output is 3*I-1 ; Or I*:1+. Output is 2*I+1 ) ``` You may note that we don't pass any input to predicate 1 when we call `y - Yield`. Because of constraint propagation, it will find the right input once reaching the `1.` clause which will propagate the correct input values. [Answer] ## 05AB1E, ~~18~~ 17 bytes Uses [CP-1252](http://www.cp1252.com) encoding. ``` $Fз>s3*<)˜Ù}ï{¹è ``` **Explanation** ``` $ # initialize with 1 F } # input number of times do Ð # triplicate current list/number ·> # double one copy and add 1 s3*< # multiply one copy by 3 and subtract 1 )˜Ù # combine the 3 lists to 1 list and remove duplicates ï{ # convert list to int and sort ¹è # take the element from the list at index input ``` [Try it online for small numbers](http://05ab1e.tryitonline.net/#code=JEbDkMK3PnMzKjwpy5zDmX3Dr3vCucOo&input=OQ) Very slow. Uses 0-based indexing. [Answer] ## JavaScript (ES6), 63 bytes ``` f=(n,a=[1],i=0)=>a[i++]?--n?f(n,a,a[i*2]=a[i*3-2]=1):i:f(n,a,i) ``` Probably gives up quickly due to the recursion. [Answer] # MATL, ~~19, 18~~ 17 bytes ``` 1w:"tEQy3*qvSu]G) ``` This is an *extremely* inefficient algorithm. The online interpreter runs out of memory for inputs greater than 13. *One byte saved, thanks to Luis Mendo!* [Try it online!](http://matl.tryitonline.net/#code=MXc6InRFUXkzKnF2U3VdRyk&input=MTA) This version is longer, but more efficient (21 bytes) ``` 1`tEQy3*qvSutnG3*<]G) ``` [Try it online](http://matl.tryitonline.net/#code=MWB0RVF5MypxdlN1dG5HMyo8XUcp&input=MjA) Explanation: The logical way to do it, is to add elements to the array until it is long enough to grab the i'th element. That's how the efficient one works. The *golfy* (and inefficient) way to do it, is to just increase the array size *i* times. So first, we define the start array: `1`. Then we swap the top two elements, so that input is on top. `w`. Now, we loop through the input with `:"`. So *i* times: ``` t %Duplicate our starting (or current) array. EQ %Double it and increment y %Push our starting array again 3*q %Multiply by 3 and decrement v %Concatenate these two arrays and the starting array Su %Sort them and remove all duplicate elements. ``` Now, we have a *gigantic* array of the sequence. (Way more than is needed to calculate) So we stop looping, `]`, and grab the i'th number from this array with `G)` (1-indexed) [Answer] ## Retina, 57 ``` ^.+ $*¶¶1 ¶¶(1(1*)) ¶1$1$1¶$2$1$1 O` }`(¶1+)\1\b $1 G2` 1 ``` [Try it online!](http://retina.tryitonline.net/#code=Xi4rCiQqwrbCtjEKwrbCtigxKDEqKSkKwrYxJDEkMcK2JDIkMSQxCk9gCn1gKMK2MSspXDFcYgokMQpHMmAKMQ&input=OQ) 0-indexed. Follows the frequently used algorithm: remove the minimum value from the current set, call it `x`, and add `2x+1` and `3x-1` to the set a number of times equal to the input, then the leading number is the result. The "set" in Retina is just a list that is repeatedly sorted and made to contain only unique elements. There are some sneaky bits added to the algorithm for golf, which I will explain once I've had some more time. Big thanks to Martin for golfing off around 20 bytes! [Answer] ## Clojure, 114 108 bytes ``` #(loop[a(sorted-set 1)n 1](let[x(first a)](if(= n %)x(recur(conj(disj a x)(+(* 2 x)1)(-(* 3 x)1))(inc n))))) ``` I wouldn't be surprised if this could be golfed/reduced by a significant amount but `set`'s not supporting nth really hurt my train of thought. [Try the online](http://ideone.com/yCxLlV) Version with spaces: ``` #(loop [a (sorted-set 1) n 1] (let [x (first a)] (if (= n %) x (recur (conj (disj a x) (+ (* 2 x) 1) (- (* 3 x) 1)) (inc n)) ))) ``` [Answer] # C++, 102 bytes ``` [](int i){int t;map<int,int>k;for(k[1];i--;k.erase(t))t=k.begin()->first,k[t*2+1],k[t*3-1];return t;}; ``` This lambda function requires `#include <map>` and `using std::map`. The `map` here is just a collection of keys; their values are ignored. I use `map` in order to benefit from the terse code for insertion: ``` k[1]; // inserts the key 1 into the map ``` Thanks to the sorted order of `map`, the smallest element is extracted by `k.begin()->first`. [Answer] ## Actually, 27 bytes ``` ╗1#╜`;;2*1+)3*1@-#++╔S`n╜@E ``` [Try it online!](http://actually.tryitonline.net/#code=4pWXMSPilZxgOzsyKjErKTMqMUAtIysr4pWUU2Bu4pWcQEU&input=NA) This program uses 0-based indexing. The approach is very brute-force, so don't expect it to work in the online interpreter for larger inputs. Explanation: ``` ╗1#╜`;;2*1+)3*1@-#++╔S`n╜@E ╗ save input (n) in register 0 1# push [1] ╜ push n `;;2*1+)3*1@-#++╔S`n do the following n times: ;; make two copies of the list 2*1+ apply 2x+1 to each element in one copy )3*1@- and 3x-1 to each element in the other copy # workaround for a weird list bug ++ append those two lists to the original list ╔S uniquify and sort ╜@E get the nth element (0-indexed) ``` [Answer] # Ruby, 70 bytes ``` ->n{a=*1 n.times{a<<a.map{|i|([2*i+1,3*i-1]-a).min||1.0/0}.min} a[-2]} ``` ## Explanation ``` ->n{ # Magical, golfy way of initializing an array. Equivalent to a = [1]. a=*1 n.times{ # Generate the next element in the sequence, by... a<< # ... finding the minimal term that will appear at some point. a.map{|i| ([2*i+1,3*i-1]-a).min||1.0/0 }.min } # We generated n+1 elements, so we'll take the *second* to last one. a[-2] } ``` [Answer] ## CJam (25 bytes) ``` ri1a1${{_2*)1$3*(}%_&}*$= ``` [Online demo](http://cjam.aditsu.net/#code=ri1a1%24%7B%7B_2*)1%243*(%7D%25_%26%7D*%24%3D&input=10). Note that this uses zero-based indexing. This uses a similar approach to most: apply the transforms `n` times and then sort and extract the `n`th item. As a nod to efficiency the deduplication is applied inside the loop and the sorting is applied outside the loop. [Answer] ## [Retina](https://github.com/m-ender/retina), 48 bytes ``` .+ $* +1`^(((!*)!(!|\3)(?=\3!1))*!)1|\b !$1 -2`. ``` [Try it online!](http://retina.tryitonline.net/#code=LisKJCoKKzFgXigoKCEqKSEoIXxcMykoPz1cMyExKSkqISkxfFxiCiEkMQotMmAu&input=MTA) Inspired by [nimi's answer](https://codegolf.stackexchange.com/a/85432/8478) I thought I'd try a different approach for Retina, making use of the regex engine's backtracking to figure out if any given (unary) number is in the sequence or not. It turns out this can be determined with a 27 byte regex, but making use of it costs a few more, but it still ends up shorter than the generative approach. Here's an alternative 48-byte solution: ``` .+ $* {`1\b 1! }T`1``1((!*)!(!|\2)(?=!\2$))*!$ ! ``` And using unary I/O we can do 42 bytes, but I'm trying to avoid that and the other Retina answer uses decimal as well: ``` 1\b 1! }T`1``1((!*)!(!|\2)(?=!\2$))*!$ ! 1 ``` [Answer] # Perl, ~~173~~ 132 bytes +1 for -n = 133 ``` sub c{my$a=pop;return($a==1||($a%2&&c(($a-1)/2))?1:$a%3!=2?0:$a%3==2?c(($a+1)/3):1)}while($#b<$_){$i++;@b=(@b,$i)if c$i}say$b[$_-1]; ``` Ungolfed: ``` my @array = (); my $n = <>; sub chk { my $a = shift; return 1 if ($a == 1); if ($a % 2 == 0) { if ($a % 3 != 2) { return 0; } else { return chk(($a + 1) / 3); } } else { if (chk(($a - 1) / 2) == 0) { if ($a % 3 != 2) { return 0; } else { return chk(($a + 1) / 3); } } else { return 1 } } } my $i = 1; while ($#array < $n-1) { push(@array,$i) if (chk($i) == 1); $i++; } print $array[$n]; ``` I can probably do better if I thought more about it, but this is what I came up with after just a few minutes. My first time golfing, so this was pretty fun! Thanks to @Dada and @TùxCräftîñg (and a bunch of minor byte-optimizations) for -40 bytes [Answer] # [Factor](https://factorcode.org/), 73 bytes ``` [ { } 1 rot [ { 2 3 } n*v { 1 -1 } v+ union natural-sort unclip ] times ] ``` [Try it online!](https://tio.run/##NU7LjsIwELv3K8x1EYjyWB77ASsuXBCnFYcoGmhEO8lOJpUQ6rd3U2Avlu3xyL4Yq17603F/@N7hRsJUozFaPWEqhq8UX7ylIfoWl8RWneeIIKR6D@JYEek3Edv8EUkzeFHHV3wV@8MO0YpRWxXFCEpR4TgkjcUDM5SYY4ElVvjEGhtsUc7Q9T94oMtH8YqBD6EO/NFmXmJSZtGOkTjvABtNYurJ0JktW7uAM9Q1ecy5b0z4r/VJn71T2JqM9H8 "Factor – Try It Online") Found a hidden golfing gem `unclip` which, given an array, returns `rest first` on the stack. It is especially helpful that `first` is on top of the stack. Using the `unclip`-ed state as the loop invariant, I could save a byte from `swap` vs. `rot` and six bytes from saving `first` at the end. ``` [ ! anonymous lambda { } 1 rot [ ... ] times ! setup stack as ( rest min ) and call n times... { 2 3 } n*v ! ( rest {2*min,3*min} ) { 1 -1 } v+ ! ( rest {2*min+1,3*min-1} ) union natural-sort ! set union of rest and next two numbers, sorted unclip ! extract first item (= next min) ] ``` [Answer] # J, 31 bytes ``` {1(]]/:~@~.@,3&*,&:<:2*>:)^:[~] ``` Uses zero-based indexing. Very memory-inefficient. ## Explanation ``` {1(]]/:~@~.@,3&*,&:<:2*>:)^:[~] Input: n ] Identity function, gets n 1 The constant 1 ( )^:[~ Repeat n times with an initial array a = [1] >: Increment each in a 2* Multiply by 2 to get 2a+2 3&* Multiply each in a by 3 to get 3a &:<: Decrement both x and y to get 2a+1 and 3a-1 , Join them ] Identity function, gets a , Join a with 2a+1 and 3a-1 ~.@ Take the distinct values /:~@ Sort up ] Return the sorted list { Select the value from the list at index n and return it ``` [Answer] # Octave, 68 bytes ``` function r=a(n)s=1;for(i=1:n)r=s(i);s=union(s,[r*2+1 r*3-1]);end;end ``` [Answer] # JavaScript (ES6), 58 ``` n=>(a=>{for(;n;)a[++i]?a[i-~i]=a[3*i-1]=--n:0})([i=0,1])|i ``` *Less golfed* ``` n=>{ a=[]; a[1] = 1; for(i = 0; n;) { ++i if (a[i]) { a[2*i+1] = 1; a[3*i-1] = 1; --n; } } return i } ``` *Test* About time and memory: element 500000 in ~20 sec and 300MB used by my FireFox 64 bit alpha ``` F= n=>(a=>{for(;n;)a[++i]?a[i-~i]=a[3*i-1]=--n:0})([i=0,1])|i function test() { var n=+I.value, t0=+new Date O.textContent = F(n) console.log((+new Date-t0)/1000,'sec') } test() ``` ``` #I { width:5em} ``` ``` <input id=I type=number value=10 oninput="test()"> <span id=O></span> ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 17 bytes ``` !OuΞ¡ṁ§eo←*3o→D;1 ``` [Try it online!](https://tio.run/##yygtzv7/X9G/9Ny8Qwsf7mw8tDw1/1HbBC1jIDnJxdrw////RgYA "Husk – Try It Online") There should be a shorter way using set difference. This answer creates all the possibilities, merges them and deduplicates. [Answer] # [Perl 5](https://www.perl.org/) `-p`, 82 bytes ``` $;{1}++;map@;{$_*2+1,$_*3-1}=1,keys%;while$_*3>keys%;;$_=(sort{$a-$b}keys%;)[$_-1] ``` [Try it online!](https://tio.run/##JYlRCgIhFEX/3zoMKsfwaa8fmWgDrSBCJhAaspRxIELcemYMXDicc6ObPNXKTMbCuXkO8WQys1vFsWvQAkuP3cN90sq876N3/3hc3DDbr1OY5swGwW5lqZsLswKvtSIo0LAHApSgJGgJ1IZACkgDtYeADt8Q5zG8UhVn2kmUVUT/Aw "Perl 5 – Try It Online") [Answer] # TI-Basic, 74 bytes ``` Input N {1→A For(I,1,N 1+2ʟA(I If min(Ans≠ʟA augment(ʟA,{Ans→A 3ʟA(I)-1 If min(Ans≠ʟA augment(ʟA,{Ans→A End SortA(ʟA ʟA(N ``` Uses 1-based indexing. Output is stored in `Ans` and is displayed. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 37 bytes ``` Nest[Union[#,2#+1,3#-1]&,{1},#][[#]]& ``` [Try it online!](https://tio.run/##DcgxCoAwDADArwQDXUzB6qyTs7g4hQxFFDO0Be1WfHv1xgs@X0fwWXdfTxjrcjyZt6gpMlKPraMBrRNDxb2Ewowips6J11tjZiVowE7QEJysIgTlr757pX4 "Wolfram Language (Mathematica) – Try It Online") ]
[Question] [ # Introduction Every number can be represented as ASCII. For example, \$0\$ comes in ASCII is \$48\$, \$1\$ is \$49\$, and so on. Using this method of translating numbers to other numbers, it is possible to infinitely expand a number, by replacing all its digits with their ASCII values and doing the same for the result. For example, if you started with \$0\$, you would expand to \$48\$, then to \$5256\$, and so on. # Challenge * You will be given a single digit and a number as input. You can assume the digit will be in the range \$0-9\$, or \$48-57\$ in ASCII. You can assume the digit will always be of length 1, and will be a string. The number will always be a positive integer, greater than -1. If it is 0, you do not expand at all. Other than that, there are no guarantees about its value. If, and only if your language has no method of input, you may store the input in two variables or in a list. * You must output the ASCII expansion of the digit if you expand it \$n\$ times, n being the number that was the input. If your language has no method of output, you may store it in a variable. # Example I/O * `Digit = 0, N = 3` `Output = 53505354` * `Digit = 2, N = 2` `Output = 5348` * `Digit = 5, N = 0` `Output = 5` # Rules This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer (in bytes) wins! [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 28 bytes ``` {($^a,*.ords.join...*)[$^b]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WkMlLlFHSy@/KKVYLys/M09PT09LM1olLim29n9xYqVCmoKBjrE1F4RppGMEY5rqGFj/BwA "Perl 6 – Try It Online") ### Explanation: ``` { } # Anonymous codeblock ( ...*)[$^b] # Index into an infinite list $^a, # Starting from the given number * # Where each element is .ords.join # The ordinal values joined ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` FÇJ ``` Takes `N` as first input and the digit as second. [Try it online](https://tio.run/##yy9OTMpM/f/f7XC71///xlwGAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/s5umi5Gd7eL9CYl6KQkpmemaJrZK9p4u9ksKjtkkKSvbF/90Ot3v9r9X5b8xlwGUEhAZcpgA). **Explanation:** ``` F # Loop the (implicit) first input (N) amount of times Ç # Convert the characters in the string at the top of the stack to its unicode values # (which will take the second input implicitly in the first iteration) J # Join these unicode integers together to a single string # (after the loop, the result is output implicitly) ``` [Answer] # [Python 2](https://docs.python.org/2/), 55 bytes ``` f=lambda s,n:f(`ord(s[0])`,n-1)+f(s[1:],n)if n*s else s ``` [Try it online!](https://tio.run/##DcfBCsMgDADQe78i5KRdBurYReiXjEI7aqjgUmkcY1/v9m6vftt@SOidp7K@ntsKShLZLMe5GX242S4kV28v/J@PM4nNDDIqpKIJtH/2XBL4WM8sDdiMWeq7GWs7OqTbgAEpDHhHcj8 "Python 2 – Try It Online") --- **56 bytes** ``` lambda s,n:eval("''.join(`ord(c)`for c in"*n+" s"+")"*n) ``` [Try it online!](https://tio.run/##DcZBDoIwEAXQPaeY/A0daAzWuCHhJi6oQENNnTalajx99a1e@pY9iqluutVgn/fV0qFl3N42KLTt6RG9qDnmVS08u5hpIS/opAcd6MH/cv3sPmx0HlP2Usipzkt6FcVcMUBfGhho0@AKPfwA "Python 2 – Try It Online") Generates and evaluates monstrosities like: ``` ''.join(`ord(c)`for c in''.join(`ord(c)`for c in''.join(`ord(c)`for c in s))) ``` --- **56 bytes** ``` f=lambda s,n:s*0**n or''.join(`ord(c)`for c in f(s,n-1)) ``` [Try it online!](https://tio.run/##DcpBDoMgEEDRvaeYzEYgtEGabky8i1ZLHKMzBDGmp6ds//vxl1dhX0oY9un4LBOclvvTOGMYJLXtcxNiNUpa1KzHIAlmIIag6vfotC73SvsXuj4m4ly7IY5XVlXQoX016NH6Bt9o3R8 "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 5 bytes ``` ṾOVƊ¡ ``` [Try it online!](https://tio.run/##y0rNyan8///hzn3@Yce6Di38//@/wX9jAA "Jelly – Try It Online") -2 bytes after a friend helped me figure out what's wrong with `O` For some reason, to run all test cases with a footer, an extra byte is required for the explicit `⁹` nilad: [Try it online!](https://tio.run/##y0rNyan8///hzn3@Yce6HjXuPLTw/@Hlx@Y@aloT@f9/dLSBjnGsTrSRjhGQNNUxiI0FAA "Jelly – Try It Online") ``` Ṿ Stringify the input O and convert each character to a codepoint, V then concatenate them and eval the result, Ɗ¡ repeated a number of times equal to the right argument. ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes ``` {ṫạc}ⁱ⁾ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wv/rhztUPdy1Mrn3UuPFR477//6MVog10jGN1oo10jICkqY5BbCwA "Brachylog – Try It Online") ``` { }ⁱ Repeat ṫ stringifying, ạ converting to a list of codepoints, c and concatenating ⁾ a number of times equal to the last element of the input. ``` [Answer] # [J](http://jsoftware.com/), ~~14~~ 13 bytes ``` [:,":@u:~"+&3 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o610lKwcSq3qlLTVjP9rcqUmZ@QrGCukKagbqEM4RiCOEZRjAOKYqv8HAA "J – Try It Online") ### How it works The "bind" operator `&` is commonly used to bind a constant to a dyad, so that it can be used as a monad. However, [the same form can be used as a dyad](https://code.jsoftware.com/wiki/Vocabulary/ampm#dyadic): `x n&v y` (where `n` is a noun and `v` is a dyadic verb) or `x v&n y` applies monadic `n&v` or `v&n` to `y` **repeatedly `x` times**. Using this feature, we can design the target function like this: ``` x some_constant&some_dyad y run `some_constant some_dyad y` x times ... or ... x some_dyad&some_constant y run `y some_dyad some_constant` x times ``` In this case, there is an obvious choice for the `some_constant`, which is `3` for `3 u: y`. And here goes the full explanation: ``` [:,":@u:~"+&3 & Apply this function x times... u:~ 3 Convert chars of y to ASCII values (3 u:) ":@ "+ Convert each number back to string [:, Flatten the array to get a single string ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 30 bytes ``` ->s,n{n.times{s=s.bytes*''};s} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9euWCevOk@vJDM3tbi62LZYL6myJLVYS1291rq49n9BaUmxQlq0uoG6joJxLBeMawTkGiG4pkCuQex/AA "Ruby – Try It Online") [Answer] # C# (.NET Core), ~~174~~ 147 bytes ``` class Z{static void Main(string[] a){for(int n=int.Parse(a[1]);n-->0;){var x="";foreach(char c in a[0])x+=c-0;a[0]=x;}System.Console.Write(a[0]);}} ``` Big help from Jo King. [Try it online!](https://tio.run/##FYzBCsIwEAV/ZekpQVIiHkO8eBYED4Klh2WNNlATyIZSKfn2mF4ewzA8YkUxuVppRmZ4bpwxe4Il@hdc0QfBOfnwGUZAub1jEj5kCLZtf8PETuBwHKUJSp21kduCCVbbdaalDmkSNDVD4APgoEe5HiwpbXa2qyn3H2f37S8xcJxd/0g@748tNKXUWnU9/QE "C# (.NET Core) – Try It Online") # Ungolfed ``` class Z { static void Main(string[] a) { int n = int.Parse(a[1]); for (; n-- > 0;) { var x = ""; foreach (char c in a[0]) x += c - 0; //c-0 gets converted to int, and then the int is //automatically converted to a string a[0]=x; } System.Console.Write(a[0]); } } ``` [Answer] # JavaScript (ES6), ~~43~~ 40 bytes *Thanks to @tsh for reminding me that I didn't use currying this time :p (-3 bytes)* Takes input as `(N)(digit)`. ``` n=>g=k=>n--?g(k.replace(/./g,c=>c^48)):k ``` [Try it online!](https://tio.run/##XcpNCsMgEEDhfU8RspqB@kOiEAKamxRkaqRVNCSl1zduWmgXb/W9p3u7g/bH9mK53H1dTc3GBhONzYwtASLf/ZYceRBchCsZSzc1Ic6xUslHSZ6nEmCFEaGXPWInRKdHLVvq8rsMbRm@i5r@WDbWH64n "JavaScript (Node.js) – Try It Online") ### How? This is a simple recursive function. The only trick in there is `c^48`. Because `c` is a string, we need to coerce it to an integer. We could do `+c+48`, but that would be 1 byte longer. Using a bitwise XOR is safe here, as \$48\$ is \$110000\_2\$ and `c` is less than \$10000\_2\$. [Answer] # [Haskell](https://www.haskell.org/), ~~30~~ ~~35~~ 30 bytes ``` (!!).iterate(>>=show.fromEnum) ``` [Try it online!](https://tio.run/##JYy9CsIwGEX3PsXX4JBAWkrFpdBsDp0cHNUhhKQNNmnID@LLG1OdDvdezl14eMp1zYZrC8MA0wUwqX5pBOe1jXAAwx3gZEXy/g2KwA2jDtEjoRj1iPY7T4h25FGp/eMaizdDw2AqesG/KOMI94zrmrQ6Ss@jxIyNYdlerfKbOdtkSM4foVY@h9wI574 "Haskell – Try It Online") +5 then -5 bytes from Jo King clarifying the rules and then working it into pointfree. My first Haskell golf so I've probably done something horribly wrong. In addition to having misspelled golf, I tried to import `ord` without putting it in my byte count! ``` . The composition of iterate infinitely iterating, starting with the argument, (>>= ) concatenating the results of mapping show finding the string representation of .fromEnum the codepoint of the argument, (!!) with indexing into the resulting infinite list. ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` VÆ=mc ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=VsY9bWM&input=IjAiCjI) ``` VÆ=mc V = number of times, U = digit VÆ V times do: (Collects each result into an array) =mc Map every digit of U to it's ASCII value, and make that the new U -h Take last element ``` [Answer] # [Perl 5](https://www.perl.org/), 22 bytes ``` eval's/./ord$&/ge;'x<> ``` [Try it online!](https://tio.run/##K0gtyjH9/z@1LDFHvVhfTz@/KEVFTT891Vq9wsbu/38DLmMuIyA05TL4l19QkpmfV/xftwAA "Perl 5 – Try It Online") [Answer] # [J](http://jsoftware.com/), 18 bytes ``` ([:,3":@u:"0])@[&0 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NaKtdIyVrBxKrZQMYjUdotUM/mtypSZn5CsYK6QpqBuoQzhGII4RlGMA4piq/wcA "J – Try It Online") From [the J dictionary](https://www.jsoftware.com/help/dictionary/d630n.htm): > > The phrase x f@[&0 y is equivalent to f^:x y , apply the monad f x times to y. > > > That is, it's a shortcut for power of `^:` applied as many times as the left arg. Which explains the ``` ( )@[&0 ``` part of the code. Now for what's in the parentheses: `3 u:]` converts to a unicode code point, but unfortunately has infinite rank, and we want to apply it with 0 rank, hence the added `"0`. The code point is a number, and we convert it back to a string with format `":`. Finally, we flatten `,` this list of strings. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~51~~ 49 bytes -2 bytes thanks to mazzy ``` param($s,$n),1*$n|%{$s=-join($s|% t*y|%{+$_})};$s ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/b8gsSgxV0OlWEclT1PHUEslr0a1WqXYVjcrPzMPKFyjqlCiVQkU01aJr9WstVYp/l/LxaWmkqagZKCkYAxhGSkpGEFYpkoKBv8B "PowerShell – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~63~~ 57 bytes ``` f=lambda i,n:n and f(''.join(`ord(c)`for c in i),n-1)or i ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIVMnzypPITEvRSFNQ11dLys/M08jIb8oRSNZMyEtv0ghWSEzTyFTUydP11ATyM38X1CUmVcCUmygrmOsyQUE/wE "Python 2 – Try It Online") -6 bytes due to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) noting that the input can be a string. Takes input as single digit string and an integer number of repetitions. [Answer] # [Bracmat](https://github.com/BartJongejan/Bracmat), 63 bytes ``` get':%?a %?n&whl'(!n+-1:~<0:?n&str$vap$((=.asc$!arg).!a):?a)&!a ``` [Try it online!](https://tio.run/##SypKTM5NLPn/Pz21RN1K1T5RQdU@T608I0ddQzFPW9fQqs7GwAooUlxSpFKWWKCioWGrl1icrKKYWJSuqaeYqGlln6ipppj4v6C0BCj430DBGAA "Bracmat – Try It Online") [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~13~~ 9 bytes -4 bytes thanks to ngn ``` (,/$`i$)/ ``` [Try it online!](https://tio.run/##y9bNz/7/P81KQ0dfJSFTRVP/f1q0sbWSgVLsfwA "K (oK) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 30 bytes ``` (!!).iterate(show.fromEnum=<<) ``` [Try it online!](https://tio.run/##BcFBCoAgEADAr@iSoFASRbc89orqIGElqYka/b5t5tT5Ms4hZ0ItyCkV0haTdDE8n/cr93T7KTxejaNAr20gisRkQyEVmaEF1tfQAetqGIC1K37b7vSRsdli/AE "Haskell – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes ``` FN≔⭆η℅κηη ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzOvoLTErzQ3KbVIQ1NTwbG4ODM9TyO4pCgzL903sUAjQ0fBvyglMy8xRyNbU1NHIUPTmisAKFmiAWT9/2/MZfBftywHAA "Charcoal – Try It Online") Link is to verbose version of code. Takes `N` as the first input and the digit as the second input. Explanation: ``` FN ``` Repeat `N` times... ``` ≔⭆η℅κη ``` Map each character to its ordinal and concatenate. ``` η ``` Output the final result. Sadly `FN≦℅ηη` doesn't work... [Answer] # [Lua](https://www.lua.org/), 55 bytes ``` a,N=...for i=1,N do a=a:gsub('.',('').byte)end print(a) ``` [Try it online!](https://tio.run/##yylN/P8/UcfPVk9PLy2/SCHT1lDHTyElXyHRNtEqvbg0SUNdT11HQ11dUy@psiRVMzUvhaugKDOvRCNR8////wb/jQE "Lua – Try It Online") Take input as arguments. Explanation is fairly obvious. # Alternative solution: [Lua](https://www.lua.org/), 60 bytes ``` a,N=...for i=1,N do a=table.concat{a:byte(1,-1)}end print(a) ``` [Try it online!](https://tio.run/##yylN/P8/UcfPVk9PLy2/SCHT1lDHTyElXyHRtiQxKSdVLzk/LzmxpDrRKqmyJFXDUEfXULM2NS@Fq6AoM69EI1Hz////Bv@NAQ "Lua – Try It Online") [Answer] # [QuadR](https://github.com/abrudz/QuadRS), 8 bytes Translation of [Nahuel Fouilleul](https://codegolf.stackexchange.com/users/70745/nahuel-fouilleul)'s [solution](https://codegolf.stackexchange.com/a/194746/43319). Thanks to [Veskah](https://codegolf.stackexchange.com/users/78849/veskah) for [pointing it out](https://chat.stackexchange.com/transcript/message/52256724#52256724). ``` . ⎕UCS⍵M ``` [Try it online!](https://tio.run/##KyxNTCn6/1@P61Hf1FDn4Ee9W33//zf4bwwA "QuadR – Try It Online") `.` replace any character `⎕UCS` with the Universal Character Set ordinal of the `⍵M` Match This is equivalent to the [Dyalog APL](https://www.dyalog.com/) expression `'.'⎕R{⍕⎕UCS⍵.Match}⍣⎕⊢⍞`. [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L@6nvqjvqlB1Y96pwLpUOfgR71b9XwTS5Izah/1LgYKPepa9Kh3HkjxfwUwKOAy4DIGAA "APL (Dyalog Unicode) – Try It Online") [Answer] # Lua, 67 bytes ``` i=io.read d=i(1)for _=1,i()do d=d:gsub(".",string.byte)end print(d) ``` [Try it online!](https://tio.run/##yylN/P8/0zYzX68oNTFFIcU2U8NQMy2/SCHe1lAnU0MzJZ8rxTbFKr24NElDSU9Jp7ikKDMvXS@psiRVMzUvhasAyC3RSNH8/99AwRgA "Lua – Try It Online") Let `d` be the digit we will transform (always of length 1, so we ask to read 1 character with `io.read(1)`). If `N > 0`, replace each character by its byte value. Return the digit. [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 3 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` {CJ ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSU3QkNKJmZvb3Rlcj0maW5wdXQ9MyUwQSUyMjAlMjImZmxhZ3M9) #### Explanation ``` {CJ # Implicit input { # Repeat N times: C # Get ASCII codes J # Join into a string # Implicit output ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 41 bytes ``` ""<>ToString/@ToCharacterCode@#&~Nest~##& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X0nJxi4kP7ikKDMvXd8hJN85I7EoMbkktcg5PyXVQVmtzi@1uKROWVntfwBQSUm0sq5dmoODcqyavkM1V7WSgZKOca0OkGGkpGMEZpgq6RjUctVy/QcA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 16 bytes ``` {(∊⍕¨∘⎕UCS)⍣⍵⊢⍺} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v1rjUUfXo96ph1Y86pjxqG9qqHOw5qPexY96tz7qWvSod1ft/7RHbRMe9fYB5Tz9H3U1H1pv/KhtIpAXHOQMJEM8PIP/qxuoK6QpGHOpG4FoIy51UxBtAAA "APL (Dyalog Unicode) – Try It Online") Left input is a one-digit string, right input is the number of iteration. Returns the string representation of the result. ### How it works ``` {(∊⍕¨∘⎕UCS)⍣⍵⊢⍺} { } Dyadic dfn, ⍺=digit string, ⍵=iteration ⊢⍺ Start with ⍺ ( )⍣⍵ Repeat ⍵ times... ⎕UCS Convert each char to Unicode codepoint ⍕¨∘ Convert each number back to string ∊ Enlist (flatten) all chars into one string ``` [Answer] # [PHP](https://php.net/), 58 bytes ``` for([,$a,$b]=$argv;$b--;)$a=strtr($a,range(48,57));echo$a; ``` [Try it online!](https://tio.run/##NY1BCsIwEEX3OUUoWSQwhdJaFGLxIDHItMRmoW1IoiDi2WNa66we/P/@OOvS8eSsI4RFE2KgHVWE5lMVNBp@WEP9xxaqjFoScp29wcFSvokY6EqCvtcqQz8@8xx6j6/L3fjRcDU9bjcNW1GmvMEVMATW624VJOvLUgqGXYg@ep4zj1NWdwdo90JIM9iZoUzLi4VpcZ4KST4pVan5Ag "PHP – Try It Online") Input digit and number are two command arguments (`$argv`) in same order. ### Comented ``` for( [,$a,$b]=$argv; // $a is input digit and $b is number $b--; // loop $b times ) $a= // set $a to strtr( // strtr in array mode, replaces keys with values $a, // replace in $a itself range(48,57) // an array with keys 0...9 and values 48...57 ); echo$a; // at the end, output $a ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 55 bytes ``` a=>b=>{for(;b-->0;a=a.SelectMany(l=>l-0+""));return a;} ``` [Try it online!](https://tio.run/##ZY5NS8QwEIbv@RVDTwlNSyt4MU0uywqCenAFz9NsqoHuFNLUD0p@e03Xo6cX3meembFzZWe/3S9ku4cjLRcXsB9dZz8wGHmtPUX5Dxkz6A216bVZhylw1VeVaRRqrE9udDY@If3wUZuxasqiEEIFF5dAgCptin1igEDvoIHcF7wgnacLF4rtq/I98Jk0KkcH7Z5lKWBlAH/eOdNs18/uO/JWwm02Ad6Cj@7Rk@PF2iQJa5vuYL1JhQQvd0vCHIPP3mEii5EP3Nev0@nacSF4HhH5UZbY9gs "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~69~~ 60 bytes ``` f=lambda n,i:i and f(''.join(str(ord(c))for c in n),i-1)or n ``` [Try it online!](https://tio.run/##DcfBCoAgDADQXxle2sCC7Bb0MaZIi9rEvPT1q3d79e2HymJWtivee44gnleGKBkKDsN0Kgs@vaG2jImoaIMELCDkeZzpr1htLB0LuuB8ILIP "Python 3 – Try It Online") [Answer] # [Red](http://www.red-lang.org), ~~62~~ 57 bytes ``` func[d n][loop n[parse d[any[change p: skip(0 + p/1)]]]d] ``` [Try it online!](https://tio.run/##RccxDoMwDAXQnVN8ZaJiaAB14RhdLQ8RTgAVGSvAwOnTDd72cpTyjUJcpaGkU0cSKNO6bQYlC3mPEAp60TgHnSJswP5brPZoYO/2xczCxfKiBxKcd@ire51D9@zj4Msf "Red – Try It Online") Explanation: ``` f: func [ d n ] [ ; a function with 2 parameters loop n [ ; repeat n times parse d [ ; parse the string with the following rules any [ ; one ore more change p: skip ; change any string with length 1 (a single digit) (0 + p/1) ; with its representation as a number 48..57 ] ] ] d ; return the altered string ] ``` [Answer] # [Icon](https://github.com/gtownsend/icon), ~~72~~ 63 bytes Inspired by @xnor's [Python 2 solution](https://codegolf.stackexchange.com/a/194755/75681) ``` procedure f(d,n) return(*d*n<1&d)|f(48+!d,n-1)||f(d[2:0],n) end ``` [Try it online!](https://tio.run/##y0zOz/v/v6AoPzk1pbQoVSFNI0UnT5OrKLWktChPQytFK8/GUC1FsyZNw8RCWxEop2uoWQPkpUQbWRnEgpSm5qUg6c9NzMzT0ORSAILyosySVI00DSUDJR1jTTQxIyUdI3QxUyUdA02IgQA "Icon – Try It Online") ]
[Question] [ Given a non-negative integer \$n ,\$ output the \$n^{\text{th}}\$ [Euler number](https://en.wikipedia.org/wiki/Euler_number) ([OEIS A122045](https://oeis.org/A122045)). All odd-indexed Euler numbers are \$0 .\$ The even-indexed Euler numbers can be computed with the following formula (\$i \equiv \sqrt{-1}\$ refers to the imaginary unit): $$ E\_{2n} = i \sum\_{k=1}^{2n+1}{ \sum\_{j=0}^{k}{ \left(\begin{array}{c}k \\ j \end{array}\right) \frac{{\left(-1\right)}^{j} {\left(k-2j\right)}^{2n+1}}{2^k i^k k} } } \,. $$ ## Rules * \$n\$ will be a non-negative integer such that the \$n^{\text{th}}\$ Euler number is within the representable range of integers for your language. ## Test Cases ``` 0 -> 1 1 -> 0 2 -> -1 3 -> 0 6 -> -61 10 -> -50521 20 -> 370371188237525 ``` [Answer] # Mathematica, 6 bytes ``` EulerE ``` -cough- [Answer] # [J](http://jsoftware.com/), 10 bytes ``` (1%6&o.)t: ``` [Try it online!](https://tio.run/nexus/j#@5@mYGuloGGoaqaWr6dZYsWVmpyRr6Cho5emZKCpUGGlYKBgqGCkYKxgpmBooGBk8P8/AA "J – TIO Nexus") Uses the definition for the exponential generating function sech(x). [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 9 bytes ``` eulerfrac ``` This built-in was added in version 2.13.0, after this challenge was asked. [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWK1NLc1KL0ooSkyH8mypp-UUaeQq2CgY6CkZAXFCUmVcCFFBS0LUDEmkaeZqamhC1CxZAaAA) --- # [PARI/GP](https://pari.math.u-bordeaux.fr), 24 bytes ``` n->2*imag(polylog(-n,I)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWO_J07Yy0MnMT0zUK8nMqc_LTNXTzdDw1NSHSN1XS8os08hRsFQx1FIwMdBQKijLzSoACSgq6dkAiTSNPE6Z2wQIIDQA) --- # [PARI/GP](https://pari.math.u-bordeaux.fr), 32 bytes ``` n->n!*Vec(1/cosh(x+O(x^n++)))[n] ``` This is the original answer. [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWNxXydO3yFLXCUpM1DPWT84szNCq0_TUq4vK0tTU1NaPzYqHqVNLyizTyFGwVDHQUjIC4oCgzrwQooKSgawck0jTygMohahcsgNAA) [Answer] # Maple, 5 bytes ``` euler ``` Hurray for builtins? [Answer] # [Maxima](http://maxima.sourceforge.net/), 5 bytes / 42 bytes Maxima has a built in: ``` euler ``` [Try it online!](https://tio.run/nexus/maxima#@5@mkadpZZucn5qWplGSWJmTX6RRnJqcoVGhqVOhY6CTp6mVpwhk5Wla/y8oyswr0UjTsNAEcgA "Maxima – TIO Nexus") The following solution does not require the built in from above, and uses the formula that originally defined the euler numbers. ![](https://wikimedia.org/api/rest_v1/media/math/render/svg/bef01280cc39c7321fbfc295a5babae89a6ed906) We are basically looking for the n-th coefficient of the series expansion of `1/cosh(t) = sech(t)` (up to the `n!`) ``` f(n):=coeff(taylor(sech(x),x,0,n)*n!,x,n); ``` [Try it online!](https://tio.run/nexus/maxima#@5@mkadpZZucn5qWplGSWJmTX6RRnJqcoVGhqVOhY6CTp6mVpwhk5Wla/y8oyswr0UjTsNAEcgA "Maxima – TIO Nexus") [Answer] # Mathematica, without built-in, 18 bytes Using [@rahnema1](https://codegolf.stackexchange.com/a/107591/9288)'s formula: ``` 2Im@PolyLog[-#,I]& ``` --- **21 bytes:** ``` Sech@x~D~{x,#}/.x->0& ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~70~~ ~~46~~ 44 bytes ``` F=(a,b=a)=>a?F(--a,b)*~b+F(a,b-=2)*(a-b):+!b ``` [Try it online!](https://tio.run/##HY2xDsIwDER3vsJsdlMj1JFi2PIfTgkoKKpRCh359ZAy3b2Tnu6pqy5TSa83z3aLNX5yLCBQvaD2QZTkolePzI2o@wbnt51loA6VA53cPtS7FcBVC6SmHscWZ4FhK87RDiabF8vxkO2BqYf/Byaisf4A "JavaScript (Node.js) – Try It Online") Surprised to find no JavaScript answer yet, so I'll have a try. The code consists of only basic mathematics, but the mathematics behind the code requires calculus. The recursion formula is derived from the expansion of the derivatives of \$\mathrm{sech}(x)\$ of different orders. ### Explanation Here I'll use some convenient notation. Let \$T^n:=\mathrm{tanh}^n(t)\$ and \$S^n:=\mathrm{sech}^n(t)\$. Then we have $$\frac{d^nS}{dt^n}=\sum\_{i=0}^nF(n,i)T^{n-i}S^{i+1}$$ Since \$\frac{dT}{dt}=S^2\$ and \$\frac{dS}{dt}=-TS\$, we can deduce that $$ \begin{equation} \begin{aligned} \frac{d}{dt}(T^aS^b)&=aT^{a-1}(S^2)(S^b)+bS^{b-1}(-TS)(T^a) \\ &=aT^{a-1}S^{b+2}-bT^{a+1}S^b \end{aligned} \end{equation} $$ Let \$b=i+1\$ and \$a=n-i\$, we can rewrite the relation above as $$ \begin{equation} \begin{aligned} \frac{d}{dt}(T^{n-i}S^{i+1})&=(n-i)T^{n-i-1}S^{i+3}-(i+1)T^{n-i+1}S^{i+1}\\ &=(n-i)T^{(n+1)-(i+2)}S^{(i+2)+1}-(i+1)T^{(n+1)-i}S^{i+1} \end{aligned} \end{equation} $$ That is, \$F(n,i)\$ contributes to both \$F(n+1,i+2)\$ and \$F(n+1,i)\$. As a result, we can write \$F(n,i)\$ in terms of \$F(n-1,i-2)\$ and \$F(n-1,i)\$: $$F(n,i)=(n-i+1)F(n-1,i-2)-(i+1)F(n-1,i)$$ with initial condition \$F(0,0)=1\$ and \$F(0,i)=0\$ where \$i\neq 0\$. The related part of the code `a?F(--a,b)*~b+F(a,b-=2)*(a-b):+!b` is exactly calculating using the above recurrence formula. Here's the breakdown: ``` F(--a,b) // F(n-1, i) [ a = n-1, b = i ] *~b // *-(i+1) [ a = n-1, b = i ] +F(a,b-=2) // +F(n-1, i-2) [ a = n-1, b = i-2 ] *(a-b) // *((n-1)-(i-2)) [ a = n-1, b = i-2 ] // which is equivalent to *(n-i+1) ``` Since \$T(0)=0\$ and \$S(0)=1\$, \$E\_n\$ equals the coefficient of \$S^{n+1}\$ in the expansion of \$\frac{d^nS}{dt^n}\$, which is \$F(n,n)\$. For branches that \$F(0,0)\$ can never be reached, the recurrences always end at 0, so \$F(n,i)=0\$ where \$i<0\$ or \$i\$ is odd. The latter one, particularly, implies that \$E\_n=0\$ for all odd \$n\$s. For even \$i\$s strictly larger than \$n\$, the recurrence may eventually allow \$0\leq i\leq n\$ to happen at some point, but before that step it must reach a point where \$i=n+1\$, and the recurrence formula shows that the value must be 0 at that point (since the first term is multiplied by \$n-i+1=n-(n+1)+1=0\$, and the second term is farther from the "triangle" of \$0\leq i\leq n\$). As a result, \$F(n,i)=0\$ where \$i > n\$. This completes the proof of the validity of the algorithm. [![enter image description here](https://i.stack.imgur.com/NQbeY.png)](https://i.stack.imgur.com/NQbeY.png) ### Extensions The code can be modified to calculate three more related sequences: **Tangent Numbers (46 bytes)** ``` F=(a,b=a)=>a?F(--a,b)*++b+F(a,b-=3)*(a-b):+!~b ``` **Secant Numbers (45 bytes)** ``` F=(a,b=a)=>a?F(--a,b)*++b+F(a,b-=3)*(a-b):+!b ``` **Euler Zigzag Numbers (48 bytes)** ``` F=(a,b=a)=>a?F(--a,b)*++b+F(a,b-=3)*(a-b):!b+!~b ``` [Answer] # Python 2.7, 46 bytes Using scipy. ``` from scipy.special import* lambda n:euler(n)[n] ``` [Answer] # [Perl 6](http://perl6.org/), 78 bytes ``` {(->*@E {1-sum @E».&{$_*2**(@E-1-$++)*[*](@E-$++^..@E)/[*] 1..$++}}...*)[$_]} ``` Uses the iterative formula [from here](http://www.robertobigoni.eu/Matematica/Transcendental/f08/f08.htm): $$E\_n = 1 - \sum\_{k=0}^{n-1} \left[ E\_k \cdot 2^{(n-1-k)} \cdot \binom{n}{k} \right]$$ ### How it works The general structure is a lambda in which an infinite sequence is generated, by an expression that is called repeatedly and gets all previous values of the sequence in the variable `@E`, and then that sequence is indexed with the lambda argument: ``` { ( -> *@E { } ... * )[$_] } ``` The expression called for each step of the sequence, is: ``` 1 - sum @E».&{ # 1 - ∑ $_ # Eₙ * 2**(@E - 1 - $++) # 2ⁿ⁻ˡ⁻ᵏ * [*](@E - $++ ^.. @E) # (n-k-1)·...·(n-1)·n / [*] 1..$++ # 1·2·...·k } ``` [Answer] # Maxima, 29 bytes ``` z(n):=2*imagpart(li[-n](%i)); ``` [Try It Online!](https://tio.run/#PtaV9) Two times imaginary part of polylogarithm function of order `-n` with argument `i` [[1]](https://oeis.org/A028296) [Answer] # Befunge, 115 bytes This just supports a hardcoded set of the first 16 Euler numbers (i.e. E0 to E15). Anything beyond that wouldn't fit in a 32-bit Befunge value anyway. ``` &:2%v [[email protected]](/cdn-cgi/l/email-protection)_2/: _1.@v:-1 v:-1_1-.@ _5.@v:-1 v:-1_"="-.@ _"}$#"*+.@v:-1 8**-.@v:-1_"'PO" "0h;"3_"A+y^"9*+**[[email protected]](/cdn-cgi/l/email-protection)*8+*:* ``` [Try it online!](http://befunge.tryitonline.net/#code=JjoyJXYKdkAuMF8yLzoKXzEuQHY6LTEKdjotMV8xLS5ACl81LkB2Oi0xCnY6LTFfIj0iLS5ACl8ifSQjIiorLkB2Oi0xCjgqKi0uQHY6LTFfIidQTyIKIjBoOyIzXyJBK3leIjkqKyoqLkAuLSo4Kyo6Kg&input=MTQ) I've also done a full implementation of the formula provided in the challenge, but it's nearly twice the size, and it's still limited to the first 16 values on TIO, even though that's a 64-bit interpreter. ``` <v0p00+1& v>1:>10p\00:>20p\>010g20g2*-00g1>-:30pv>\: _$12 0g2%2*-*10g20g110g20g-240pv^1g03:_^* >-#1:_!>\#<:#*_$40g:1-40p!#v_*\>0\0 @.$_^#`g00:<|!`g01::+1\+*/\< +4%1-*/+\2+^>$$10g::2>\#<1#*-#2:#\_$*\1 ``` [Try it online!](http://befunge.tryitonline.net/#code=PHYwcDAwKzEmCnY+MTo+MTBwXDAwOj4yMHBcPjAxMGcyMGcyKi0wMGcxPi06MzBwdj5cOgpfJDEyIDBnMiUyKi0qMTBnMjBnMTEwZzIwZy0yNDBwdl4xZzAzOl9eKgo+LSMxOl8hPlwjPDojKl8kNDBnOjEtNDBwISN2XypcPjBcMApALiRfXiNgZzAwOjx8IWBnMDE6OisxXCsqL1w8Cis0JTEtKi8rXDIrXj4kJDEwZzo6Mj5cIzwxIyotIzI6I1xfJCpcMQ&input=MTQ) The problem with this algorithm is that the intermediate values in the series overflow much sooner than the total does. On a 32-bit interpreter it can only handle the first 10 values (i.e. E0 to E9). Interpreters that use bignums should do much better though - [PyFunge](http://mearie.org/projects/pyfunge/) and [Befungee](https://github.com/programble/befungee) could both handle at least up to E30. [Answer] # Python2, (sympy rational), 153 bytes ``` from sympy import * t=n+2 print n,re(Add(*map(lambda (k,j):I**(k-2*j-1)*(k-2*j)**(n+1)*binomial(k,j)/(k*2**k),[(c/t+1,c%t) for c in range(0,t**2-t)]))) ``` This is very suboptimal but it's trying to use basic sympy functions and avoid floating point. Thanks @Mego for setting me straight on the original formula listed above. I tried to use something like @xnor's "combine two loops" from [Tips for golfing in Python](https://codegolf.stackexchange.com/questions/54/tips-for-golfing-in-python) [Answer] # Axiom, 5 bytes ``` euler ``` for OEIS A122045; this is 57 bytes ``` g(n:NNI):INT==factorial(n)*coefficient(taylor(sech(x)),n) ``` test code and results ``` (102) -> [[i,g(i)] for i in [0,1,2,3,6,10,20]] (102) [[0,1],[1,0],[2,- 1],[3,0],[6,- 61],[10,- 50521],[20,370371188237525]] (103) -> [[i,euler(i)] for i in [0,1,2,3,6,10,20]] (103) [[0,1],[1,0],[2,- 1],[3,0],[6,- 61],[10,- 50521],[20,370371188237525]] ``` [Answer] ## CJam (34 bytes) ``` {1a{_W%_,,.*0+(+W%\_,,:~.*.+}@*W=} ``` [Online demo](http://cjam.aditsu.net/#code=20%0A%0A%7B1a%7B_W%25_%2C%2C.*0%2B(%2BW%25%5C_%2C%2C%3A~.*.%2B%7D%40*W%3D%7D%0A%0A%25p) which prints E(0) to E(19). This is an anonymous block (function). The implementation borrows [Shieru Akasoto's recurrence](https://codegolf.stackexchange.com/a/186062/194) and rewrites it in a more CJam friendly style, manipulating entire rows at a time. ## Dissection ``` { e# Define a block 1a e# Start with row 0: [1] { e# Loop... _W% e# Take a copy and reverse it _,,.* e# Multiply each element by its position 0+(+ e# Pop the 0 from the start and add two 0s to the end W% e# Reverse again, giving [0 0 (i-1)a_0 (i-2)a_1 ... a_{i-2}] \ e# Go back to the other copy _,,:~.* e# Multiply each element by -1 ... -i .+ e# Add the two arrays } e# @* e# Bring the input to the top to control the loop count W= e# Take the last element } ``` [Answer] # APL(NARS), 42 chars, 84 bytes ``` E←{0≥w←⍵:1⋄1-+/{(⍵!w)×(2*w-1+⍵)×E⍵}¨¯1+⍳⍵} ``` Follow the formula showed from "smls", test: ``` E 0 1 E 1 0 E 3 0 E 6 ¯61 E 10 ¯50521 ``` the last case return one big rational as result because i enter 20x (the big rational 20/1) and not 20 as i think 20.0 float 64 bit... ``` E 20x 370371188237525 ``` It would be more fast if one return 0 soon but would be a little more long (50 chars): ``` E←{0≥w←⍵:1⋄0≠2∣w:0⋄1-+/{(⍵!w)×(2*w-1+⍵)×E⍵}¨¯1+⍳⍵} E 30x ¯441543893249023104553682821 ``` it would be more fast if it is used the definition on question (and would be a little more long 75 chars): ``` f←{0≥⍵:1⋄0≠2∣⍵:0⋄0J1×+/{+/⍵{⍺÷⍨(0J2*-⍺)×(⍵!⍺)×(¯1*⍵)×(⍺-2×⍵)*n}¨0..⍵}¨⍳n←1+⍵} f 0 1 f 1 0 f 3 0 f 6 ¯61J0 f 10 ¯50521J¯8.890242766E¯9 f 10x ¯50521J0 f 20x 370371188237525J0 f 30x ¯441543893249023104553682821J0 f 40x 14851150718114980017877156781405826684425J0 f 400x 290652112822334583927483864434329346014178100708615375725038705263971249271772421890927613982905400870578615922728 107805634246727371465484012302031163270328101126797841939707163099497536820702479746686714267778811263343861 344990648676537202541289333151841575657340742634189439612727396128265918519683720901279100496205972446809988 880945212776281115581267184426274778988681851866851641727953206090552901049158520028722201942987653512716826 524150450130141785716436856286094614730637618087804268356432570627536028770886829651448516666994497921751407 121752827492669601130599340120509192817404674513170334607613808215971646794552204048850269569900253391449524 735072587185797183507854751762384660697046224773187826603393443429017928197076520780169871299768968112010396 81980247383801787585348828625J0 ``` The result above it is one complex number that has only the real part. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~47~~ 46 bytes Without using any special functions: ``` e@0=1;e@n_:=-n!Sum[e[n-k]/k!/(n-k)!,{k,2,n,2}] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/z/VwcDW0DrVIS/eylY3TzG4NDc6NTpPNztWP1tRXwPI0FTUqc7WMdLJ0zGqjf0fUJSZVxIdkpiUkwpSF6ujUJ2no2Cgo2BkUBsb@x8A "Wolfram Language (Mathematica) – Try It Online") ]
[Question] [ Oh no! I'm trapped in a big forest (Okay, not really, but just assume it) and I don't know where I am! Thankfully, I brought my laptop. But when I searched 'Maps', It said 'No results', and I'm asking this as a last resort. Please make a program which outputs my location's longitude and latitude in any two number format. `any two number format` includes: * A tuple. * A string including the longitude and the latitude. * A JSON Object. * etc.. Any API or Libraries may be used. That is, You can query Google Maps, etc. (I guess, They didn't trash their APIs :\) [Answer] ## Mathematica, 4 bytes > > Err, where am I? > > > ``` Here ``` Evaluates to `GeoPosition[{latitude, longitude}]`. [Answer] # JavaScript (ES6), ~~89~~ 82 bytes ``` navigator.geolocation.watchPosition(x=>alert([(y=x.coords).latitude,y.longitude])) ``` [Try it online!](https://jsfiddle.net/MangaCoder/64wLmvjv/3/) (For some reason, this was not working in the snippet). ## Explanation `navigator` object is a part of [BOM](https://en.wikipedia.org/wiki/Browser_Object_Model). `geolocation` is a property of its and is also an object, which contains geolocational data of the user. `watchPosition()` is a method of `geolocation` object. It takes in a callback function which is executed after the geolocational data has been retrieved. The callback function `x=>alert((y=x.coords).latitude+","+y.longitude)` is an anonymous (lambda) function that takes in an object `x` and `alert()`s the `latitude` and `longitude` properties of `x.coords` separated by a comma. Note that the object `x` is passed to the callback function by `watchPosition()` when the callback function is called (i.e. after the retrieval of the geolocational data). --- **Note:** The geolocational data is GPS-based if GPS is available, otherwise it's based on IP. [Answer] # PowerShell, 130 Bytes ``` Add-Type -A System.Device;($a=[Device.Location.GeoCoordinateWatcher]::new()).Start();for(;($b=$a|% Po*n|% L*)|% I*){}$b|select L*e ``` Ungolfed: ``` Add-Type -AssemblyName System.Device #Required to access System.Device.Location namespace $GeoWatcher = New-Object System.Device.Location.GeoCoordinateWatcher #Create the required object $GeoWatcher.Start() #Begin resolving current locaton whille ($GeoWatcher.Status -ne "Ready") do { sleep -Milliseconds 100 } #Wait for discovery. $GeoWatcher.Position.Location | Select Latitude,Longitude #Select the relevent results. ``` Returns as: ``` PS C:\users\sweeneyc\Desktop> Add-Type -A System.Device;($a=[Device.Location.GeoCoordinateWatcher]::new()).Start();for(;($b=$a|% Po*n|% L*)|% I*){}$b|select L*e Latitude Longitude -------- --------- 53.4064177191653 -6.36202495701332 ``` Turns out there is a way to do this, but it's not so pretty. bonus: opens google maps on your current location. ``` Add-Type -A System.Device;($a=[Device.Location.GeoCoordinateWatcher]::new()).Start();for(;($b=$a|% Po*n|% L*)|% I*){};saps "https://www.google.ie/maps/@$($b.Latitude),$($b.Longitude)z" ``` could save 3 bytes using `TryStart` but it outputs a `true` to the pipeline and costs more to suppress that. ``` Add-Type -A System.Device;($a=[Device.Location.GeoCoordinateWatcher]::new()).TryStart($true,[int]9e8);$a|% Po*n|% L*|select L*e ``` --- # PowerShell (non-competing), 44 Bytes ``` (irm freegeoip.net/xml).Response|select *ude ``` Uses an external service since PowerShell has no internal builtins for 'current location' - this is IP-based Geolocation, so almost definitely won't return your actual location, it will return a 'default' location for your ISP, and if you run this over a VPN will present wherever the exit point is. I've tried (not as a golf exercise) to get google maps API to work with the wireless-mac-address geolocation method, but it's far from accurate or golfable. marked as non-competing due to the inaccuracy of the results. ``` PS C:\Users\sweeneyc> (irm freegeoip.net/xml).Response|select *ude Latitude Longitude -------- --------- 53.3472 -6.2439 ``` this displays `Central Dublin, Ireland` when searched up, however i'm a bit outside the city center currently, about 8 miles from the returned point. [Answer] # Python with requests, ~~101~~ ~~100~~ 75 bytes *4 bytes saved thanks to @КириллМалышев* *21 bytes saved thanks to @Rod* ``` from requests import*;print(get('http://su0.ru/auls').text.split(',')[5:7]) ``` [Answer] # [Angolf](http://github.com/XtremePlayzCODE/angled/blob/master/angolf.js), 110 107 bytes ``` ❦™navigator.geolocation.getCurrentPosition#x=>™alert##y=x.coords▷.latitude+","+y.longitude▷▷● ❦ Define an IIFE ™ Get the scope navigator Get JavaScript's navigator object from the scope geolocation Get the geolocation property of the navigator object getCurrentPosition Get the current position and execute a function x=> Define a function with x as a parameter ™ Get the scope alert Call alert and alert the following string: #y=x.coords▷ Define y with the value of the coordinates of x latitude Get y's latitude +"," Append "," to the string +y.longitude Append the longitude to the string ● Close the IIFE and call it with the scope ``` [Answer] # C#, 132 bytes ``` _=>{var w=new System.Device.Location.GeoCoordinateWatcher();w.Start();var c=w.Position.Location;return c.Longitude+","+c.Latitude;}; ``` [Answer] # Excel VBA (Windows, Office 2016+ Only), ~~278~~ 272 Bytes > > Restricted to Windows, Office 2016+ for the use of the `Microsoft.Mashup.OleDb.1` provider > > > Full `sub`routine that takes no input and outputs [your current location](http://su0.ru/auls) as a `Excel.ListObject` typed table, including extra information. ``` Sub a ThisWorkbook.Queries.Add"x","let S=Json.Document(Web.Contents(""su0.ru/auls""))in S With Sheet1.ListObjects.Add(0,"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=x",,,[A1]).QueryTable .CommandText="SELECT * FROM [x] .Refresh End With End Sub ``` Example output excluded for obvious reasons. -2 Bytes for use of `[Sheet1]` over `Sheets(1)` [Answer] # [Swift 4](https://developer.apple.com/swift/), ~~125 117~~ 96 bytes This can only be tested locally, unfortunately. ``` import CoreLocation;var c=CLLocationManager().location!.coordinate;print(c.longitude,c.latitude) ``` ]
[Question] [ Amazingly, this simple task doesn't seem to exist already, so... Your task is to write a program that takes as input a 12 hour time, and converts it into "military time", or 24-hour time format. Input will be in the form: ``` HH:MM am/pm ``` Although slight variations are allowed: * The space separating the am/pm from the rest of the time is optional. * The last part can either be "am"/"pm", or "a"/"p". * Any capitalization is fine. Output will be the inputted time, transformed into 24-hour format. It can be a number, or a string. For both the input and output: * 0s in the first place are optional. 0s in the last 3 places are mandatory. * the delimiter separating hours and minutes can be a ":", " " (a space), or nothing. Other notes: * Midnight can be expressed either as 0000, or 2400. * Midnight will be considered "am", while noon will be considered "pm". Your program can be a function, or a full program, and should either return the result, or output it to the stdout. Trailing whitespace is ok. Examples (you aren't required to support every format): ``` 12:00am -> 0000 1200 pm -> 1200 1234Am -> 00:34 134a -> 134 01:34PM -> 13 34 1234pm -> 1234 ``` This is code golf, so the smallest number of bytes wins. Since this is so trivial to solve using a built-in, it would be nice to see some code that manually solves this (but use of built-ins are fine). Just to clarify, you *aren't* required to support every possible format. Supporting only a single input and a single output format (of your choice) is fine. I would however like to limit the format as outlined above (which is already quite free). `{1134,'pm'}`, for example, would be unacceptable. [Answer] # [MATL](https://github.com/lmendo/MATL), 4 bytes ``` 15XO ``` [Try it online!](https://tio.run/nexus/matl#@29oGuH//7@6qZWJgUKArzoA "MATL – TIO Nexus") ### Explanation Built-in function: date string conversion with automatic detection of input format and with output format `15`, which corresponds to `'HH:MM'`. This is equivalent to [@StewieGriffin's Octave answer](https://codegolf.stackexchange.com/a/105862/36398). [Answer] # Octave, ~~21~~ 17 bytes Saved 4 bytes thanks to Luis Mendo. I could specify format number 15 instead of `'HHMM'`. ``` @(c)datestr(c,15) ``` **Explanation:** This is an [anonymous function](https://www.gnu.org/software/octave/doc/interpreter/Anonymous-Functions.html) taking a string `c` as input on the format: `'11:34 AM'`. `datestr` recognizes the format automatically as one of the [standard date formats](https://www.gnu.org/software/octave/doc/v4.0.0/Timing-Utilities.html#XREFdatestr), and outputs it in the specified format number 15, which is `HH:MM`. Since the specified output format doesn't have `AM` or `PM` Octave automatically converts it to what you refer to as Military time. [Try it online.](https://ideone.com/anyZ6R) --- **A version not using `datestr` using 35 bytes** ``` @(c)[c(1:4)+[1,2,0,0]*(c(5)>97),''] ``` **Explanation:** Takes an input string `c` on the format `1134am`. ``` @(c) % Anonymous function [c(1:4) % First 4 elements of the string +[1,2,0,0] % Add 1 and 2 to the first to the ASCII-value of the first two characters *)c(5)>97) % if the fifth element is larger than 97 (the ASCII code for `a`). ,''] % Implicitly convert to string ``` **Or, a different approach for 37 bytes:** ``` @(c)[c(1:4)+('1200'-48)*(c(5)>97),''] ``` [Answer] # [V](https://github.com/DJMcMayhem/V), ~~21~~ 17 bytes Thanks @DJMcMayhem for 4 bytes! ``` í12:/0: çp/12 $x ``` [Try it online!](https://tio.run/nexus/v#@394raGRlb6BFdfh5QX6hkaMKhX/Dy9P1AdSQHEjk0QuIGVoVMBlaGVqBiETAQ "V – TIO Nexus") This takes the format `HH:MMx` where `x` is either `a` or `p`, and returns it in the format `HH:MM` Hexdump: ``` 00000000: ed31 323a 2f30 3a0a e770 2f31 3201 2478 .12:/0:..p/12.$x 00000010: 0ae7 612f 2478 ..a/$x ``` Explanation: ``` í12:/0: | find and replace 12: with 0: (to avoid replacing HH:12) ç | on every line p/ | that contains a p 12^A | increment 12 times (the first number, hours) $x | delete the character at the end of the line ``` [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), ~~23~~ ~~20~~ 19 bytes ``` date "$args"-f HHmm ``` [Try it online!](https://tio.run/nexus/powershell#@5@eWqKbkliSqqCkkliUXqykm6bg4ZGb@///f3VDK2MThYJcdQA "PowerShell – TIO Nexus") (If you're on Windows, you can omit the `get-`, to get down to 19 bytes. On TIO, it apparently requires the full `Get-Date` name.) Takes input as a string `$args[0]`, uses that as the input to the `Get-Date` cmdlet, which parses it into a .NET `datetime` object. That's passed with the `-f`ormat parameter of `HHmm` to convert it to military time (the capital `HH` specifies 24-hour time). Output is implicit. The parsing engine is pretty robust, so additional inputs like `12am` or `12:00am` are allowed as well. Play around with the input on TIO and see what else works. (*Saved 3 bytes thanks to @admalledd ... saved another byte thanks to @briantist*) [Answer] ### Python 2, 44 bytes ``` lambda s:`int(s[:2])%12+12*("p"in s)`+s[3:5] ``` Input format: `01:23am`, optional `m` and spaces after minutes Output format: `123` [Answer] ### Pyth, ~~21~~ 20 bytes ``` Aczd++*12}\pH%sG12PH ``` Takes input of the form `01 23a` as "01:23 am". Initial 0 is optional. Output is of the form `123`, with the initial 0 omitted. In pseudocode: ``` z = input() A G, H = czd z.split(" ") # splits into the form ["1","23p"] ( +*12}\pH 12*('p' in H) + # add 12 if 'p' is in the string %sG12 int(G) % 12 + PH ) + H[:-1] # prepend hour to minutes, with a/p removed ``` [Try it online!](http://pyth.herokuapp.com/?code=Aczd%2B%2B%2a12%7D%5CpH%25sG12PH&test_suite=1&test_suite_input=12+00a%0A12+00p%0A12+34a%0A1+34a%0A01+34p%0A12+34p&debug=0) [Answer] # PHP, ~~35~~ 32 bytes input format: case insensitive, requires colon and the `m`, output format `hhmm`. uses built-ins: ``` <?=date(Hi,strtotime($argv[1])); ``` takes input from first command line argument. # PHP, 45 bytes, no built-ins input format `(h)h:mm a(m)` lowercase, output format `(h)hmm`. ``` <?=($s=$argv[1])%12+12*($s[6]>a).$s[3].$s[4]; ``` [Answer] # JavaScript (ES6), 40 bytes ``` a=>(new Date('1/1/1/'+a)+a).slice(16,21) ``` Input should be formatted like: `12:32 am` [Answer] # GNU Coreutils (~~18~~ 16 bytes) From a shell script: Does not accept whitespace in the input At which point, may as well use $1 and ignore additional args. ``` date -d$1 +%H%M ⇒ echo 'date -d$1 +%H%M' > time24 ⇒ sh time24 1:45pm 1345 ⇒ sh time24 1:45 pm 0145 # Wrong answer, “pm” ignored because of space ``` ## Original To allow whitespace in the input, ``` date -d"$@" +%H%M ``` [Answer] ## C#, 46 bytes ``` s=>System.DateTime.Parse(s).ToString("HH:mm"); ``` Strings are taken in input like `12:00 AM` Doing the same thing but substringing on the output from the default call to `ToString` (Assuming a culture of `en-GB`) is 3 bytes longer for 49 bytes: ``` s=>(System.DateTime.Parse(s)+"").Substring(11,5); ``` [Answer] # `date`, 0 + 8 = 8 bytes On the subject of using the right tool for the job… Takes input as a command line argument. Run with `+%H%M -d` (8 byte penalty). There's no actual program here; the entire work is done by the command-line arguments. (This is a pretty good demonstration of *why* there's a penalty for command-line arguments!) Example: ``` $ date +%H%M -d "12:05 am" 0005 ``` [Answer] # Java 7, ~~138~~ ~~106~~ ~~105~~ 104 bytes ``` String a(String a){return new java.text.SimpleDateFormat("Hmm").format(new java.util.Date("Ja1,0,"+a));} ``` [Try it online!](https://tio.run/nexus/java-openjdk#jY67jsIwEEV7vmLkyhbIShYq0HYLQkhbpVxRDMGwXvklewKsUL49OLzqVDN3dHTn1AZTgm/UDq5dRVG7IyB/LeIaFTXRgVNn@MMTSlIXkpW2wagvJLXy0SJxtraWCXl4pDfckDayxzjbYDkpJmyMQizaDkKzM7qGREh5nLzeg80Oz8c/250A@o3@nGB5qVUg7bPfCOBhivB5N@oDF4v@Xv0nUlb6hmTIFWQcR4mclR/zogDMdkO4MISbzob0DcOKO/d6247a7gY "Java (OpenJDK 8) – TIO Nexus") Input is colon delimited and has a space between the time and the am/pm. Output is not colon delimited. -1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 bytes ``` Ð"1/"+U s sG21 ``` [Try it online!](https://tio.run/nexus/japt#@394gpKhvpJ2qEKxQrG7keH//0qGVsbGCgW5SgA "Japt – TIO Nexus") This only works on Chrome. Here's a version that works in all browsers: ``` Ð"1/"³+U s sG21 ``` Thanks again to ETHproductions for the help! [Answer] # Perl, ~~45~~ ~~28~~ ~~37~~ bytes ## ~~28~~ 37 bytes (c/o @Dada) (36 bytes code, 1 byte for compiler `-p` switch) Accepts `0145pm` type formats, with am/pm or a/p. Leading zeroes on inputs required. ``` s/(..)(.)$//;$_=$_%12+12*(p eq$2).$1 ``` Test: ``` ⇒ echo 0145pm | perl -p time24 1345 ⇒ echo 0245pm | perl -p time24 1445 ⇒ echo 1245pm | perl -p time24 1245 ⇒ echo 1245am | perl -p time24 045 ``` ## My original answer (also gently revised) (39 bytes code, 1 byte for compiler `-p` switch.) Accepts only the form like 0145p or 0145a, and no other, and requires `perl -p` mode to work. ``` s/(..)(..)([ap])/$1%12+12*($3eq"p").$2/e ``` test: ``` ⇒ echo 0145p | perl -p time24 1345 ⇒ echo 1222a | perl -p time24 022 ⇒ echo 1234p | perl -p time24 1234 ``` [Answer] # Commodore 64 BASIC, 301 bytes before running, 321 bytes used once run ``` 0 A$="12:34AM":A=VAL(LEFT$(A$,2)+MID$(A$,4,2)):ON-(RIGHT$(A$,2)="AM")+1GOSUB1,2:TI$=A$:PRINTTI$:END 1 ON-(A=>1200ANDA<=1259)GOTO3:A=A+1200:GOTO3 2 ON-(A=>1200ANDA<=1259)GOTO4:ON-(A<=959)GOTO7:RETURN 3 A$=RIGHT$(STR$(A)+"00",6):RETURN 4 A=A-1200:IFA=0THENA$="000000":RETURN 5 IFA<10THENA$="000"+RIGHT$(STR$(A),1)+"00":RETURN 6 A$="00"+RIGHT$(STR$(A),2)+"00":RETURN 7 A$="0"+RIGHT$(STR$(A),3)+"00":RETURN ``` In order to enter this on a real Commodore 64, you will need to use BASIC keyword abbreviations, such as LE[shift]F for `LEFT$`, M[shift]I for `MID$` etc... or you could try CBM PRG STUDIO. The `TI$` variable in Commodore BASIC presents the time in 24 hour clock format as HHMMSS when printed. Taking the space out after the line number does not save any memory as Commodore BASIC adds in the space automatically anyway when you list the program after entering it. When converting a number to a string with `STR$`, Commodore BASIC will add in the space (so if you `PRINT A` you will see a space before the number is shown), I've removed the opening space on the number to string conversion with the `RIGHT$` command. You could save a few bytes by amending line zero to: ``` 0 A=VAL(LEFT$(A$,2)+MID$(A$,4,2)):ON-(RIGHT$(A$,2)="AM")+1GOSUB1,2:TI$=A$:PRINTTI$:END ``` so you will need to declare your time to convert before running the program, as follows: ``` A$="01:22AM":GOTO 0 ``` At any moment thereafter, you can see the current time with: ``` ? TI$ ``` [Answer] # Java, 171 bytes ``` enum t{;public static void main(String[] a){a=a[0].split("[: ]");System.out.format("%02d%02d",(Long.parseLong(a[0])+(a[2].charAt(0)=='p'?12:0))%24,Long.parseLong(a[1]));}} ``` Input format is `HH:MM a/p` and output format is `HHMM`. Abusing the fact that main function has an array of strings to split the input into 3 sections: hour, minute and a/p indicator. Example input and output: ``` Input: 01:02 a Output: 0102 Input: 01:02 p Output: 13:02 Input: 12:22 p Output: 0022 ``` Ungolfed version: ``` enum t { ; public static void main(String[] a) { a = a[0].split("[: ]"); System.out.format("%02d%02d", (Long.parseLong(a[0]) + (a[2].charAt(0) == 'p' ? 12 : 0)) % 24, Long.parseLong(a[1])); } } ``` [Answer] ## REXX, 33 bytes ``` arg h':'m a say h+((a=pm)*12)':'m ``` Use: ``` 12:34 pm -> 24:34 1:34 pm -> 13:34 1:34 am -> 1:34 0:34 AM -> 0:34 ``` This could be shortened by a few bytes if a colon as delimiter was not used. [Answer] ## [C (clang)](http://clang.llvm.org/), 94 bytes ``` h,m;f(){char a,b;scanf("%d:%d%c%c",&h,&m,&a,&b);printf("%02d%02d",a=='a'?(h%12):(12+h%12),m);} ``` [Try it online!](https://tio.run/nexus/c-clang#HY3LCoMwEEV/JVgSEzotPqALU9tvGSdKAiZK1FXxs7tOtYsDF86Fc3GBxs30z2U1brrbV7Lg9SDVhyxGhtDphTAMMuOm4YYTpwyEBeFBIIhO6Tm6sJ6@qMxJBti2OeZvaXlZqUaW1fW/wCu9p@PMPLpwFNiR0Sz26xYDKzTb06Op69l/w3QjJNv/AA "C (clang) – TIO Nexus") I'm here to learn, so any tips on how i can optimize the code are welcome. @ Johan du Toit Thanks, for saving a few bytes! [Answer] # C, ~~87~~ 72 bytes *Saved 15 bytes thanks to @Johan du Toit* Call `f()` with a mutable string as an argument, the input is the output. The format is `HH:MMa/p`, where `a/p` is either lowercase `a` or lowercase `p`. No space between the time and the meridian specifier is allowed. ``` i;f(char*p){i=atoi(p)%12+(p[5]^97?12:0);*p=i/10+48;p[1]=i%10+48;p[5]=0;} ``` [Try it on ideone](http://ideone.com/R77K7N). [Answer] # tcl, 45 ~~47~~ Now using a built-in: ``` puts [clock f [clock sc $s -f %I:%M%p] -f %R] ``` Testable on <http://rextester.com/TSRXI8802> where there is a script that runs it from 0100am to 1259pm [Answer] # SmileBASIC, 67 bytes ``` INPUT T$P=POP(T$)>"a TMREAD"00:"+T$OUT,H,M?H MOD 12+12*P,T$[3];T$[4] ``` Input: `HH:MMa/p` Output: `HH MM` [Answer] ## R, 68 bytes ``` x=substr(strptime(scan(,""),"%I:%M %p"),12,16);`if`(x=="","00:00",x) ``` Reads input from stdin and it's assumed to be in one of the following formats: * `12:00 AM` * `12:00 am` * `12:00AM` * `12:00am` and output is on the format: `[1] "00:00"` In most instances `strptime()` output is on the format: `"2017-01-06 12:00:00 CET"` where the date is the local date. As such we need to use `substr()` to only return the time, however, if the input is midnight (e.g. `12:00am`) the output is only `"2017-01-06 CET"` which is the reason for the `if` thing at the end (there must be some more clever workaround). [Answer] # C, ~~159~~ 152 bytes ``` #define C c[0] main(i,c)char**c;{scanf("%s",C);i=atoi(C);if(C[5]-97){i+=i-12?12:0;sprintf(C,"%d",i);}else if(i==12)C[0]=C[1]=48;C[2]=58;C[5]=0;puts(C);} ``` Input format: `07:30am` [Answer] ## Pyke, 15 bytes ``` 4<bwӐi%\pQ{i*+ ``` [Try it here!](http://pyke.catbus.co.uk/?code=4%3Cbw%D3%90i%25%5CpQ%7Bi%2a%2B&input=1200+am) [Answer] # Mathematica, 33 bytes ``` #~DateString~{"Hour24","Minute"}& ``` Anonymous function. Takes a string as input and returns a string as output. Works with most formats, including `hh:mm AM/PM`. [Answer] # JavaScript, 67 bytes ``` f=s=>!~s.indexOf`pm`?s.slice(0,5):((+s.slice(0,2)+12)+s.slice(2,5)) ``` Input is like in the example [Answer] ## Haskell, 61 characters Short version: ``` c[a,b,c,d,e]=(mod(read[a,b]::Int)12+f e,[c,d]) f 'a'=0 f _=12 ``` Input format: `HHMM(a/p)` where `(a/p)` is either 'a' or 'p' without parenthesis. Output format: `(hs, MM)` – a tuple containing the hours as an integer and MM still as string. Example: ``` > c "1200p" (12,"00") > c "1200a" (0,"00") ``` Longer version (with more useful names and one substitution `hs`): ``` conv [h0,h1,m0,m1,ap] = (mod hs 12 + offset ap, [m0,m1]) where hs = read [h0,h1] :: Int offset 'a'= 0 offset _ = 12 ``` [Answer] # Common Lisp (~~151~~122 bytes) OK, CL isn't meant to be “terse” but I'm just surprised that it isn't the most verbose for this one. Here's the 122 byte version, which requires fixed-position input. `0145pm` or `145p` are acceptable (with the leading space in the first character-position). ``` (defun a(x)(let((h(parse-integer(subseq x 0 2)))(m(subseq x 2 4)))(format nil "~a~a" (+(mod h 12)(if(find #\p x)12 0))m))) ``` PPRINT: ``` (DEFUN A (X) (LET ((H (PARSE-INTEGER (SUBSEQ X 0 2))) (M (SUBSEQ X 2 4))) (FORMAT NIL "~a~a" (+ (MOD H 12) (IF (FIND #\p X) 12 0)) M))) ``` ## Nicer but bigger Using only the `Common-Lisp` package. Accepts (only) input in the form of integer hours (with or without leading `0`), literal `:`, two-digit minutes, and optional trailing `am` or `pm` (in lower-case only). Permits whitespace around the time and around the AM/PM, but not directly after the `:`. ``` (defun a(x)(let*((c(position #\: x))(h(parse-integer(subseq x 0 c)))(m(subseq x(1+ c)(+ 3 c))))(format nil "~a~a" (+(mod h 12)(if(find #\p x)12 0))m))) ``` Test: ``` GOLF> (a " 1:45 am ") "1:45" GOLF> (a " 1:45 pm ") "13:45" GOLF> (a " 12:45 am ") "0:45" GOLF> (a "12:45p") "12:45" ``` `pprint` the function definition: ``` (DEFUN A (X) (LET* ((C (POSITION #\: X)) (H (PARSE-INTEGER (SUBSEQ X 0 C))) (M (SUBSEQ X (1+ C) (+ 3 C)))) (FORMAT NIL "~a~a" (+ (MOD H 12) (IF (FIND #\p X) 12 0)) M))) ``` De-obfuscated: ``` (defun 12->24-hour (timestring) "Given a TIMESTRING with hours:minutes and a trailing “am” or “pm” \(lowercase-only), return the 24-hour time without a delimiter as a string \(eg, \"1:45am\" → \"0145\"). Spaces surrounding the time or meridian markers are ignored \(eg, \" 02:22 pm \") but other junk in the string may cause incorrect behavior." (let ((colon (position #\: timestring))) (let ((hours (parse-integer (subseq timestring 0 colon))) (minutes (subseq timestring (+ 1 colon) (+ 3 colon)))) (format nil "~a~a" (+ (mod hours 12) (if (find #\p timestring) 12 0)) minutes)))) ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~61~~ 60 bytes ``` ^12(.*)a 00$1 ^(12.*)p $1 a (\d\d)(.*)p $1$*x12$*x$2 x+ $.& ``` Input is given without a separating colon, mandatory leading `0`, and using only `a` or `p` instead of `am` or `pm`, eg `0134a` is 01:34 am. Outputs in straight military time using 0000 as midnight. (I could save some bytes if I'm allowed to convert, for example, 12:30 am into `2430`, but I doubt that's acceptable). [Try it online!](https://tio.run/nexus/retina#@x9naKShp6WZyGVgoGLIFadhaATkFXAB2YlcXBoxKTEpmhpQERWtCkMjIKFixFWhzaWip/b/v4GhsUkBAA "Retina – TIO Nexus") **Explanation** The initial two cases deal with the "12" hours, since am/pm is reversed for 12: ``` ^12(.*)a 00$1 ``` If the time is between midnight (12 am) and 1 am, change it to 00 instead of 12, and remove the `a`. ``` ^(12.*)p $1 ``` If the time is between noon (12 pm) and 1pm, remove the p to simply get the 24 hour time. For any other hour: ``` a ``` If the time is am, simply remove the `a` to get the 24 hour time. ``` (\d\d)(.*)p $1$*x12$*x$2 x+ $.& ``` If the time is pm, remove the `p`. Convert the hour component to unary, add 12, and convert back to decimal. Leave the minutes unchanged. [Answer] ## Batch, 40 bytes ``` @set/aa=0,p=12,h=%1%%12+%3 @echo %h% %2 ``` Takes input as three arguments. Assumes second argument has leading zero where necessary, third argument is either `a` or `p`. Works by treating the third argument as an indirect variable name therefore adding it on to the number of hours; the number of minutes is unaffected so is just output directly. If mixing different formats is OK then the last space can be deleted to save a byte. (Rather annoyingly, this question didn't appear on the questions page when I originally loaded it, and I only stumbled across it because I was searching for another question.) ]
[Question] [ You should write a program or function which takes a non-negative integer `N` as input and outputs or returns two integers (negative, zero or positive) `X` and `Y`. Integers are meant in the mathematical sense as there are infinitely many of them. The implemented function has to be [bijective](http://en.wikipedia.org/wiki/Bijection). This means that for every `N` it has to output a different `X` `Y` pair and every `X` `Y` pair should be outputted for some input `N` i.e. all of the following pairs should be outputted for some `N`: ``` ... ┌─────┬─────┬────┬────┬────┐ │-2 -2│-2 -1│-2 0│-2 1│-2 2│ ├─────┼─────┼────┼────┼────┤ │-1 -2│-1 -1│-1 0│-1 1│-1 2│ ├─────┼─────┼────┼────┼────┤ ... │0 -2 │0 -1 │0 0 │0 1 │0 2 │ ... ├─────┼─────┼────┼────┼────┤ │1 -2 │1 -1 │1 0 │1 1 │1 2 │ ├─────┼─────┼────┼────┼────┤ │2 -2 │2 -1 │2 0 │2 1 │2 2 │ └─────┴─────┴────┴────┴────┘ ... ``` Note that `U V` and `V U` are different pairs if `U!=V`. ## Details * If your language doesn't support arbitrarily large integers that's fine but your algorithm should work with an arbitrarily large integer data-type. Your code should still support input values for at least `2^31-1`. * If you choose to print or return the output as string no leading `0`'s or `+` signs are allowed. Otherwise your language's standard integer representation is fine. ## Example **If** the task would be to make a bijective function taking a non-negative integer `N` and output **one** integer `X` a solution could be the function `if (input mod 2 == 0) return N/2 else return -(N+1)/2`, implemented in some language. This function returns `X = 0 -1 1 -2 2...` for `N = 0 1 2 3 4...`. [Answer] # CJam, ~~24~~ ~~22~~ 21 bytes My brain has trouble understanding the math other solutions are using. But my brain definitely understands binary, so here's a soultion based on bit manipulation! ``` li4b2fmd2/z{)(\2b^}%p ``` [Try it online.](http://cjam.aditsu.net/#code=li4b2fmd2%2Fz%7B)(%5C2b%5E%7D%25p&input=73) ### Explanation This approach treats the input as two interleaved binary values, one for each output number. All but the least significant bit of each encode a magnitude, and the least significant bit signals whether or not to take the bitwise complement of this magnitude. In this implementation, the odd-positioned bits correspond to the first output number (and the even-positioned bits correspond to the second) and an LSB of `0` signals to take the complement. For example, given an input of `73`, uninterleaving its binary representation of `1001001b` produces `0 1|0` (odd-positioned bits) and `1 0 0|1` (even-positioned bits). The first value has a magnitude of `01b = 1` and should be complemented for a final value of `~1 = -2`, and the second value has a magnitude of `100b = 4` and should not be complemented. ### Informal demonstration of correctness I made a testing program that places each input from zero to a user-specified number minus one in its output location on a 2D grid. You can [try it online](http://cjam.aditsu.net/#code=S2li%3AM(mq2mLi%23%3AL2*)%2CLf-%2B_%7BSL)2**%2B%7D%25S%40%2Ba%5C%2BM%2C%7B%3AX4b2fmd2%2Fz%7B)(%5C2b%5E%7D%25L2%2Bf%2B~_3%24%3D%40Xtt%7D%2F%7B%7BsSK*%5C%2BM(s%2CW*%3E%7D%25S*%7D%25N*&input=100) as well. Here's an output of this program showing how the algorithm maps `0-99`: ``` -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 -8 92 84 86 94 -7 88 80 82 90 -6 76 68 70 78 -5 96 72 64 66 74 98 -4 60 52 28 20 22 30 54 62 -3 56 48 24 16 18 26 50 58 -2 44 36 12 4 6 14 38 46 -1 40 32 8 0 2 10 34 42 0 41 33 9 1 3 11 35 43 1 45 37 13 5 7 15 39 47 2 57 49 25 17 19 27 51 59 3 61 53 29 21 23 31 55 63 4 97 73 65 67 75 99 5 77 69 71 79 6 89 81 83 91 7 93 85 87 95 8 ``` The fill pattern looks a bit weird, but it is in fact bijective! With each successive power of 4, it fills a square with double the previous side length. For example, here's how the algorithm maps `0-15`: ``` -2 -1 0 1 2 -2 12 4 6 14 -1 8 0 2 10 0 9 1 3 11 1 13 5 7 15 2 ``` This makes up the 4x4 square in the middle of the 8x8 square of `0-63`: ``` -4 -3 -2 -1 0 1 2 3 4 -4 60 52 28 20 22 30 54 62 -3 56 48 24 16 18 26 50 58 -2 44 36 12 4 6 14 38 46 -1 40 32 8 0 2 10 34 42 0 41 33 9 1 3 11 35 43 1 45 37 13 5 7 15 39 47 2 57 49 25 17 19 27 51 59 3 61 53 29 21 23 31 55 63 4 ``` Which makes up the 8x8 square in the middle of the 16x16 square of `0-255`: ``` -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 -8 252 244 220 212 124 116 92 84 86 94 118 126 214 222 246 254 -7 248 240 216 208 120 112 88 80 82 90 114 122 210 218 242 250 -6 236 228 204 196 108 100 76 68 70 78 102 110 198 206 230 238 -5 232 224 200 192 104 96 72 64 66 74 98 106 194 202 226 234 -4 188 180 156 148 60 52 28 20 22 30 54 62 150 158 182 190 -3 184 176 152 144 56 48 24 16 18 26 50 58 146 154 178 186 -2 172 164 140 132 44 36 12 4 6 14 38 46 134 142 166 174 -1 168 160 136 128 40 32 8 0 2 10 34 42 130 138 162 170 0 169 161 137 129 41 33 9 1 3 11 35 43 131 139 163 171 1 173 165 141 133 45 37 13 5 7 15 39 47 135 143 167 175 2 185 177 153 145 57 49 25 17 19 27 51 59 147 155 179 187 3 189 181 157 149 61 53 29 21 23 31 55 63 151 159 183 191 4 233 225 201 193 105 97 73 65 67 75 99 107 195 203 227 235 5 237 229 205 197 109 101 77 69 71 79 103 111 199 207 231 239 6 249 241 217 209 121 113 89 81 83 91 115 123 211 219 243 251 7 253 245 221 213 125 117 93 85 87 95 119 127 215 223 247 255 8 ``` [Answer] # Pyth, 15 ``` u,-HyeGhGjQ2,ZZ ``` [Try it online.](https://pyth.herokuapp.com/?code=u%2C-HyeGhGjQ2%2CZZ&input=19) ``` u reduce lambda G,H: [implicit] ,-HyeGhG (H-2*G[-1],G[0]) jQ2 base(input(),2) ,ZZ (0,0) print result [implicit] ``` A Python translation: ``` g=lambda Z,n:(n-2*Z[1],Z[0]) print reduce(g,binlist(input()),(0,0)) ``` or iteratively: ``` (x,y)=(0,0) for b in binlist(input()): (x,y)=(b-2*y,x) print (x,y) ``` where `binlist` converts a number to a list of digits like `binlist(4) = [1,0,0]`. So, how does this work? It interprets the binary digits of the number \$n\$ as two interleaved numbers in [base negative two](http://en.wikipedia.org/wiki/Negative_base) like in my [Python solution](http://codegolf.stackexchange.com/a/48730/20260). The binary number $$n=\dots b\_5 b\_4 b\_3 b\_2 b\_1 b\_0 $$ corresponds to the pair $$ (x,y) = (b\_0 - 2 b\_2 + 4 b\_4 - 8 b\_6 + \cdots, b\_1 - 2 b\_3 + 4 b\_5 - 8 b\_7 + \cdots).$$ If we hadn't yet processed the last digit \$b\_0\$ of \$n\$, we'd have all indices higher by $1$, $$n'=\dots b\_5 b\_4 b\_3 b\_2 b\_1 $$ corresponding to the pair $$ (x',y') = (b\_1 - 2 b\_3 + 4 b\_5 - 8 b\_7 + \cdots, b\_2 - 2 b\_4 + 4 b\_6 - 8 b\_8 + \cdots).$$ We can then express the new values once \$b\_0\$ is read in terms of the old values $$(x,y) = (b\_0 - 2y', x').$$ So, by repeatedly performing the transformation \$(x,y) \to (b - 2y, x)\$ on each successive bit \$b\$ of \$n\$, we build the point \$(x,y)\$ that comes from extracting its digits. [Answer] ## Python 2, 49 Edit: Improved to 49 by using better one-step recursion for base -2. ``` def f(n):x,y=n and f(n/2)or(0,0);return n%2-2*y,x ``` Here's a [Pyth version](https://codegolf.stackexchange.com/a/48740/20260) using `reduce`. Edit: Improved to 52 by switching to [base -2](http://en.wikipedia.org/wiki/Negative_base) from [balanced ternary](http://en.wikipedia.org/wiki/Balanced_ternary). **Python 2, 52** ``` h=lambda n:n and n%2-2*h(n/4) lambda n:(h(n),h(n/2)) ``` --- **Python 2, 54** ``` h=lambda n:n and-~n%3-1+3*h(n/9) lambda n:(h(n),h(n/3)) ``` This uses digit interleaving like [Runer112's solution](https://codegolf.stackexchange.com/a/48717/20260), but with balanced ternary rather than signed binary. Python doesn't have built-in base conversion, so the code implements it recursively. The helper function `h` (with `3` in place of the `9`) takes a natural number and converts it from ternary to balanced ternary with the digit substitutions ``` 0 -> 0 1 -> +1 2 -> -1 ``` So, for example, 19, which is 201 in base, becomes (-1)(0)(+1) in balanced ternary, which is (-1)\*3^2 +(0)\*3^1+(+1)\*3^0 = -8. Balanced ternary suffices to encode every integer, and so gives a mapping from natural numbers to integers. To map to pairs of integers, we interleave the digits in `n`. To do so, we have `h` look at every other digit by doing `n/9` as the recursive step rather than `n/3`. Then, for one coordinate, we shift `n` by floor-dividing by `3`. Here are the first 81 outputs, which cover the region [-4,4]^2. ``` 0 (0, 0) 1 (1, 0) 2 (-1, 0) 3 (0, 1) 4 (1, 1) 5 (-1, 1) 6 (0, -1) 7 (1, -1) 8 (-1, -1) 9 (3, 0) 10 (4, 0) 11 (2, 0) 12 (3, 1) 13 (4, 1) 14 (2, 1) 15 (3, -1) 16 (4, -1) 17 (2, -1) 18 (-3, 0) 19 (-2, 0) 20 (-4, 0) 21 (-3, 1) 22 (-2, 1) 23 (-4, 1) 24 (-3, -1) 25 (-2, -1) 26 (-4, -1) 27 (0, 3) 28 (1, 3) 29 (-1, 3) 30 (0, 4) 31 (1, 4) 32 (-1, 4) 33 (0, 2) 34 (1, 2) 35 (-1, 2) 36 (3, 3) 37 (4, 3) 38 (2, 3) 39 (3, 4) 40 (4, 4) 41 (2, 4) 42 (3, 2) 43 (4, 2) 44 (2, 2) 45 (-3, 3) 46 (-2, 3) 47 (-4, 3) 48 (-3, 4) 49 (-2, 4) 50 (-4, 4) 51 (-3, 2) 52 (-2, 2) 53 (-4, 2) 54 (0, -3) 55 (1, -3) 56 (-1, -3) 57 (0, -2) 58 (1, -2) 59 (-1, -2) 60 (0, -4) 61 (1, -4) 62 (-1, -4) 63 (3, -3) 64 (4, -3) 65 (2, -3) 66 (3, -2) 67 (4, -2) 68 (2, -2) 69 (3, -4) 70 (4, -4) 71 (2, -4) 72 (-3, -3) 73 (-2, -3) 74 (-4, -3) 75 (-3, -2) 76 (-2, -2) 77 (-4, -2) 78 (-3, -4) 79 (-2, -4) 80 (-4, -4) ``` An alternative coding with [quarter-imaginary](http://en.wikipedia.org/wiki/Quater-imaginary_base) turned out longer, though it is very pretty. **Python 2, 63** ``` h=lambda n:n and n%4+2j*h(n/4) lambda n:(h(n).real,h(n).imag/2) ``` In a language with less clunky handling of complex conversion, this would probably be a better approach. If we could output complex numbers, we could do: **Python 2, 38** ``` f=lambda n:n and n%2+n/2%2*1j-2*f(n/4) ``` [Answer] ## Python 2, 98 bytes Let's start out with a simple approach: ``` def f(N): x=a=0;b=2 while N:x+=1j**b;b+=a<1;a=a or b/2;N-=1;a-=1 return int(x.real),int(x.imag) ``` It just forms a rectangular spiral `N` units long on a 2d grid, starting from the origin, and returns the coordinates of the last point. The function is bijective since: * Each point can be covered, given a long enough spiral * Each point will only be intersected by the spiral once The spiral looks something like this (except starting at 0 rather than 1): ![Ulam Spiral](https://i.stack.imgur.com/mekMi.png) [Answer] # dc, 49 ``` [1+2~2*1-*n]sm?dsa8*1+v1-2/dd1+*2/lar-dlmx32P-lmx ``` This starts off by arranging the non-negative integers on a grid thus: ``` ..| 4 | 14 3 | 9 13 2 | 5 8 12 1 | 2 4 7 11 0 | 0 1 3 6 10 Y +----------------- X 0 1 2 3 4 ... ``` Note that how the grid positions are filled diagonally with increasing N. Notice the Y=0 line contains the triangular number sequence, given by `N = X(X+1)/2`. This is a quadratic equation which is solved using the normal formula, using just the +ve root, so that we can determine X from N when Y=0. Next is some simple arithmetic shuffling to give unique {X,Y} for every N. This provides the required bijective quality, but X and Y are only non-negative, but the question requires all possible integers. So X and Y are mapped using `((t+1)/2)*((t+1)~2*2-1)` to give all possible integers. `dc` has arbitrary precision numbers, so input range to `2^31-1` is no problem. Note also that default precision is 0 decimal digits, and the `sqrt()` and `/` round down which is the behavior needed here. ### Output: ``` $ for i in {0..10}; do dc biject.dc <<< $i; echo; done 0 0 0 -1 -1 0 0 1 -1 -1 1 0 0 -2 -1 1 1 -1 -2 0 0 2 $ ``` [Answer] # Matlab, 54 bytes ``` n=input('')+1;[i,j]=find(spiral(2*n)==n);disp([i,j]-n) ``` The key here is `spiral`, this creates a spiral matrix of an arbitrary size. ``` spiral(3) ``` returns ``` ans = 7 8 9 6 1 2 5 4 3 ``` In Matlab, this works for integers, but you will get memory issues way before that, (well, I am assuming you as the command `spiral` creates a full matrix first, that has size of about \$4n^2\$. At around \$n \simeq 10^4\$ this matrix takes up more than 1GB of space. So with 1TB of RAM you will get to around \$n \simeq 10^5\$, and about \$2.9\cdot 10^{11}\$ GB of RAM will get you to \$n=2^{32}\$. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 12 bytes ``` -2/+2 2\0,4\ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700Oz4vPW_BgqWlJWm6FuvSrHSN9LWNFIxiDHRMYiCCOwwNDBRsFZRtFdLUFRSBHC4oDZGG6QUA) (ATO because the original ngn/k page isn't working at the time of posting) Uses bit halving followed by base -2. `0,` is necessary to get `0 0` for input `0`. ``` -2/+2 2\0,4\ 4\ convert to base 4 0, prepend a 0 2 2\ convert each to base 2, forcing two bits per a base-4 digit (base conversion happens column-wise, so the result here is a two-row matrix) + transpose -2/ evaluate each column in base -2 ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~72~~ ~~68~~ ~~66~~ ~~62~~ 53 bytes ``` {(-|:)/[0<d;0,d:m*x-1+s*s-1]+(m:*/s#-1)*2#-2!s:-_-%x} ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs6rW0K2x0tSPNrBJsTbQSbHK1arQNdQu1irWNYzV1si10tIvVtY11NQyUtY1Uiy20o3XVa2o5eKyKrJKUzfUVjQ0MuVy0De0sYop4gIAAckSxQ==) -4 : Squeezed out a few bytes -2 : A couple more -4 : Oh yeah, we’re golfing… -9 : Forgot ngn/k has sqrt [Answer] # [J](https://www.jsoftware.com), 11 bytes ``` _1j1+.@#.#: ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT0F9TQFWysFdR0FAwUrINbVU3AO8nFbWlqSpmuxOt4wy1Bbz0FZT9kKIrJBk4srNTkj3yFNzU4hU8_YCCK8YAGEBgA) Uses [complex base](https://en.wikipedia.org/wiki/Complex-base_system#Binary_systems) `-1 + i` to generate a Gaussian integer from the binary representation of the given nonnegative integer. ``` _1j1+.@#.#: #: Convert to binary _1j1 #. Evaluate the binary sequence as base -1 + i +.@ Take apart its real and imaginary parts ``` If outputting a complex number were allowed, it would be 8 bytes (delete `+.@`). I couldn't find a complete proof that this conversion is bijective, but [this challenge](https://codegolf.stackexchange.com/q/76062/78410) mentions it, and I think the following argument is enough to prove it: > > Given a Gaussian integer, the lowest bit of base `-1 + i` representation is determined by `(real+imag)%2`. Subtract it and divide by `-1 + i`, and you always get another Gaussian integer with smaller magnitude (at least until it becomes small enough, at which point the proof can be done individually). This conversion algorithm is deterministic and finite, and defines an inverse of conversion from binary to Gaussian using base `-1 + i`. > > > [Answer] # Haskell, ~~78~~ 74 bytes ``` (concat[[(x,i-x),(x,x-1-i),(-1-x,x-1-i),(-1-x,i-x)]|i<-[0..],x<-[0..i]]!!) ``` Test run: ``` *Main> mapM_ (print . (concat[[(x,i-x),(x,x-1-i),(-1-x,x-1-i),(-1-x,i-x)]|i<-[0..],x<-[0..i]]!!) ) [0..20] (0,0) (0,-1) (-1,-1) (-1,0) (0,1) (0,-2) (-1,-2) (-1,1) (1,0) (1,-1) (-2,-1) (-2,0) (0,2) (0,-3) (-1,-3) (-1,2) (1,1) (1,-2) (-2,-2) (-2,1) (2,0) ``` How it works: list all pairs in the first quadrant in the following order ``` | 2| #4 | 1| #2 #5 | 0| #1 #3 #6 +--------------- 0 1 2 3 ``` mirror each point into the other quadrants to make a list of 4 element lists. Concatenate all into a single list and take the `n`th element. Edit: function doesn't need a name, reordered math. expressions. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 35 bytes ``` >©DÝʒo®sÖ}àsÅÉʒ®sÖ}à<2÷‚εDÈi2÷ë>2÷( ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f7tBKl8NzT03KP7Su@PC02sMLig@3Hu48NQnGtTE6vP1Rw6xzW10Od2QC2YdX2wFJjf//zQE "05AB1E – Try It Online") or as [Test suite](https://tio.run/##NY2/SgNBHIRfJaSy@Ir9/dnbXZCkubcQCwWLVCkOhBQHNgZtr7AQAmlFsBP7bJfCh8iLnNvYDDMfzMx2uLvfPMyPu35enT76ejhP29PXUN/Gehzqc309T//xWuvP5en997uvL5vm6@eq6dU8jrv1cnHZT4vlmvkmICiGE@lIZArSoCCKGOJIRDokIRkpaEBbR1FDHY1ohyY0owULmGBt0jDHItZhCctYwQMuuOLt0fGId3jCM16I4fYP "05AB1E – Try It Online") ## Explanation Consider $$\begin{align\*} f: \mathbb{N} &\longrightarrow \mathbb{N} \times \mathbb{N} \\ n&\longmapsto (x,y)\, , \end{align\*} $$ where \$x\$ is the largest number so that \$2^x\$ divides \$n+1\$, and where \$2y+1\$ is the largest odd number which divides \$n+1\$. The inverse of \$f\$ is the well-known bijection \$f^{-1}(x,y) = 2^x(2y+1)-1\$. Then consider $$\begin{align\*} g: \mathbb{N} \times \mathbb{N} &\longrightarrow \mathbb{Z} \times \mathbb{Z} \\ (m,n)&\longmapsto (h(m),h(n))\, , \end{align\*} $$ where $$\begin{align\*} h: \mathbb{N} &\longrightarrow \mathbb{Z} \\ n&\longmapsto \begin{cases}\frac n2, & n \text{ even}\\ -\frac{n+1}2, & n \text{ odd}\end{cases}\, . \end{align\*} $$ Since \$f\$, \$g\$ and \$h\$ all are bijections, the composition \$g\circ f:\mathbb{N} \longrightarrow \mathbb{Z} \times \mathbb{Z}\$ is a bijection. The program simply computes \$g\circ f\$. ``` >©DÝʒo®sÖ}àsÅÉʒ®sÖ}à<2÷‚εDÈi2÷ë>2÷( # Full program # Implicit input: Integer n >© # Compute n+1 and save it to the register DÝ # Duplicate n+1 and push the list [0,...,n+1] ʒo®sÖ} # Only keep those numbers x so that 2^x divides n+1 à # Get maximum element in the list. sÅÉ # Swap so that n+1 is on top and push [1,3,5,...,n+1] ʒ®sÖ} # Only keep those numbers z which divides n+1 à<2÷ # Compute y = (z-1)/2 ‚ # Push the pair [x,y] ε # Apply the function h to x (and y): i # if... DÈ # x is even 2÷ # then compute x/2 ë>2÷( # else compute -(x+1)/2 # Implicit output: [h(x),h(y)] ``` [Answer] # [Haskell](https://www.haskell.org/), 50 bytes ``` (0!).succ l!n=(last$(!).succ:[(,)|odd n])l$div n 2 ``` [Try it online](https://tio.run/##y0gszk7NyfmfpmCrEPNfw0BRU6@4NDmZK0cxz1YjJ7G4REUDKmQVraGjWZOfkqKQF6uZo5KSWaaQp2D0PzcxMw@ot6AoM69EQU8hDYiLUhNTFGxtbBTSU0uc8/NKUvNKiv8b/EtOy0lML/6vG@EcEAAA "Haskell – Try It Online") or [try it with its inverse!](https://tio.run/##hY@9CsIwAIT3PMVZCibalrSjoIurguAi1Cohba2YpmLiH/jsxljcHb/v7oZrhDlVSrl6CPqIngxTZLsHRqDZ6DlOGWKkhNRebx3lA5aYq5REDfSUKmFsSH9qktOIvbqyhC6YCsvjDRqZa8VR@20rzss96Plq1/ay0Ehw6BhyniQp57zAvakuFSHwGt@@7LQU1jOQwzTdHbqHCAHi2dYGP@qjEPWf2H/zFdbbwr1lrcTBuHgzX60@ "Haskell – Try It Online") ## Ungolfed ``` ntoN2 n = 0 ! (n + 1) xCounter ! remainingNum | odd remainingNum = (xCounter, div remainingNum 2) | otherwise = (xCounter + 1) ! div remainingNum 2 ``` ## Explanation This uses the fact that each \$(x,y) \in \mathbb{N}^2\$ can be 1-to-1 mapped to \$2^x \cdot (2\cdot y + 1) - 1 \in \mathbb{N}\$. The above operator `(!)` computes \$x\$ by dividing the input as long as it's even, keeping track with the zero-initialized variable `l` (`xCounter`). Once we reached the even number an integer division computes `y`. Note that the actual function `f` (`ntoN2`) increments the input before starting with the procedure. [Answer] # JavaScript, 166 168 bytes/characters New approach using a rectangular spiral like others are using. ``` function f(n){return b=Math,k=b.ceil((b.sqrt(n)-1)/2),t=2*k+1,m=b.pow(t,2),t+=4,m-t>n?(m-=t,m-t>n?(m-=t,m-t>n?[k,k-(m-n-t)]:[-k+(m-n),k]):[-k,-k+(m-n)]):[k-(m-n),-k]} ``` I used [this](https://math.stackexchange.com/a/163101) answer on Math.SE, translated it to JS and compressed it using [UglifyJS](http://lisperator.net/uglifyjs/#demo). This approach does not use any loops nor does it create the spiral in any way. Because the spiral's coordinates cover all integers the function is bijective in the sense of \$f:\mathbb{N}^0\rightarrow \mathbb{Z}^2\$. **Update:** Saved 2 characters by storing `Math` in `b`. **Update 2:** Replaced `t-=1` with `t+=4` to fix the issue that caused \$f(0)=f(8)\$. This does not generate a spiral anymore but works for all non-negative integers \$\mathbb{N}^0\$ (all natural numbers including \$0\$). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` Þn:Ẋi ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLDnm464bqKaSIsIiIsIjUiXQ==) ``` Þn # All integers :Ẋ # Cartesian product with self i # Index input into that ``` [Answer] # JavaScript, ~~77~~ 70 bytes ``` Z=x=>(x&1n?x:-x)/2n f=(x,y=1n)=>++x&1n?[Z(++x/2n),Z(y)]:f(x/2n-1n,++y) ``` Takes a BigInt as Input. [Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGCpaUlaboWN92ibCts7TQq1Azz7CusdCs09Y3yuNJsNSp0Km0N8zRt7bS1wXLRURpAFlBSUydKo1Iz1ipNA8TTNczT0dau1ISapp2WX6SRk1qikG1rkGedbWNkCiS1tTW5FBSS8_OK83NS9XLy0zXSNLI1oVpgDgEA) First few values: ``` f(0n)=[0n,0n] f(1n)=[0n,-1n] f(2n)=[-1n,0n] f(3n)=[0n,1n] f(4n)=[1n,0n] f(5n)=[-1n,-1n] ... ``` Explanation: Uses more or less the same algorithm as [Wislaw's solution](https://codegolf.stackexchange.com/questions/48705/generate-a-pair-of-integers-from-a-non-negative-one/178920#178920): `Z` is the standard bijection from the positive integers to the integers. `f` computes positive integers `k` and `m` with `x+1=2^(k-1)*(2m-1)` (which is a bijection \$\mathbb{N} \to \mathbb{N}\_{>0} \times \mathbb{N}\_{>0}\$ by the uniqueness of prime factorizations) and then outputs the pair `Z(m),Z(k)` --- # JavaScript, 65 bytes bijection \$\mathbb{N}\_{>0} \to \mathbb{Z} \times \mathbb{Z}\$ ``` Z=x=>(x&1n?x:-x)/2n f=(x,y=1n)=>x&1n?[Z(++x/2n),Z(y)]:f(x/2n,++y) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGCpaUlaboWNx2jbCts7TQq1Azz7CusdCs09Y3yuNJsNSp0Km0N8zRt7cAy0VEa2toVQClNnSiNSs1YqzQNEE9HW7tSE2qQdlp-kUZOaolCNlCfdbaNkSmQ1NbW5FJQSM7PK87PSdXLyU_XSNPI1oRqgbkBAA) [Answer] # [Scala](http://www.scala-lang.org/), 79 bytes Port of [@ბიმო's Haskell answer](https://codegolf.stackexchange.com/a/169708/110802) in Scala. --- Golfed version. [Try it online!](https://tio.run/##XU@xboNADN3zFU9RhjsJUJKRFqSOGTpFVYeI4QomcXs96OFWpBHfTo9Tpg6237Of5eehNtbM3ds71YJnww63FdBQi89AlPHnIceT9@Z6Oopnd650jhfHgiIqgR9j0eYHJ0V5cA2N1Bzp67SECs0EIemqQjG7omw7f@PHdAvp4B7GO@LpymQbhB2lxoTTUSehjuku5YBC@UcWhZ7j9VbttzprrREhl/1y/8pyiT4yMR@k9rsw7TyZ@nL3C9RmICj57i0l4EWrUZTow3tinRrWm9jMsYmatY5702qJaf4D) ``` n=>for{i<-0 to n;x<-0 to i}yield Seq((x,i-x),(x,x-1-i),(-1-x,x-1-i),(-1-x,i-x)) ``` Ungolfed version. [Try it online!](https://tio.run/##dY9BS8NAEIXv@RWP0sMuNKHtMVjBo6AnEQ/iYUwm7eq6CbtTSZX@9ri7Kb15ePDm483wJjRkaZr69w9uBI9kHH4LoOUOX3FQ5Pehxp33dHp9Em/c/k3XeHZGsMtJ4JssPIejTajr/QUDBjcl1pAe2/UFjVdkMjnjZNi2eDBBlBpXcafEqFdIfox@E2XSXCb3H5y3dJFvzl2qzpIIu@rHDC9GDveu5bES@mS13egq9mRqDteuDQWGkuNgOZ5LWY3dLYb4sVinwmKZYY1lziz0XL9IOhfT9Ac) ``` object Main { def main(args: Array[String]): Unit = { val result = for { i <- 0 to 20 x <- 0 to i } yield List((x, i - x), (x, x - 1 - i), (-1 - x, x - 1 - i), (-1 - x, i - x)) result.flatten.zipWithIndex.take(21).foreach { case (tuple, index) => println(s"$index: $tuple") } } } ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 48 bytes ``` f=(x,y)=>x&1?f(x/2,-~y):[x/2,y].map(t=>t/2^-t%2) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGCpaUlaboWNw3SbDUqdCo1be0q1Azt0zQq9I10dOsqNa2iQazKWL3cxAKNElu7En2jON0SVSNNqD7NtPwijZzUEoVsWwPrbBsjU-tsbW1NLgWF5Py84vycVL2c_HSNNI1sTagGmIUA) [Answer] # Mathematica, 46 ``` SortBy[Tuples[Range[2#]-#,2],Norm][[#]]&[#+1]& ``` Sort the vectors their norm, then take the `n`th one. ]
[Question] [ Your program must find all the words in [this wordlist](http://www.mieliestronk.com/wordlist.html) that contain all the vowels (`a e i o u y`). There are easy ways to do this, but I am looking for the shortest answer. I will take any language, but I'd like to see Bash. Here is an example (could be much improved): ``` cat wordlist.txt | grep "a" | grep "e" | grep "i" | grep "o" | grep "u" | grep "y" ``` Your score is the length of the code. -5 points for counting all occurrences of the word. Lowest score wins. [Answer] ### GolfScript, 19 characters ``` n%{'aeiouy'&,6=},n* ``` Usage: ``` golfscript vowels.gs < wordlist.txt ``` Output: ``` abstemiously authoritatively behaviourally [...] uninformatively unintentionally unquestionably unrecognisably ``` If you also want to output the count at the end you can use ``` n%{'aeiouy'&,6=},.n*n@, ``` which is four characters longer. [Answer] ## Python - 46 characters ``` filter(lambda x:set(x)>=set("AEIOUY"),open(f)) ``` Readable version: It's already pretty readable :-) [Answer] # APL, 21 - 5 = 16 ``` (,≢)w/⍨∧⌿'aeiouy'∘.∊w ``` Expects to find the list of words as `w`. Returns a list of the words that contain all the vowels, plus their count. Tested with [ngn apl](https://github.com/ngn/apl). Here's [an example](http://ngn.github.io/apl/web/index.html#code=w%u2190%27doge%27%20%27behaviourally%27%20%27wow%27%20%27unintentionally%27%20%27much%27%0A%28%2C%u2262%29w/%u2368%u2227%u233F%27aeiouy%27%u2218.%u220Aw). **Explanation** ``` 'aeiouy'∘.∊w # generate a truth table for every vowel ∊ every word ∧⌿ # reduce with ∧ along the rows (vowels) w/⍨ # select the words that contain all the vowels (,≢) # hook: append to the list its own tally ``` [Answer] ## Ruby 38 Edit 34: Best so far (from @O-I): ``` a.split.select{|w|'aeiouy'.count(w)>5} ``` Edit 1: I just noticed the question asked for 'y' to be included among the vowels, so I've edited my question accordingly. As @Nik pointed out in a comment to his answer, `"aeiouy".chars` is one character less than `%w[a e i o u y]`, but I'll leave the latter, for diversity, even though I'm risking nightmares over the opportunity foregone. Edit 2: Thanks to @O-I for suggesting the improvement: ``` s.split.select{|w|'aeiouy'.delete(w)==''} ``` which saves 11 characters from what I had before. Edit 3 and 3a: @O-I has knock off a few more: ``` s.split.select{|w|'aeiouy'.tr(w,'')==''} ``` then ``` s.split.reject{|w|'aeiouy'.tr(w,'')[1]} ``` and again (3b): ``` a.split.select{|w|'aeiouy'.count(w)>5} ``` I am a mere scribe! Here are two more uncompettive solutions: ``` s.split.group_by{|w|'aeiouy'.delete(w)}[''] (43) s.gsub(/(.+)\n/){|w|'aeiouy'.delete(w)==''?w:''} (48) ``` Initially I had: ``` s.split.select{|w|(w.chars&%w[a e i o u y]).size==6} ``` `s` is a string containing the words, separated by newlines. An array of words from `s` that contains all five vowels is returned. For readers unfamiliar with Ruby, `%w[a e i o u y] #=> ["a", "e", "i", "o", "u", "y"]` and `&` is array intersection. Suppose ``` s = "abbreviations\nabduction\n" s.split #=> ["abbreviations", "abduction"] ``` In the block `{...}`, initially ``` w #=> "abbreviations" w.chars #=> ["a", "b", "b", "r", "e", "v", "i", "a", "t", "i", "o", "n", "s"] w.chars & %w[a e i o u y] #=> ["a", "e", "i", "o"] (w.chars & %w[a e i o u y]).size == 6 #=> (4 == 6) => false, ``` so "abbreviations" is not selected. If the string `s` may contain duplicates, `s.split.select...` can be replaced by `s.split.uniq.select...` to remove duplicates. Just noticed I could save 1 char by replacing `size==6` with `size>5`. [Answer] # GolfScript, 20 chars − 5 = 15 points ``` n%{'aeiouy'\-!},.,+` ``` Based on [Howard's solution](https://codegolf.stackexchange.com/a/20950), but using a shorter test (`\-!` saves one char over `&,6=`), shorter length-appending (`.,+` = 3 chars) and shorter output formatting (nobody said the output had to be newline-separated, so ``` saves one char over `n*`). Here's the output, given the lowercase word list as input (linebreaks inserted for readability): ``` ["abstemiously" "authoritatively" "behaviourally" "consequentially" "counterrevolutionary" "disadvantageously" "educationally" "encouragingly" "eukaryotic" "evolutionarily" "evolutionary" "exclusionary" "facetiously" "gregariously" "heterosexuality" "homosexuality" "importunately" "inconsequentially" "instantaneously" "insurrectionary" "intravenously" "manoeuvrability" "neurologically" "neurotically" "ostentatiously" "pertinaciously" "precariously" "precautionary" "questionably" "revolutionary" "simultaneously" "supersonically" "tenaciously" "uncomplimentary" "uncontroversially" "unconventionally" "undemocratically" "unemotionally" "unequivocally" "uninformatively" "unintentionally" "unquestionably" "unrecognisably" 43] ``` (Ps. Technically, given that the challenge only says the code has to work for this specific input, `n%{'aeiouy'\-!},`43` would be one character shorter yet. I consider that cheating, though.) --- ### Explanation: * `n%` splits the input on newlines into an array. * `{ },` is a "grep" operator, executing the code between the braces for each element of the array and selecting those for which it returns a true value. + Inside the loop, `'aeiouy'\-` takes the literal string `aeiouy` and removes from it every character found in the candidate word. The `!` then logically negates the resulting string, yielding `1` (true) if the string is empty and `0` (false) if it's not. * `.,+` makes a copy of the filtered array, counts the number of words in it, and appends the result to the original array. * Finally, ``` un-evals the array, converting it into a string representation of its contents. (Without it, the words in the array would simply be concatenated in the output, yielding an unreadable mess.) [Answer] # Haskell - 67 ``` main=interact$unlines.filter(and.flip map "aeiouy".flip elem).lines ``` [Answer] # Ruby - 28 characters (or 27 if `y` is excluded from vowels) ``` ("ieaouy".chars-s.chars)==[] ``` The complete command to run is (48 chars): ``` ruby -nle 'p $_ if ("ieaouy".chars-$_.chars)==[]' ``` EDIT: replaced `puts` with `p` as suggested by @CarySwoveland [Answer] # AWK - 29 ``` /a/&&/e/&&/i/&&/o/&&/u/&&/y/ ``` To run: Save the lowercase word list to `wordlist.txt`. Then, do: ``` mawk "/a/&&/e/&&/i/&&/o/&&/u/&&/y/" wordlist.txt ``` If your system does not have `mawk`, `awk` can be used as well. You can also run it from a file by saving the program to `program.awk` and doing `mawk` or `awk` `-f program.awk`. [Answer] ## Python, 45 characters ``` [w for w in open(f) if set('aeiouy')<=set(w)] ``` [Answer] # k [22-5=17 chars] I have renamed the file "corncob\_lowercase.txt" to "w" ## Count the words [22 chars] ``` +/min'"aeiouy"in/:0:`w ``` ### Output ``` 43 ``` ## Find all words [25 chars] ``` x@&min'"aeiouy"in/:x:0:`w ``` Overall 43 words containing all the vowels `(a e i o u y)` ### Output ``` "abstemiously" "authoritatively" "behaviourally" .. .. "unintentionally" "unquestionably" "unrecognisably" ``` [Answer] # Javascript/JScript 147(152-5), 158(163-5) or 184(189-5) bytes: Here is my Javascript and JScript horribly "ungolfyfied" version (~~164~~ ~~152~~ 152-5=147 bytes): ~~`function(s,k,z,x,i,c,r){c='aeiouy'.split('');r=[];for(k in s=(s+'').split(/\b/)){i=0;for(z in c)i+=s[k].indexOf(c[z])>=0;i==6&&(r[r.length]=s[k]);}return r;}`~~ `function(s,k,z,x,i,c,r){c='aeiouy'.split('');r=[];for(k in s=(s+'').split(/\b/)){i=6;for(z in c)i-=!!s[k].search(c[z]);i&&(r[r.length]=s[k]);}return r;}` Thank you @GaurangTandon for the `search()` function, which saved me a byte! RegExp based with **HORRIBLE** performance, but support both upper and lowercase (163-5=158 bytes): `function(s,k,z,x,i,c,r){c='aeiouy'.split('');r=[];for(k in s=(s+'').split(/\b/)){i=0;for(z in c)i+=RegExp(c[z],'i').test(s[k]);i==6&&(r[r.length]=s[k]);}return r;}` RegExp based with **BETTER** performance, **BUT** takes a lot more bytes (189-5=184 bytes): `function(s,k,z,x,i,c,r,l){l=[];r=[];for(z in c='aeiouy'.split(''))l[z]=RegExp(c[z],'i');for(k in s=(s+'').split(/\b/)){i=0;for(z in c)i+=l[z].test(s[k]);i==6&&(r[r.length]=s[k]);}return r;}` --- This one if just for the fun (175-5 bytes) and won't count as an answer: `function(s,k,z,x,i,c,r){c='aeiouy'.split('');r=[];for(k in s=(s+'').split(/\b/)){i=0;for(z in c)i+=s[k].indexOf(c[z])>=0;i==6&&(r[r[r.length]=s[k]]=1+(r[s[k]]||0));}return r;}` It's based on the 1st answer, but has a 'twist': You can know how many times a word has been found. You simply do like this: `var b=(function(s,k,z,x,i,c,r){c='aeiouy'.split('');r=[];for(k in s=(s+'').split(/\b/)){i=0;for(z in c)i+=s[k].indexOf(c[z])>=0;i==6&&(r[r[r.length]=s[k]]=1+(r[s[k]]||0));}return r;})('youaie youaie youaie youaie a word');` `b.youaie //should be 4` Since that `length` doesn't have all vowels, it wont be deleted and still would be an answer for the bonus. --- How do you call it? "Simple": You wrap the function inside `()` and then add `('string goes here');` to the end. Like this: `(function(s,k,z,x,i,c,r){c='aeiouy'.split('');r=[];for(k in s=(s+'').split(/\b/)){i=0;for(z in c)i+=s[k].indexOf(c[z])>=0;i==6&&(r[r.length]=s[k]);}return r;})('a sentence youyoy iyiuyoui yoiuae oiue oiuea');` This example will return an array only with 1 string: yoiuae I know that this is the worst solution, but works! --- Why am i counting -5? Well, Javascript/JScript arrays have a property (`length`) in arrays which tells the number of elements that it have. After being confirmed in the question, the bonus of -5 is for telling the number of words. Since the number of words is in that property, automatically I have the score of -5. [Answer] # Ruby ~~39~~ 38 Currently the shortest Ruby entry when counting the **whole program** including input and output. Saved a char by using `map` instead of `each`: ``` $<.map{|w|w*5=~/a.*e.*i.*o.*u/m&&p(w)} ``` Another version, 39 characters with prettier output: ``` puts$<.select{|w|w*5=~/a.*e.*i.*o.*u/m} ``` Both programs take input from stdin or as a file name passed as a command line argument: `$ ruby wovels.rb wordlist.txt` It costs 3 extra characters to inclyde `y` as a wovel. [Answer] ## Mathematica (65 or 314) Two very different approaches, the better one was proposed by Belisarius in the comments to my initial response. First, my brutish effort, which algorithmically generates every possible regular expression that matches a combination of six vowels (including "y"), and then checks every word in the target wordlist against every one of these 720 regular expressions. It works, but it's not very concise and it's slow. ``` b = Permutations[{"a", "e", "i", "o", "u","y"}]; Table[ Select[StringSplit[ URLFetch["http://www.mieliestronk.com/corncob_lowercase.txt"]], StringMatchQ[#, (___ ~~ b[[i]][[1]] ~~ ___ ~~ b[[i]][[2]] ~~ ___ ~~ b[[i]][[3]] ~~ ___ ~~ b[[i]][[4]] ~~ ___ ~~ b[[i]][[5]]~~ ___ ~~ b[[i]][[6]] ~~ ___)] &], {i, 1, Length[b]}] ``` ~320 characters. A few could be saved through using alternate notation, and additional characters are lost preparing the dictionary file as a list of strings (the natural format for the dictionary in Mathematica. Other languages may not need this prep, but Mathematica does). If we omit that step, presuming it to have been handled for us, the same approach can be done in under 250 characters, and if we use Mathematica's built-in dictionary, we get even bigger savings, ``` Map[DictionaryLookup[(___ ~~ #[[1]] ~~ ___ ~~ #[[2]] ~~ ___ ~~ #[[3]] ~~ ___ ~~ #[[4]] ~~ ___ ~~ #[[5]]~~ ___ ~~ #[[6]] ~~ ___) .., IgnoreCase -> True] &, Permutations[{"a", "e", "i", "o", "u","y"}]] ``` Under 200 characters. Counting the number of words found requires only passing the result to `Length[Flatten[]]`, which can be added around either block of code above, or can be done afterwards with, for example, `Length@Flatten@%`. The wordlist specified for this challenge gives 43 matches, and the Mathematica dictionary gives 64 (and is much quicker). Each dictionary has matching words not in the other. Mathematica finds "unprofessionally," for example, which is not in the shared list, and the shared list finds "eukaryotic," which is not in Mathematica's dictionary. Belisarius proposed a vastly better solution. Assuming the wordlist has already been prepared and assigned to the variable `l`, he defines a single test based on Mathematica's `StringFreeQ[]` function, then applies this test to the word list using the `Pick[]` function. 65 characters, and it's about 400 times faster than my approach. ``` f@u_ := And @@ (! StringFreeQ[u, #] & /@ Characters@"aeiouy"); Pick[l,f /@ l] ``` [Answer] # Perl 6 - 35 characters Inspired by @CarySwoveland 's Ruby solution: ``` say grep <a e i o u y>⊆*.comb,lines ``` This selects (`grep`s) each line that returns `True` for `<a e i o u y> ⊆ *.comb`, which is just a fancy way of asking "is the Set `('a','e','i','o','u','y')` a subset (`⊆`) of the Set made up of the letters of the input (`*.comb`)?" Actually, both `<a e i o u y>` and `*.comb` only create `List`s: `⊆` (or `(<=)` if you're stuck in ASCII) turns them into `Set`s for you. To get the number of lines printed, this **42 character - 5 = 37 point** script will output that as well: ``` say +lines.grep(<a e i o u y>⊆*.comb)».say ``` [Answer] ## C - 96 bytes ``` char*gets(),*i,j[42];main(p){while(p=0,i=gets(j)){while(*i)p|=1<<*i++-96;~p&35684898||puts(j);}} ``` I saved several bytes of parentheses thanks to a fortunate coincidence of operator precedence. [Answer] # Javascript - Score = 124 - 5 = 119 !!! ### Edit: 17/02/14 ``` function(l){z=[],l=l.split("\n"),t=0;while(r=l[t++]){o=0;for(i in k="aeiouy")o+=!~r.search(k[i]);if(o==0)z.push(r)}return z} ``` Big thanks to @Ismael Miguel for helping me cut off **~12 chars**! I removed the fat arrow notation function form because though I have seen it begin used, it doesn't work. No idea why... --- ### To make it work: Pass all the words separated by newline as an argument to the function as shown below. --- ### Test: ``` // string is "facetiously\nabstemiously\nhello\nauthoritatively\nbye" var answer = (function(l){z=[],l=l.split("\n"),t=0;while(r=l[t++]){o=0;for(i in k="aeiouy")o+=!~r.search(k[i]);if(o==0)z.push(r)}return z})("facetiously\nabstemiously\nhello\nauthoritatively\nbye") console.log(answer); console.log(answer.length); /* output -> ["facetiously", "abstemiously", "authoritatively"] 3 // count */ ``` --- [Answer] # Bash + coreutils, 39 ``` eval cat`printf "|grep %s" a e i o u y` ``` Takes input from stdin. [Answer] ### sed 29 chars ``` /y/{/u/{/o/{/i/{/a/{/e/p}}}}} ``` Order choosed from [Letter frequency on wikipedia](http://en.wikipedia.org/wiki/Letter_frequency) to speed check. On my host: ``` time sed -ne '/a/{/e/{/i/{/o/{/u/{/y/p}}}}}' </usr/share/dict/american-english >/dev/null real 0m0.046s ``` and ``` time sed -ne '/y/{/u/{/i/{/o/{/a/{/e/p}}}}}'</usr/share/dict/american-english >/dev/null real 0m0.030s ``` [Answer] ## Bash (grep) - 36 bytes ``` g=grep;$g y|$g u|$g o|$g i|$g a|$g e ``` Note the order of vowels tested, least frequent first. For the test case, this runs about 3 times as fast as testing in order a e i o u y. That way the first test removes a larger number of words so subsequent tests have less work to do. Obviously this has no effect on the length of the code. Many of the other solutions posted here would benefit similarly from doing the tests in this order. [Answer] ## D - 196 ``` import std.regex,std.stream;void main(string[]a){auto f=new File(a[1]);while(!f.eof)if(!(a[0]=f.readLine.idup).match("(?=.*a)(?=.*e)(?=.*i)(?=.*o)(?=.*u)(?=.*y).*").empty)std.stdio.writeln(a[0]);} ``` **Un-golfed**: ``` import std.regex, std.stream; void main( string[] a ) { auto f = new File( a[1] ); while( !f.eof ) if( !( a[0] = f.readLine.idup ).match( "(?=.*a)(?=.*e)(?=.*i)(?=.*o)(?=.*u)(?=.*y).*" ).empty ) std.stdio.writeln( a[0] ); } ``` **Usage**: `C:\>rdmd vowels.d wordlist.txt` `wordlist.txt` must contain the lowercase list words. [Answer] # Rebol (104 chars) ``` remove-each w d: read/lines %wordlist.txt[6 != length? collect[foreach n"aeiouy"[if find w n[keep n]]]] ``` ### Un-golfed: ``` remove-each w d: read/lines %wordlist.txt [ 6 != length? collect [foreach n "aeiouy" [if find w n [keep n]]] ] ``` `d` now contains list of found words. Here is an example from Rebol console: ``` >> ; paste in golf line. This (REMOVE-EACH) returns the numbers of words removed from list >> remove-each w d: read/lines %wordlist.txt[6 != length? collect[foreach n"aeiouy"[if find w n[keep n]]]] == 58067 >> length? d == 43 ``` [Answer] # Smalltalk (36/57 chars) ``` 'corncob_lowercase.txt' asFilename contents select:[:w | w includesAll:'aeiouy'] ``` to get the count, send #size to the resulting collection. The result collection contains 43 words ('abstemiously' 'authoritatively' ... 'unquestionably' 'unrecognisably') The code above has 77 chars, but I could have renamed the wordlist file to 'w', so I count the filename as 1 which gives a score of 57. Is reading the file part of the problem or not? If not (see other examples), and the list of words is already in a collection c, then the code reduces to: ``` c select:[:w | w includesAll:'aeiouy'] ``` which is 36 chars (with omittable whitespace removed). [Answer] updated: unnecessary spaces removed Very slow but in bash (81 chars): ``` while read l;do [ `fold -w1<<<$l|sort -u|tr -dc ieaouy|wc -m` = 6 ]&&echo $l;done ``` EDIT: `echo $l|fold -w1` replaced with `fold -w1<<<$l` as suggested by @nyuszika7h [Answer] # JavaScript - 95 bytes Here's my golf. ``` function f(s){return[var a=s.match(/^(?=.*a)(?=.*e)(?=.*i)(?=.*o)(?=.*u)(?=.*y).*/),a.length];} ``` And I would also like to point out that your golf doesn't seem to find all occurrences of vowels. Ungolfed: ``` function countVowels(string) { var regex = /^(?=.*a)(?=.*e)(?=.*i)(?=.*o)(?=.*u)(?=.*y).*/; var matches = string.match(regex); var length = matches.length; return [matches, length]; ``` [Answer] # sort + uniq + sed This one does not match repeated occurrences of a word. It also does not match the letter 'y' if is occurs at the beginning of a word. ``` sort wordlist.txt | uniq | sed -n '/a/p' | sed -n '/e/p' | sed -n '/i/p' | sed -n '/o/p' | sed -n '/u/p' | sed -nr '/^[^y]+y/p' ``` [Answer] # Bash Not as short as the OP's , but one line in Bash: ``` while read p; do if [ $(sed 's/[^aeiouy]//g' <<< $p | fold -w1 | sort | uniq | wc -l) -eq 6 ] ; then echo $p; fi; done < wordlist.txt ``` [Answer] # C# - 170 ``` using System.Linq;class P{static void Main(string[]a){System.Console.Write(string.Join(",",System.IO.File.ReadAllLines(a[0]).Where(w=>"aeiouy".All(c=>w.Contains(c)))));}} ``` Formatted: ``` using System.Linq; class P { static void Main(string[] a) { System.Console.Write( string.Join(",", System.IO.File.ReadAllLines(a[0]) .Where(w => "aeiouy".All(c => w.Contains(c))))); } } ``` ~~Not in the mood right now to implement counting ![puh](https://i.stack.imgur.com/qkavd.gif) but should be easy.~~ The path to the (lower-case version of the) wordlist should be passed to the program as first argument: ``` program.exe D:\foo\bar\corncob_lowercase.txt ``` **Output:** ``` abstemiously,authoritatively,behaviourally,consequentially,counterrevolutionary, disadvantageously,educationally,encouragingly,eukaryotic,evolutionarily,evolutio nary,exclusionary,facetiously,gregariously,heterosexuality,homosexuality,importu nately,inconsequentially,instantaneously,insurrectionary,intravenously,manoeuvra bility,neurologically,neurotically,ostentatiously,pertinaciously,precariously,pr ecautionary,questionably,revolutionary,simultaneously,supersonically,tenaciously ,uncomplimentary,uncontroversially,unconventionally,undemocratically,unemotional ly,unequivocally,uninformatively,unintentionally,unquestionably,unrecognisably ``` I took the liberty of outputting and comma-separating the words; neither of which is specified in the rules (which state "must find all the words", not how (and IF) to output). ## Including count (+output): 192 - 5 = 187 ``` using System.Linq;class P{static void Main(string[]a){var r=System.IO.File.ReadAllLines(a[0]).Where(w=>"aeiouy".All(c=>w.Contains(c)));System.Console.Write(string.Join(",",r)+" "+r.Count());}} ``` Output: ``` abstemiously,authoritatively,behaviourally,consequentially,counterrevolutionary, disadvantageously,educationally,encouragingly,eukaryotic,evolutionarily,evolutio nary,exclusionary,facetiously,gregariously,heterosexuality,homosexuality,importu nately,inconsequentially,instantaneously,insurrectionary,intravenously,manoeuvra bility,neurologically,neurotically,ostentatiously,pertinaciously,precariously,pr ecautionary,questionably,revolutionary,simultaneously,supersonically,tenaciously ,uncomplimentary,uncontroversially,unconventionally,undemocratically,unemotional ly,unequivocally,uninformatively,unintentionally,unquestionably,unrecognisably 4 3 ``` (Note the count at the end: 43) ## No output ("must *find* all the words"): 137 - 5 = 132 ``` using System.Linq;class P{static void Main(string[]a){var r=System.IO.File.ReadAllLines(a[0]).Where(w=>"aeiouy".All(c=>w.Contains(c)));}} ``` (Bending the rules a bitm then again: not really) This **finds** all the words and the count is available by executing `r.Count()`. [Answer] ## C-Sharp I've never done this before and I'm not exactly sure what the posting procedures are. But this is what i came up with: ## 185 bytes ``` Action<string>x=(s=>s.Split('\n').ToList().ForEach(w=>{if("aeiouy".All(v=>w.Contains(v)))Console.Write(w);}));using(var s=new StreamReader(@"C:\corncob_lowercase.txt"))x(s.ReadToEnd()); ``` `wordList` = a `List<string>` of all the words. if you want to display a total: ## 219 - 5 = 214 bytes ``` Action<string>x=(s=>{var t=0;s.Split('\n').ToList().ForEach(w=>{if("aeiouy".All(v=>w.Contains(v))){Console.Write(w);t++;}});Console.Write(t);});using(var s=new StreamReader(@"C:\corncob_lowercase.txt"))x(s.ReadToEnd()); ``` --- **Expanded** ``` // init var words = ""; var vowels = "aeiouy"; var total = 0; using (var stream = new StreamReader(@"C:\corncob_lowercase.txt")) { // read file words = stream.ReadToEnd(); // convert word to List<string> var wordList = words.Split('\n').ToList(); // loop through each word in the list foreach (var word in wordList) // check if the current word contains all the vowels if(vowels.All (w => word.ToCharArray().Contains(w))) { // Count total total += 1; // Output word Console.Write(word); } // Display total Console.WriteLine(total); } ``` [Answer] **vb.net** (Score 91 = 96c - 5)\*0 \*0 +49c min This creates an enumeration contain all of the words which contain all of the vowels. ``` Dim r=IO.File.ReadLines(a(0)).Where(Function(w)"aeiou".Intersect(w).Count=5) Dim c=r.Count ``` [Answer] # Mathematica - ~~136~~ 102 ``` Fold[Flatten@StringCases@## &, Flatten@Import@"http://bit.ly/1iZE9kY", ___ ~~ # ~~ ___ & /@ Characters@"aeiouy"] ``` The shortened link goes to <http://www.mieliestronk.com/corncob_lowercase.txt> ]
[Question] [ The [Reuleaux triangle](http://mathworld.wolfram.com/ReuleauxTriangle.html) is the shape formed by the intersection of three circles, with each circle passing through the others' centers. Regardless of rotation, a Reuleaux triangle's width will always equal the radius of the circles: [![From Wolfram MathWorld](https://i.stack.imgur.com/I9rVr.gif)](https://i.stack.imgur.com/I9rVr.gif) Image: [Wolfram MathWorld](http://mathworld.wolfram.com/ReuleauxTriangle.html) Write a program that takes a width `r` as input and displays a Reuleaux triangle of that width (in pixels). You must display the shape in isolation, i.e. solid-filled, un-stroked, and over a solid-filled background. [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") - Shortest program in bytes wins. [Answer] ## JavaScript + HTML, ~~164~~ 158 + 13 = 171 bytes ``` w=+prompt(f=(x,y)=>x*x+y*y<w*w);C.width=C.height=w*2;for(y=-w;++y<w;)for(x=-w;++x<w;)f(x,y)&f(w-x,y)&f(w/2-x,y-w*.866)&&C.getContext`2d`.fillRect(x+w,y+w,1,1) ``` ``` <canvas id=C> ``` I don't know why I enjoy answering these mathy drawing challenges with `<canvas>` so much... [Answer] # Love2D, 320 bytes. ``` j=math.rad(60)i="increment"m=math s=m.sin C=m.cos g=love.graphics f="fill"S=g.stencil function love.draw()r=arg[2]c=function(x,y)return function()g.circle(f,x,y,r,r*4)end end X=r/2 Y=0 S(c(X,Y),i,1)S(c(X+C(j)*r,Y+s(j)*r),i,1,true)S(c(X-C(j)*r,Y+s(j)*r),i,1,true)g.setStencilTest("greater",2)g.rectangle(f,0,0,2*r,2*r)end ``` Probably not the optimal solution, it uses Love2D's stencils, setting up the 3 circles, and filling in over where they intersect. Call via the command line, like `love tri.love 256` ## Example Output ![](https://i.stack.imgur.com/YyFMK.png) [Answer] # [Python 2](https://docs.python.org/2/), 111 bytes ``` from turtle import* r=input() ht() begin_fill() c=circle c(r,60) seth(120) c(r,60) seth(240) c(r,60) end_fill() ``` [![example run](https://i.stack.imgur.com/xAYhH.gif)](https://i.stack.imgur.com/xAYhH.gif) [Answer] ## Mathematica ~~101~~ ~~100~~ 98 Bytes Taking a different approach than @MichaelSeifert, and probably interpreting this a little more literally with regard to the pixel clause: ``` Image@Boole@Table[And@@(({x,y}∈#~Disk~2)&/@{{0,c=√3},d={1,0},-d}),{x,-1,1,2/#},{y,c-2,c,2/#}]& ``` Usage Example: ``` %@10 ``` 10 pixels [![10 pixel image](https://i.stack.imgur.com/BSgV4.png)](https://i.stack.imgur.com/BSgV4.png) 50 pixels [![50 pixel image](https://i.stack.imgur.com/zB8q9.png)](https://i.stack.imgur.com/zB8q9.png) 100 pixels [![100 pixel image](https://i.stack.imgur.com/1Mtir.png)](https://i.stack.imgur.com/1Mtir.png) Saved a byte thanks to @MartinEnder (infix notation) and another 2 bytes by defining d. [Answer] ## PostScript, ~~96~~ ~~86~~ ~~85~~ ~~75~~ ~~73~~ 72 bytes ``` dup(^@^^Z<^@Z<){sin mul exch dup}forall 0 1 2{newpath 369 arc clip}for fill ``` Takes the input as a value on the stack. `^^` and `^@` represent literal control characters. `(^@^^Z<^@Z<)` is the string of characters with code points 0, 30, 90, 60, 0, 90, and 60, respectively. Those are then interpreted as angles in degrees, because obviously that’s what code points are for. Saved 10 bytes because `closepath` isn’t needed (both `clip` and `fill` implicitly close the path). Saved 1 byte by using `repeat` instead of defining a function. Saved 10 bytes by switching to a completely different approach. Saved 2 bytes by doing tricks with the stack. Saved 1 byte by using `0 1 2{}for` instead of `3{}repeat`. [Answer] # PHP+SVG, 165 bytes ``` <?$h=3/8*$w=2*$d=2*$r=$_GET[0];$q=$r+sqrt($r**2-($r/2)**2);echo"<svg width=$w height=$w><path d='M$r,$r A$r,$r 0 0 1 $d,$r A$r,$r 0 0 1 $h,$q A$r,$r 0 0 1 $r,$r'/>"; ``` ## Example Output for Input 128 ``` <svg width=512 height=512><path d='M128,128 A128,128 0 0 1 256,128 A128,128 0 0 1 192,238.85125168441 A128,128 0 0 1 128,128'/> ``` [Answer] ## TeX/TikZ, ~~128~~ ~~121~~ 112 bytes ``` \input tikz\footline{}\tikz\draw[draw=none,fill=red](0,1)\foreach~ in{1,2,3}{[rotate=~*120]arc(0:60:\r pt)};\bye ``` The code is based on [this answer at TeX.se](https://tex.stackexchange.com/a/160705/28808). TeX is vector-based, so doesn't do pixels. The radius is a float with a maximum of about 15 before it hits the edge of the page. It's also not really built for commandline input, so need to be run as ``` pdftex "\def\r{2} \input rt.tex" ``` where the code above is saved in `rt.tex` [Answer] ## Mathematica, ~~134~~ 131 bytes **N.B.** This solution is no longer valid, as the question was later edited to require *r* to be measured in pixels. Thanks to Martin Ender for helping me shave off a few bytes in the comments. ``` r=Input[];RegionPlot[And@@((Abs[y+I x-#]^2<3r^2)&/@Table[Exp[2n I/3Pi]r,{n,3}]),{x,-1,1},{y,-1,1},Frame->False,BoundaryStyle->None] ``` [![enter image description here](https://i.stack.imgur.com/7wZx8.jpg)](https://i.stack.imgur.com/7wZx8.jpg) The input value must be scaled between 0 and 1 for this code to work. Note that almost a quarter of this code is required to display the shape "in isolation", as this is not Mathematica's default. [Answer] # BBC BASIC, 58 bytes ``` I.r:L.r,r,r,r:F.i=0TO9S.PI/1.5PLOT177,r*COS(i),r*SIN(i)N. ``` Download interpreter at <http://www.bbcbasic.co.uk/bbcwin/download.html> **Ungolfed** ``` INPUTr :REM input a radius LINEr,r,r,r :REM draw a line of length 0 from r,r to r,r to establish a cursor history away from the corner of the screen FORi=0 TO 9 STEP PI/1.5 :REM in steps of 120 degrees (going round and round the three sides of an equilateral triangle) PLOT177,r*COS(i),r*SIN(i) :REM move relative by r*COS(i),r*SIN(i) and draw a sector with arc between new and last graphics cursor positions, NEXT :REM with the centre of the arc at the penultimate graphics cursor position. ``` [Answer] ## GLSL, ~~298~~ 229 characters ``` precision lowp float; uniform vec2 resolution;float r=100.;void main(){vec2 p=gl_FragCoord.xy-resolution.xy/2.;float h=sqrt(3.)/4.*r;gl_FragColor=vec4(length(p+vec2(r/2.,h))<r&&length(p+vec2(-r/2.,h))<r&&length(p-vec2(0.,h))<r);} ``` [Try it here](http://glslsandbox.com/e#40956.5) [Bonus](http://glslsandbox.com/e#40956.7) * Radius can be set by changing `r` variable * Triangle width is in pixels as requested (you have to make zoom is set to 1x in GLSL sandbox). [Answer] ## [Java + `Processing`](http://openjdk.java.net/), 95 bytes ``` noStroke();arc(r,r,r,r,0,PI/3);arc(r+r/2,r,r,r,2*PI/3,PI);arc(r+r/4,r+r/2.3,r,r,4*PI/3,5*PI/3); ``` Takes input as variable r, outputs a Reuleaux triangle at \$(r,r)\$, given an adequately sized canvas. [Code](https://tio.run/##y0osS9TNL0jNy0rJ/v8/Lz@4pCg/O1VD0zqxKFmjSAcCDXQCPPWNoWLaRfpGUHEjLZA4UBIhZaIDVqBnDFZgAlFgqgXR//8/AA "Java (OpenJDK 8) – Try It Online") ### As a function with size call, 124 bytes ``` void a(int r){size(r*2,r*2);noStroke();arc(r,r,r,r,0,PI/3);arc(r+r/2,r,r,r,2*PI/3,PI);arc(r+r/4,r+r/2.3,r,r,4*PI/3,5*PI/3);} ``` ### Outputs 50 [![enter image description here](https://i.stack.imgur.com/2wHLh.png)](https://i.stack.imgur.com/2wHLh.png) 100 [![enter image description here](https://i.stack.imgur.com/4XsSO.png)](https://i.stack.imgur.com/4XsSO.png) 200 [![enter image description here](https://i.stack.imgur.com/b3CZO.png)](https://i.stack.imgur.com/b3CZO.png) [Answer] # JavaScript (ES6) + HTML, 196 + 13 = 209 bytes Uses a path-based approach instead of a pixel-filling approach. ``` r=>{c.width=c.height=r*2 with(Math)with(c.getContext`2d`)scale(e=r*.578,e),beginPath(a=s=>s*PI/3),moveTo(2,1),[2,4,6].map(s=>arcTo(cos(i=a(s-1))+1,sin(i)+1,cos(j=a(s))+1,sin(j)+1,sqrt(3))),fill()} ``` ``` <canvas id=c> ``` ``` f= r=>{c.width=c.height=r*2 with(Math)with(c.getContext`2d`)scale(e=r*.578,e),beginPath(a=s=>s*PI/3),moveTo(2,1),[2,4,6].map(s=>arcTo(cos(i=a(s-1))+1,sin(i)+1,cos(j=a(s))+1,sin(j)+1,sqrt(3))),fill()} f(200) //r=>{c.width=c.height=r*2 //with(Math)with(c.getContext`2d`)translate(r,r),scale(r,r),beginPath(a=s=>s*PI/3),S=sqrt(3),moveTo(1/S,0),[2,4,6].map(s=>arcTo(cos(i=a(s-1))/S,sin(i)/S,cos(j=a(s))/S,sin(j)/S,1)),fill()} //r=>{c.width=c.height=r*2 //with(Math)with(c.getContext`2d`)translate(r,r),scale(r,r),beginPath(),P=PI/2,A=(s,_)=>(_?sin:cos)(s*PI/3)/sqrt(3),moveTo(A(0),0),[2,4,6].map(s=>arcTo(A(s-1),A(s-1,1),A(s),A(s,1),1)),fill()} ``` ``` <canvas id=c> ``` [Answer] # Logo, 53 bytes ``` to t :r filled 0[repeat 3[arc 60 :r fd :r rt 120]]end ``` uses the `filled` command to fill the shape in colour 0 (black.) The code in the outer square brackets is executed without any line being drawn, but Logo keeps track of the turtle movements and fills in the shape once the bracket is exited. # Logo, ~~64~~ 61 bytes ``` to t :r repeat 3[pd arc 60 :r pu fd :r rt 120]fd 9 fill end ``` Pen Down, draw 60 degree arc with turtle at the centre, Pen Up, move pen to start of arc, turn 120 deg. Repeat 3 times, then move inside the shape and fill it. Try at <http://turtleacademy.com/playground/en> Call like `cs ht t 100` (clear screen, hide turtle, `t` with r=100.) [Answer] ## JavaScript (ES6) + SVG (HTML5), 28 + 102 = 130 bytes ``` f= n=>s.setAttribute('width',n) ``` ``` <input type=number value=82 oninput=f(this.value)><br> <svg id=s width=82 viewbox=0,0,82,82><path d=M0,71a82,82,0,0,0,82,0A82,82,0,0,0,41,0A82,82,0,0,0,0,71> ``` Byte count excludes code needed for convenient user input of desired size. [Answer] # [MATL](https://github.com/lmendo/MATL), 35 bytes ``` 9Bo&ZQ*3X^/G_G&:t!J*+8L&!-|G<A&e0YG ``` This produces a file called `image.png`. For input `r`, the size of the image is `2*r+1`, and the width of the triangle is `r` as required. Try it at [**MATL Online!**](https://matl.io/?code=9Bo%26ZQ%2a3X%5E%2FG_G%26%3At%21J%2a%2B8L%26%21-%7CG%3CA%26e0YG&inputs=100&version=20.1.1) The online interpreter automatically opens the created file and displays the image with arbitrary scaling; click on it to obtain the actual-size version. Alternatively, here are two example outputs from the offline compiler running on Matlab, with inputs `50` and `100`. The last part of the code `0YG` has been replaced by `IYG` so that the figure is directly displayed (with the right size) instead of written to a file. [![enter image description here](https://i.stack.imgur.com/LdB5L.png)](https://i.stack.imgur.com/LdB5L.png) ### Explanation ``` 9B % Push 9 in binary: [1 0 0 1] with logical values o % Convert to double &ZQ % Roots of polynomial with coefficients [1 0 0 1], as a 3×1 column vector * % Multiply by implicit input r 3X^/ % Divide by sqrt(3). This gives a 3×1 vector with the circle centers G_G&: % Push row vector [-r -r+1 ... r-1 r], with size 1×(2*r+1) t!J* % Duplicate, transpose, multiply by 1j + % Add with broadcast. This gives a (2*r+1)×(2*r+1) 2D-array of complex % numbers, which defines the pixel grid 8L % Push [3 1 2] &! % Permute dimensions as indicated. This gives a 1×(2*r+1)×(2*r+1) 3D-array -| % Subtract with broadcast. Absolute value. This gives a 3×(2*r+1)×(2*r+1) % 3D-array with the distance from each circle center to each grid point G< % Less than r? Gives a 3×(2*r+1)×(2*r+1) 3D-array containing true or false A % All: this gives a 1×(2*r+1)×(2*r+1) array containing true for % columns of the original 3D-array that contained all true values &e % Squeeze the first singleton dimension to give a (2*r+1)×(2*r+1) 2D-array 0YG % Save as image file with default file name ``` [Answer] # MetaPost (~~242~~ 226 Bytes) ``` outputtemplate:="%j-%c.ps"; prologues:=1 beginfig(1); len:=1cm; path p[]; p[1]:=len * dir -30 {dir 90} .. len * dir 90; p[2]:=p[1] rotated 120; p[3]:=p[1] rotated 240; fill p[1] -- p[2] -- p[3] -- cycle; endfig; end. ``` It may be possible to reduce this somewhat, I'm new to metapost. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 66 bytes ``` ’) ¨€(ÿ,60) lt(60’Ð’€š éà £Ø* ht() ï…_œã(ÿÿÿ) „–_œã() „ˆ 1:ht()’.e ``` Can't use TIO, since it opens a window and draws the Reuleaux triangle there. Asks for input, and then opens up a Python turtle window drawing the triangle. Jonathan Allan's answer gave me the inspiration to do this, although I altered his code a bit. Essentially, this is a combination of 05AB1E's compressing capabilities and Python's ease of turtle graphics. [Answer] # k, ~~141~~ ~~100~~ 98 bytes ``` s:*/2#;l:2*r:.:0:` `0:(,"P1")," "/'$(,l,l),&/{(s'n+x)</:(s r)-s'y+n:r-!l}./:r*%(0 0;4 0;1 3)%4 \\ ``` Input is taken from `stdin`, output is `stderr` (or `stdin` depending on the interpreter) in `pgm` format. For example: [![Example of the program working.](https://i.stack.imgur.com/0Qnai.png)](https://i.stack.imgur.com/0Qnai.png) Explanation: ``` s:*/2# /set s to a squaring function r:.:0:` /get user input, set to r l:2* /width/height is 2 times r r*%(0 0;4 0;1 3)%4 /the coordinates of circle centers { }./: /for each coordinate pair (x, y) get a circle /function to get a circle: n:r-!l / set n to {r, r-1, ..., -(r-1)} (s'n+x)</:(s r)-s'y+ / use b^2<r^2-a^2 on all points to get a circle / where x and y shift the circle right and down &/ /get intersections of circles (fold binary and) (,l,l), /prepend height and width for PGM format " "/'$ /convert to string, add spaces (,"P1"), /prepend PGM header `0: /output to stderr \\ /exit ``` [Answer] ## [OpenSCAD](http://www.openscad.org/), 91 bytes ``` module t(r){intersection_for(t=[0,120,240]){rotate(t)translate([r/sqrt(3),0,0])circle(r);}} ``` I'm not sure how kosher this is, as pixels aren't really a well-defined unit in any mesh grid formats that I know of. In stead, the module `t` draws a reuleaux triangle of given radius `r` in whatever native units are in use. Sample preview output for `t(100)`: ![t(100)](https://i.stack.imgur.com/MO8w4.png) [Answer] # SmileBASIC, ~~87~~ ~~86~~ ~~85~~ ~~83~~ ~~82~~ ~~81~~ ~~79~~ ~~78~~ ~~77~~ ~~76~~ 75 bytes ``` INPUT R C.5Y=R*.87C 1C.GPAINT.,0DEF C X A=X*240GCIRCLE R*X,Y+2,R,A-60,A END ``` ## Ungolfed: ``` INPUT RADIUS CIRCLE 0.5 Y=RADIUS*(SQR(3)/2) CIRCLE 1 CIRCLE 0 GPAINT 0,0 DEF CIRCLE X ANGLE=X*240 GCIRCLE RADIUS*X,Y+2,RADIUS,ANGLE-60,ANGLE END ``` ]
[Question] [ ## **21, 21, 23, 20, 5, 25, 31, 24, ?** Inspired by [this Puzzle](https://puzzling.stackexchange.com/questions/89656/what-is-the-next-number-in-the-series-21-21-23-20-5-25-31-24), given an integer \$n>0\$ , print out the following sequence until you reach a non-Integer (spoilered, in case you want to solve the puzzle yourself first) > > \$a\_0 = n\$ > > \$a\_{4k+1} = a\_{4k} \cdot(4k+1) \$ > > \$a\_{4k+2} = a\_{4k+1} + (4k+2)\$ > > \$a\_{4k+3} = a\_{4k+2} - (4k+3)\$ > > \$a\_{4k+4} = a\_{4k+3} / (4k+4)\$ > > > or more intuitively: \*1, +2, -3, /4, \*5, +6, -7, /8, ... > > > **TestCases:** > > 1: 1, 1, 3, 0, 0, 0, 6, -1 > > 2: 2, 2, 4, 1 > > 3: 3, 3, 5, 2 > > 4: 4, 4, 6, 3 > > 5: 5, 5, 7, 4, 1, 5, 11, 4 > > 6: 6, 6, 8, 5 > > 9: 9, 9, 11, 8, 2, 10, 16, 9 > > 21: 21, 21, 23, 20, 5, 25, 31, 24, 3, 27, 37, 26 > > > **Input** and **Output** may be taken in any reasonable format, standard loopholes are as forbidden as usual. **In the spirit of [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in byte wins!** Sandbox: <https://codegolf.meta.stackexchange.com/a/18142/59642> [Answer] # Scratch 3.0 39 blocks/323 bytes [![Oh eval, I miss you](https://i.stack.imgur.com/kqsKa.png)](https://i.stack.imgur.com/kqsKa.png) [Try it on~~line~~ scratch!](https://scratch.mit.edu/projects/333168394/) *Alternatively, as SB syntax:* ``` when gf clicked delete[all v]of[o v ask()and wait set[. v]to(answer set[n v]to(1 repeat until<(n)contains[. if<((n)mod(4))=(0 set[. v]to((. )*(n else if<((n)mod(4))=(1 change[. v]by(n else if<((n)mod(4))=(2 change[. v]by((0)-(n else set[. v]to((. )/(n end end end add(n)to[o v change[n v]by(1 end delete(length of(o))of[o v ``` Look at you guys, having fun with your fancy `eval` statements! Well, not me! **No**... Scratch doesn't have evals, so I had to do things the hard way... if statements. At least it isn't `goto`s... [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), ~~251~~ ~~227~~ 202 bytes ``` [S S S N _Push_0][S N S _Duplicate_0][S N S _Duplicate_0][T N T T _Read_STDIN_as_integer][T T T _Retrieve_input][N S S N _Create_Label_LOOP][S N S _Duplicate_top][T N S T _Print_as_integer][S S S T S T S N _Push_10_newline][T N S S _Print_as_character][S N T _Swap_top_two][S S S T N _Push_1][T S S S _Add][S T S S T N _Copy_2nd_item][S T S S T N _Copy_2nd_item][S N S _Duplicate_top][S S S T S S N _Push_4][T S T T _Modulo][S N S _Duplicate_top][N T S S N _If_0_Jump_to_Label_DIVIDE][S S S T N _Push_1][T S S T _Subtract][S N S _Duplicate_top][N T S T N _If_0_Jump_to_Label_MULTIPLY][S S S T N _Push_1][T S S T _Subtract][N T S S S N _If_0_Jump_to_Label_ADD][S N T _Swap_top_two][S T S S T N _Copy_2nd_item][T S S T _Subtract][N S N N _Jump_to_LOOP][N S S S N _Create_Label_DIVIDE][S N N _Discard_top][T S T S _Divide][S T S S T S N _Copy_3nd_item][S T S S T S N _Copy_3nd_item][T S T T _Modulo][N T S N _If_0_Jump_to_Label_LOOP][N N N _Exit_Program][N S S T N _Create_Label_MULTIPLY][S N N _Discard_top][T S S N _Multiply][N S N N _Jump_to_Label_LOOP][N S S S S N _Create_Label_ADD][T S S S _Add][N S N N _Jump_to_Label_LOOP] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. [Try it online](https://tio.run/##RYxRCoAwDEO/k1P0CnojkYH@CQoev0vbTdeRbi9N3@N82n1te3M3M6p0QcRhAXXIg4rBpPFNDad8ZDaBHCCi8Z6jA@AHuaDgh4xk0YErWC3WSsgcQg1JRsjmQrqvSwc) (with raw spaces, tabs and new-lines only). -24 bytes after a comment of *@JoKing* suggesting `n%i > 0`. Although only `if(x < 0)` and `if(x == 0)` are available in Whitespace, simply checking `if(x*-1 < 0)` is basically the same as `if(x > 0)`. An additional -25 bytes thanks to *@JoKing*. **Explanation:** Quote from the [Scratch answer](https://codegolf.stackexchange.com/a/193833/52210): > > At least it isn't `goto`s... > > > Did someone say `goto`? Whitespace has nothing else than `goto` to create both loops and if-statements. xD In addition it's a stack-based language, so I have to swap/discard/copy pretty often. And to top things off: Whitespace doesn't even have floating points and only integer-division, so I've used `n % i * -1 < 0` to exit the program if the integer cannot divide the current number. *Pseudo-code:* ``` Integer n = STDIN as input Integer i = 0 Label LOOP: Print n as number i = i + 1 Integer t = i % 4 If(t == 0): Jump to Label DIVIDE t = t - 1 If(t == 0): Jump to Label MULTIPLY t = t - 1 If(t == 0): Jump to Label ADD n = n - i Jump to Label LOOP Label DIVIDE: n = n / i Integer m = n % i If(m == 0): Jump to Label LOOP Exit program Label MULTIPLY: n = n * i Jump to Label LOOP Label ADD: n = n + i Jump to Label LOOP ``` [Answer] # [Haskell](https://www.haskell.org/), ~~75 74~~ 73 bytes *-1 byte thanks to Will Ness* *-1 byte thanks to nimi* ``` (#1) n#i|i`mod`4<1,n`mod`i>0=[n]|y<-i+1=n:(x!!i)n i#y x=div:(*):(+):(-):x ``` [Try it online!](https://tio.run/##HcfRCoIwFIDh@z3FEW@2ptIigobrvovoAUxyuMpDehwZoeCzt8KLH76/scPz1rahMZfAYyUYxThj1fWu2uYqoUV4WJuCynnKU5TKkOZjFKEgwHhio3H40XwlNJf/UqHH0Fkk0BqOZ@CCLWfA9Qygs/50Be5fSO@sEcALlWW7EqSEYp9sVCnCt7639jGEtPb@Bw "Haskell – Try It Online") Avoids the use of fractional ints to save on bytes [Answer] # [JavaScript (V8)](https://v8.dev/), 52 bytes Prints groups of 4 terms. Inspired by [GB's Ruby answer](https://codegolf.stackexchange.com/a/193828/58563). ``` n=>{for(k=0;n%1==0;n/=k+=3)print(n,n*=++k,n-~k,--n)} ``` [Try it online!](https://tio.run/##NY/dDoIwDIXvfYpeaAKyBfYDQkx9Fo2RREmqQeINwVfHrptJu26nX7ezx@VzeV/H@2vSn3btcSU8zf1zzAasjrQzGEqJQ4Euf413mjJStMeiGBTp76C0pnxZp9t7AgQCPMEMkTvzCbYzLef8CH1GvMYGb5bNJoxkYHIoSzAqhFNQ/aNRoE1irDBWhfBMJtmJ7GSu5maSvcheUL7FJbkWuRb0EO@RveHiE9MI08hcy90kdyJ3KkTAW3Fi2KVhsIuUjT@x3JdkU7aKxjhdkLxYtfy647TN@gM "JavaScript (V8) – Try It Online") --- # [JavaScript (V8)](https://v8.dev/), 54 bytes Prints the terms of the sequence. ``` n=>{for(k=0;n%1==0;n=eval(n+'*+-/'[k++&3]+k))print(n)} ``` [Try it online!](https://tio.run/##NY/bioMwEEDf@xXz0G5NE9FcdBWJP7IsVIpC65ItKr6I3@5OJlmYIcmZM8nk1a3d/Jie7yVdq2Owh7PtNvxOyWjzxl2k9Yvt1@4ncfx642l2/Ro5/9DffGTsPT3dkji2H0s/L2DBgW1hg8DveILz5vY7a2BArYkF3Oynk29JQDLIMpDChxaQ/0cpIJXRUeQo4cOgGbEmrKmvwGLEhrAhFW/REReEC1I/wz20l7iY6JTklNRXYTXimnAtfHi9okkkTilRrIOlwk8U1ilxKJWHwTC1R4ZGVfi6xlTl8Qc "JavaScript (V8) – Try It Online") --- # JavaScript (ES6), ~~59~~ 58 bytes Returns an array. ``` f=(n,k)=>k&&(n=eval(n+'/*+-'[k&3]+k))%1?[]:[n,...f(n,-~k)] ``` [Try it online!](https://tio.run/##XdBLDoIwEADQvafoRmilfPoBwQQ9CGFBEIyWFCOGpVfHaaubJjNp07yZdvro1m7pX/fnO9bzddi2scaaKlKfVRBgXQ9rN2EdhekhisNGBaKNFCF7dmnaU6NpkiQj@PijSLv1s17maUim@YZHjBghKE0RoyYERdk/CopitvM0d5pTExJqfCAcELZXDswH0gFpy@EO4YPcgdyWH90tds9gkb4unC5srxKcDyoHKmrCtCjt2xlMyKCk8jz//QcHaRPG4JkbBVKYI2mH4/A2AcmL7Qs "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [N"/*+-"Nè.VÐïÊ#= ``` [Try it online](https://tio.run/##MzBNTDJM/f8/2k9JX0tbV8nv8Aq9sMMTDq8/3KVs@/@/kSEA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9W@T/aT0lfS1tXye/wCr2wwxMOrz/cpWz7v/bQNvv/0YY6RjrGOiY6pjpmOpY6RoaxAA). **Explanation:** ``` [ # Start an infinite loop: N # Push the 0-based loop-index "/*+-" # Push string "/*+-" Nè # Index into this string with the loop-index .V # And use a 05AB1E-eval to calculate the next number Ð # Triplicate this number ï # Cast it to an integer Ê # And if it's NOT equal to the number we triplicated: # # Stop the infinite loop = # Print the number without popping ``` I'm using the legacy version of 05AB1E here, and also first calculate the next number before printing it, because the loop is 0-based and it will do a `/0` in the very first iteration. This saved a byte in comparison to the previous `N>` and `"*+-/"`. This only works, because in the legacy version a number that's being divided by 0 remains the same; whereas in the new version it would become 0; and in actual math it would give a division by zero error. [Answer] # [Piet](http://www.dangermouse.net/esoteric/piet.html), 297 190 144 codels (432 bytes) [![New Piet Code](https://i.stack.imgur.com/CxFAZ.png)](https://i.stack.imgur.com/CxFAZ.png) Tried a new approach using a `pointer` command as switch(k mod 4) to unify the output code, resulting in a denser 10x19 code picture. Then I golfed that down by 1 row and 2 collumns to 8x18. Here is a trace, to see how it works: [![enter image description here](https://i.stack.imgur.com/Bmpg0.png)](https://i.stack.imgur.com/Bmpg0.png) The first line pushes a 0 on the stack as starting index (since we can only `push` natural numbers, we push 2 ones and then substract), then reads the input as number. The leftmost collumn has the shared code of duplicating the number and popping one into output, then moving the index on top of the stack, incrementing it and then duplicating it thrice. We then enter the pastel red r-shaped block through the dark cyan codel for a `pointer` command which gives us different paths for the remainder of our index mod 4. Mod 1, we exit through the top to multiply. We first shuffle a copy of our index down for later, then perform the multiplication. After passing through the white for a noop, we enter the collumn above to fix the cc parity (it needs to be flipped an even number of times to keep the loop stable), followed by a `pointer (1)` from entering the magenta bar: It acts as a catch for our four paths and send us back into the loop. Mod 2, we exit backwards to sum. The shape of the pastel code block means we exit a row above from where we entered, and we use the 3 we push onto the stack by exiting through the red codel to `pointer (3)` ourselves upwards. This collumns has the white space before the arithmetic and a slightly different order of pushing and switching cc, because otherwise we would have colour overlap with integer-valued codels in the neighbouring collumn. Mod 3 send us downwards for subtraction. Same deal as multiplication, except we cross over the division path on the way up (As the cc has differing parity when entering the pastel green bar, the two executions exit that bar at different ends). While doing so, we pick up an unwanted `duplicate` command, so we `pop` it back off with the dark green codel before entering the cc correction and collection bar. Mod 4, we go straight ahead to divide. Here, we first have to re-shuffle the stack more severely to get two pairs of n and a to perform operations on, because we need to test if it's integer. We do that my doing `mod` on the first pair, then `not` on the result, then use that for a `pointer` - if it's not divisible, we keep going straight, which sends us with two `pointer` commands into the opposite corner into the inescapable block and thus ends program. Otherwise, we turn right and get a `divide` command from entering the magenta bar. ### Old Version [![Piet Code](https://i.stack.imgur.com/6E4D1.png)](https://i.stack.imgur.com/6E4D1.png) Very straightforward code: Pushes a 1 and the input on the stack, then loops through the four operations by: Shuffling the index on top of the stack, incrementing it by 1, duplicating it, shuffling one copy back down, performing the arithmetic operation, duplicating the number and popping one into output. For division, which is the only one where the sequence can end, it creates a more complicated stack to first check if n mod index == 0, otherwise it enters the inescapable codel and terminates. Otherwise, it uses its second copy of i and n to perform the division. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 44 bytes ``` {$_,{($_,<* + - />[$++%4]~++$).EVAL}...^*%1} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1olXqdaA0jYaCloK@gq6NtFq2hrq5rE1mlrq2jquYY5@tTq6enFaaka1v4vTqxUSNMw1LT@DwA "Perl 6 – Try It Online") Anonymous code block that takes a number and returns a sequence. If we could skip the first element (which is always the same as the second element anyway), we could save 3 bytes by removing the `$_,` [Answer] # [Python 3](https://docs.python.org/3/), 60 bytes ``` f=lambda n,i=1:[]if n%1else[n]+f([n/i,n*i,n+i,n-i][i%4],i+1) ``` [Try it online!](https://tio.run/##DcNBCsIwEAXQvaeYTSExXyRtFSz0JCGLih38UKelduPpYx687Xe8V@tK0XGZPs/XJAaOcUiZKtbEefnOyXJQl@xK2LkO9YU5sekzGKIvuu5CoUlEiw49brjjgTYOJ6m2nXY4dfS@/AE "Python 3 – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~72~~, ~~70~~, 69 bytes ``` n=>{for(int i=1;n%1==0;n=new[]{n/i,n*i,n+i,n-i}[i++%4])Write(n+" ");} ``` [Try it online!](https://tio.run/##bZDNasMwEITveYrFELBrGVs/dmMUBXrvvYeQQzE2CMIaEkMPIc/uTNf0pMIOEuKbkUbDvRrucf0YljjzcbrO38uJJgorh9Njmm955IVi0J73OoTGc@Dx53x5cB0Vv0ElVMXnOZbl3l2Kr1tcxpzLjLLCP1e/m3JdeKprrQhjFTV/0ymq9E4Mn5HHPIMDuBHcKMI4mFLCCmElrQWXEk4IJwG4xqZEK0QrAe/bRbLXWFyKd4J3knYAmBK9EL2ifgs5SAGNnhqe/p@e278YsCKUMc1WCLK/R04qGrzPQqZbXw "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~56 54~~ 52 bytes ``` f=->n,z=1{n%1>0?[]:[n,n*=z,n-~z,n-=1]+f[n/=z+3,z+4]} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y5Pp8rWsDpP1dDOwD461io6TydPy7ZKJ0@3DkTYGsZqp0Xn6dtWaRvrVGmbxNb@jzbUMdIx1jHRMdUx07HUMTKM1ctNLKiuqagpUEiLrtAryY9PAwtpqFkB2Zmatf8B "Ruby – Try It Online") After some (failed) attempt with `eval`, I found out that the happiest solution is building the array with 4 elements at once, at least in ruby. Thanks to Arnauld for -2 bytes. [Answer] # [R](https://www.r-project.org/), ~~[90 bytes](https://tio.run/##HYpLCoAgFEXX0kDQumIPLYtoJRGY0jTC5m/rlg3PJ5cSOKz5vJe4yicdl1SaVJukYwfCwBZJEma2ykzKuK4SwaL/yghN0H@H9p/3dVri1kQhaC@DLS8), ~~[87 bytes](https://tio.run/##FcjBDkAwDADQb3GQtHSZKrZl8SUiYYurCPf9enF871bdyjbfxxXTDE/eT0DD2GSQvgzkaeiKEFMoglb6NgN/Evp3IsNk/glk3PcOrceYlirVNa86ir4)~~ ~~[85 bytes](https://tio.run/##DcgxCoAwDADAtzgIiW0QEUFofYl0SGxRoTio4CC@PXY6uFOVp2vhA9BlTzkd6725Z9tzgopnKQWMoa47fHlagG30VD40YqMR09nkKVKhBTE94ud4Jgk6Dqo/ "R – Try It Online")~~ ~~[80 bytes](http://[Try%20it%20online!](https://tio.run/##K/r/P9G2ODkxT0PTujwjMydVQzExOslGNyc1L70kQyNRM1ZV1VCzOtE2WSNRJ8VGFygZq5Wkk6KdpG2ok2qjm6ILpPQ1krSNNTVrrROjdZNi/1uY/v8PAA%20%22R%20%E2%80%93%20Try%20It%20Online%22))~~ 74~~ [73 bytes](https://tio.run/##K/r/P9G2ODkxT0PTujwjMydVQzExOiRWVdVQM9E2WSNRJ8VGFySgFaKToh2ibaiTaqOboguk9DU0Qmx0Q7RNNHUNNTWtE6N1Q2L/W5j@/w8A) A plain implementation of the rules: ``` a=scan();while(T<13)a=c(a,d<-a[T]*T,d+T+1,e<-d-1,e/((T<-T+4)-1));a[!a%%1] ``` [Try it online!](https://tio.run/##K/r/P9G2ODkxT0PTujwjMydVQzExOiRWVdVQM9E2WSNRJ8VGFySgFaKToh2ibaiTaqOboguk9DU0Qmx0Q7RNNHUNNTWtE6N1Q2L/W5j@/w8A "R – Try It Online") with the `T<13` following from a deeper analysis of the puzzle. Indeed there are only three kinds of sequences: those of length 4, when a⁰ is not congruent to 1 modulo 8; those of length 12 when a⁰ is congruent to 21 modulo 32; and those of length 8 for the remaining cases. An alternative code avoiding loops ends up being longer with 87 bytes: ``` `~`=rep;b=(scan()-1)*c(32~4,8,40~3,1,9~3)/32+c(1,1,3,0~3,6,-c(8,1,9,-71,17)/8);b[!b%%1] ``` [Try it online!](https://tio.run/##FcjBDkAwDADQb3GQtHSZKrZl8SUiYYurCPf9enF871bdyjbfxxXTDE/eT0DD2GSQvgzkaeiKEFMoglb6NgN/Evp3IsNk/glk3PcOrceYlirVNa86ir4 "R – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~104~~ ~~86~~ 85 bytes ``` n#i=n:(cycle[(/),(*),(+),(-)]!!floor i)n i#(i+1) takeWhile((==).ceiling<*>floor).(#1) ``` [Try it online!](https://tio.run/##HYoxD4IwEEZ3fsURHO5Aa@pGY92dHB0IQ4OnvVCLKcTEX18Jwxu@9z3v5pFDyDlWYqPB4TcE7vBIe6xXmpUD9WX5DNOUQCiCVCiNpsLbxY189xIY0VpSA0uQ@DrXly0mhZWm/HYSwRi43gCp2JaFx1QALMl9Oc0M@EkSF@UJOq1U26/fZmAHHk46/wE) The `h=` can be omitted since it's only used for testing. Ah, code golf, where a quadratic increase in time complexity is worth it for the reduction of one character. # 104 bytes ``` f=flip g x=scanl(f($))x.zipWith(f($))[1..].cycle$f<$>[(*),(+),(-),(/)] takeWhile((==).ceiling<*>floor).g ``` [Try it online!](https://tio.run/##JY2xDsIgFEV3vuINDFAVUzeb0t3JsUPTgSAU0idtKDHVn8dahzOce4br1DIaxJyttOhnMsAqF60CMsso56v4@Ln1yf21K4XohX5rNNTWtOlYwY/ssHHaOPOeOJnUaFrn0TAmJRfaePRhqIvG4jRFLob8VD5AVcHtDoyT3SQ8JgKQonqZuBhgc/QhCcfhd3ntt7YvQMHBpcxf "Haskell – Try It Online") I like this answer better, but alas it is longer. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~25~~ 24 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Another adaptation of [GB's Ruby solution](https://codegolf.stackexchange.com/a/193828/58974). ``` %1ª[UU*=°VU´ÒVU]cßU/=V±3 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=JTGqW1VVKj2wVlW00lZVXWPfVS89VrEz&input=MjE) The main trick here is in the overloading of the `c` method for arrays. Pass it another array as an argument and it concatenates it to the original array. Pass it a number as an argument, as happens on the last recursive call, and it flattens the original array by that many levels - `1` in this case, after rounding. But, as the array is only ever one level deep, flattening it has no effect. ``` %1ª[UU*=°VU´ÒVU]cßU/=V±3 :Implicit input of integer U %1 :U modulo 1 ª :Logical OR with [ :Construct and array containing U : U U*= : U multiplied by °V : V (initially 0) prefix incremented U´ : The new value of U, postfix decremented ÒV : Subtract the bitwise negation of V U : The now-decrmented U ] :End array c :Concatenate, or flatten by ß : Recursive call to the programme with argument U/= : U divided by V±3 : V incremented by 3 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 16 bytes ``` ↑¦1G`I⁰zI¢ë*+-/N ``` [Try it online!](https://tio.run/##ASEA3v9odXNr///ihpHCpjFHYEnigbB6ScKiw6sqKy0vTv///zE "Husk – Try It Online") ## Explanation ``` ↑¦1G`I⁰zI¢ë*+-/N Input is a number n, accessible via ⁰. ë*+-/ Four-element list containing the functions *, +, - and /. ¢ Cycle infinitely. z N Zip with the list [1,2,3,4,5,.. I using the identity function (which works as function application since e.g. I+2 == (I+)2 == +2). G Cumulative reduce from the left `I using flipped identity function ⁰ with initial value n. This results in [n, n*1, (n*1)+2, ((n*1)+2)-3, .. ↑ Take the maximal prefix of elements ¦1 that are divisible by 1, or in other words are integers. ``` [Answer] # Java 8, 84 bytes ``` n->{for(int i=1;n%1==0;n=new float[]{n/i,n*i,n+i,n-i}[i++%4])System.out.println(n);} ``` [Try it online.](https://tio.run/##bZA9T8MwEIb3/opTpUoOIYFAQYLI7Ax06RhlMK6DXNJLFF@KUJTfHi4fg1E7nKXnvt73fFRnFR0P34MulXPwoSx2KwCLZJpCaQO7EQHOlT2AFkVZKQIMUk72K34cKbIadoAgYcDorSuqRvA4WJmkuEmkvE9RovmBaTbLO7yzt3jDEXJEts9sGG62ebD/dWROcdVSXDe8oUTBQv2Qjjp1@1myziI3uTmxV7Enbv3KclDBbJSMI5FMBhd48OHRh60PTz48@/Dyb1tycfzkZirO32Oxbmmxc@Wo9ftYf4V1ODfOyzHWwucrg4twP/wB) Creating an array with all four values is inspired by [*@GB*'s Ruby answer](https://codegolf.stackexchange.com/a/193828/52210), although I now notice that using a ternary if-statement is the same amount of bytes: ``` n->{for(int i=0;n%1==0;n=++i%4<1?n/i:i%4<2?n*i:i%4<3?n+i:n-i)System.out.println(n);} ``` [Try it online.](https://tio.run/##bZA9b4MwEIb3/IpTpEimCFqStFKhlLlDs2SsOrgOVJeSA@EjUhXx26mNGVwli32P7@N9z0d5ltHx8DOqWmoN7xLpsgBA4rKrpCphZxHg3OABlKjqRjJQkJnHYWEOzZJRwQ4Ichgper1UTSdMO2D@kNEqye2VhyGuti9JQfeY2mhd0J2LNgWFmFKEwf5Xc3mKm57jtjMTahJGaBgzq9P2X7XRmeUmNyfjVezZlH5/fIIMnFEuNYtkMjjD2oeND1sfHn148uH537TkavnJzZR034PU9jzbubHU8s3mU1iGrtANp1gJn280zsLD@Ac) [Answer] # [Perl 5](https://www.perl.org/), 53 bytes ``` @a=qw(/ * + -);say,eval"\$_$a[++$i%4]=$i"while$_==int ``` [Try it online!](https://tio.run/##NY5bCsIwEEX/s4pQIqhNH3m02pSCG3AFKiUfBQO1VluUbt44ExHOkHDnkJuxe/aFnzKTbrOsvi3M1f5gm8d7ndEtjWmyqSe78O5l@@jMWmZPcczcSl8a5qL31fUda5vGDbNHL4q8MFRwRHGa/yk5TQSRhkqOaBCIMqgABWREG0x1UBUpDKbA7ieHu4BDk9KgAuwhJJWhFUdwuQ@PC@gTsK@IhL9IyMNAkcx/ZTAKIx3qJXQoGFl@7uPs7sPkk37wybFIc/EF "Perl 5 – Try It Online") [Answer] # [Red](http://www.red-lang.org), 102 bytes ``` func[n][k: m: 0 until[foreach o[* + - /][print n t: n n: do reduce[n o m: m + 1]]k: k + 1 t % m <> 0]] ``` [Try it online!](https://tio.run/##FYwxDoMwEAR7XrFNGlAUoDyhPCLt6QpknwUCzpFlv9@YbjWa2aS@/tSzdIFqKObYhA/CRRhRLO8nh5h0dRsi9xjwxkf4n3bLMGSCdUbwEUl9ccqG@LRXMyeRdnQ8CxmvxpYvRpEaME/1Bg "Red – Try It Online") [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 57 bytes ``` {n=$1;for(k=1;n%1==0;n/=k++)print n,n*=k++,n+=k++,n-=k++} ``` [Try it online!](https://tio.run/##SyzP/v@/Os9WxdA6Lb9II9vW0DpP1dDW1sA6T982W1tbs6AoM69EIU8nTwvE1cnThlC6IKr2/39DAA "AWK – Try It Online") [Answer] # [Rutger](https://github.com/cairdcoinheringaahing/Rutger), 310 bytes ``` n=e=$Input; a=0; w=While[{m=Modulo[$e];Not[m[1]];}]; w=w[{f=For[4];f=f[@x];f=f[{Print[$e];q=Equal[$x];i=If[{q[1];}];i=i[{k=Times[$e];}];Do[$i];i=If[{q[2];}];i=i[{k=Add[$e];}];Do[$i];i=If[{q[3];}];i=i[{k=Subtract[$e];}];Do[$i];i=If[{q[4];}];i=i[{k=Divide[$e];}];Do[$i];e=k[a=Increment[$a]];}];Do[$f];}]; Do[$w]; ``` [Try it online!](https://tio.run/##dc/NCsIwDAfw@55jD6BztxJQmMIOiqDgIfRQXabBfbjaOmH47LNzoEPYqaH/XxKirTmTbtsCCPy4uFkjPAUT4dVwuHBG2OSwLhObleiTFJvSYI5TKcVLdqbGJoVVqTGUIoUU58/@bbaaC/NpqWBZWZWh7yKG2GWVG9D1MzA2V9hzTvcPdX@R28M/GAzhIklG2GzIdvZotDqZERsObcQPTuhPElxRQVycNOXUXaHkN077y7uylqJtg@kb "Rutger – Try It Online") It's about time I used Rutger again. Unfortunately, it may not be the best language for the task, as it has no form of `eval`, forcing me to use four if statements ## How it works ### How Rutger works A brief foreword on how the language works: Everything is either an assignment or a function, and every function takes exactly one argument. For operations that require more than one argument (e.g. multiplication), the first call returns a *partial function*, that, when called again with the second argument, returns the expected result. For example: ``` left = Times[5]; Print[left[6]]; ``` will print out 30: [Try it online!](https://tio.run/##KyotSU8t@v8/JzWtRMFWISQzN7U42jTWmiugKDOvJBokHG0WG2v9/z8A "Rutger – Try It Online"). While usually this is longer than the usual alternative, it can at times save bytes, if a function is called repeatedly with one constant argument, and one changing argument, for instance when printing out times tables. This one argument rule applies to everything that isn't a constant or a variable, including loops and conditionals. However, loops and conditionals (`For`, `Each`, `While`, `DoWhile`, `If` and `IfElse`) are *doable*, meaning that in order to actually run them, the `Do` function must be called (see the last line in the answer). Again, this can save bytes when repeatedly running the same loop, or allow you to run arbitrary code between the definition and running of loops. Finally, there are three ways of referring to variables, all of which are used in this program. The first is *direct referencing*, where the variable name is prefixed with a `$` symbol. This accesses the value of the variable directly and returns it. The second is *functional referencing*, which doesn't have a prefixing character. This allows the code to distinguish between (potentially partial) functions assigned to variables, and actual variables containing a specific value. Finally, *indirect referencing*, prefixed with an `@` symbol, creates a variable (if it doesn't already exist) and returns the variable object within a given scope. This allows you to create a loop variable (e.g. `i` in `for i in range(...)`). ### How the actual solution works Here is the ungolfed code: ``` n = elem = $Input; var = 0; while = While[{ mod = Modulo[$elem]; Not[mod[1]]; }]; while = while[{ for = For[4]; for = for[@index]; for = for[{ Print[$elem]; equal = Equal[$index]; if = If[{ equal[1]; }]; if = if[{ func = Times[$elem]; }]; Do[$if]; if = If[{ equal[2];}]; if = if[{ func = Add[$elem];}]; Do[$if]; if = If[{ equal[3];}]; if = if[{ func = Subtract[$elem];}]; Do[$if]; if=If[{ equal[4];}]; if=if[{ func = Divide[$elem];}]; Do[$if]; elem = func[var = Increment[$var]]; }]; Do[$for]; }]; Do[$while]; ``` [Try it online!](https://tio.run/##hZHBTsMwDIbPzVP00AdgME5RJZAGUg8gJJA4WDmUxoFIbQIh2ZAmnr3Ya7sNadUucezf/hzlDym@Y@h7l5c5tthRKCr3maIU6zpQdiHF5sO2SNdXjrAVWec1pQ9ep9ZDwWNKiuzRRyAFFoqyX3WY24xzxjPw3gdYkjpkdMKNdRp//pVoyVOwLh7o@JXqltQ7jlBMIyKzhqqVgW2@a6H1Muftg2BZMMk1dH@xHX5PxKFnRe@35iTnUsnTmFutJ8g5xtUc4zm9xVA3cR5UHmGWe0x5DFnZtdU4hxjd5F4YrKxcE7BD/lUqsEvZfog@fXSNs51jSvb94voP "Rutger – Try It Online") As you can see, it starts by assigning the three variables `n`, `e` and `a`, which represent the input, the changing element in the sequence, and the modification number for each new element respectively. We then create a while loop: ``` w=While[{m=Modulo[$e];Not[m[1]];}]; ``` The braces (`{` and `}`) define a *block* of code, where the final statement in the block is the condition for the while loop. In this case, we start by defining a partial modulo function, which will take in a second argument `m`, and return `e % m`. We then call this partial function with \$1\$ as its second argument, returning \$0\$ for integers and a non-zero integer for floats. We then calculate the logical not of this, mapping \$0 \to 1\$ and \$n \to 0, n \ne 0\$. Next we come to the absolute monstrosity consisting of the while loop's body: ``` w=w[{f=For[4];f=f[@x];f=f[{Print[$e];q=Equal[$x];i=If[{q[1];}];i=i[{k=Times[$e];}];Do[$i];i=If[{q[2];}];i=i[{k=Add[$e];}];Do[$i];i=If[{q[3];}];i=i[{k=Subtract[$e];}];Do[$i];i=If[{q[4];}];i=i[{k=Divide[$e];}];Do[$i];e=k[a=Increment[$a]];}];Do[$f];}]; ``` The primary part of this loop is a for loop, that iterates \$4\$ times each iteration of the while loop, has an iteration variable of `x` and consists of: ``` Print[$e]; q=Equal[$x]; i=If[{q[1];}];i=i[{k=Times[$e] ;}];Do[$i]; i=If[{q[2];}];i=i[{k=Add[$e] ;}];Do[$i]; i=If[{q[3];}];i=i[{k=Subtract[$e] ;}];Do[$i]; i=If[{q[4];}];i=i[{k=Divide[$e] ;}];Do[$i]; e=k[a=Increment[$a]]; ``` The first statement prints out each iteration of the sequence before modifying it. We then create a partial function to check equality with the loop variable `x`, and encounter four if statements. Each statement checks if `x` is equal to 1, 2, 3 or 4 respectively, and then assigns `k` to each function in `*`, `+`, `-` and `/`, then makes it into a partial function with `e` as its argument. Finally, we assign `e` to `k` run with `a` as its second argument, and increment `a`. [Answer] # [Ruby](https://www.ruby-lang.org/), 52 bytes ``` ->n{i=0.0;n=[p(n)/i+=1,n*i,n+i,n-i][i%4]until 0<n%1} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOtPWQM/AOs82ukAjT1M/U9vWUCdPK1MnTxuIdTNjozNVTWJL80oycxQMbPJUDWv/p0UbGcb@BwA "Ruby – Try It Online") [Answer] # dzaima/APL, ~~34~~ 33 bytes ``` ⌽1↓{⍵,⍨⊃⍵(⍎⊃'÷×+-'⌽⍨≢⍵)≢⍵}⍣{⍵≢⌊⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pSszMTfz/qG@qp/@jtgkG/9OA5KOevYaP2iZXP@rdqvOod8WjrmYgS@NRbx@QpX54@@Hp2rrqQDUgqc5FQClNCFX7qHcxSA@I19MFEgCZCzQvTcGQC8YyMvwPAA "APL (dzaima/APL) – Try It Online") -1 thanks to [ngn](https://codegolf.stackexchange.com/users/24908/ngn) [Answer] # TI BASIC, 68 Bytes ``` 1→A DelVar L1Prompt N Repeat fPart(N N→L1(A NA-1→O augment(L1,{NA,Ans+A+2,Ans→L1 O/(A+3→N A+4→A End L1 ``` We set up a counter in A and clear L1 so we can use it to track the sequence. We then repeat until the division step causes a fraction. Inside the loop we first store N to the list. Storing to one element past the end of a list or an empty list creates that element, so this one store both adds the result of the division when it doesn't cause a fraction, and initializes the list during the first pass. We then use augment to append the next 3 terms of the sequence. The math works out a few bytes smaller by calculating term A4k+3 in variable O and then basing A4k+2 and A4k+4 off O. Then we do the division separately to reset N for the repeat check and add 4 to A. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` NθW¬﹪θ¹«Iθ⸿≔§⟦∕θⅉ×θⅉ⁺θⅉ⁻θⅉ⟧ⅉθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05qrPCMzJ1VBwy@/RMM3P6U0J1@jUEfBUFNTU6GaizOgKDOvRMM5sbgEqBaoGCqgFFOkBOI5FhdnpudpOJZ45qWkVmhEu2SWZaakggyI1NDU1FEIycxNLUZwA3JKkXi@mXkIbixMFOSk2v//jQz/65blAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input the initial value. ``` W¬﹪θ¹« ``` Repeat until the value is no longer an integer. ``` Iθ⸿ ``` Print the value on its own line. ``` ≔§⟦∕θⅉ×θⅉ⁺θⅉ⁻θⅉ⟧ⅉθ ``` Calculate the four available arithmetic operations and select the correct one depending on the current output line number. [Answer] # [C (clang)](http://clang.llvm.org/), 80 bytes ``` i;f(n){for(i=0;~i;n=++i%4?i%4-1?i%4-2?n-i:n+i:n*i:n%i?i=-1:n/i)printf("%d ",n);} ``` [Try it online!](https://tio.run/##ZY1NboMwEIX3c4oRFZJdSottMCEuzUW6iSC0I6WTiMAqSq9OB5au7WfN@@avy7vzkb@WhcKgWN@Hy6ioLcIvBW6zjNLyIMrN9tsD57TnTPQsSulAbW72/Eb6OhJPg0rSHpMX1uGxPBF357k/4ftt6uny@v0BIDX4cyRWGu8wKKPDdZ5uKvnkRAcBNgYuBmUMqhj4GDT/tkR7AeWMp2keGYsAj8WgQYfFdj3mBgEsWixxjZykKnEApRAvDqASUm/5Co2RAMBLaicWoMFmhTvpMQUaL1bmGVyfQ1us0yp04koZZmt0NVovNX8 "C (clang) – Try It Online") ``` A golfed switch statement. ``` Thanks to many @ceilingcat improvements. [Answer] # [Python 3](https://docs.python.org/3/), ~~78~~ 76 bytes ``` f=lambda n:n[-1]%1and n[:-1]or f(n+[eval(f"n[-1]{'/*+-'[len(n)%4]}len(n)")]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIc8qL1rXMFbVMDEvRSEv2grIzi9SSNPI045OLUvM0UhTAstXq@traeuqR@ek5mnkaaqaxNZCWEqasZr/C4oy80o00jSiDWM1NbngPCMUnjEKzwSFZ4rCM0PhWaKaCbLiPwA "Python 3 – Try It Online") Takes input as a list of 1 item and recursively appends the next item of the sequence until it's a non-integer. In the case that taking input as a list is not allowed, here is a very quickly patched version which takes input as an int. # Input as an integer, 102 bytes ``` f=lambda n:type(n)==int and f([n])or n[-1]%1and n[:-1]or f(n+[eval(f"n[-1]{'/*+-'[len(n)%4]}len(n)")]) ``` [Try it online!](https://tio.run/##TcxBCsIwEIXhvacIhdIZS5HYVrCQk4QsIk1QiNNQglDEs8eoCLP7eA/@uKXrQn3OXgV7v8xW0JS26IBQqRslYWkWHjQZXFZBupOmlp@N9FRcNg/UavewAXz1/Z/NYd92jQ6OSqUezOunCg3muJYoeJCIu7@PzD3zwDwyn5jPvFOi@Q0 "Python 3 – Try It Online") +2 bytes thanks to me forgetting to name the recursive function... -4 bytes thanks to Jitse [Answer] # [Twig](https://twig.symfony.com/), 164 bytes Okay, this was actually horribly horrible to write. Limitations: * No `returns`! You either output or don't output * No `while` loops. You **must** use recursion or nothing * No easy way to output! You have to repeat the output everytime * You can't give variables a value without using the `set` tag * No easy way to get out of a loop. There's no `break`, `continue`, `goto` or similar. This makes a loop impossible to use. * There is only 1 loop: `for ... in ....`, and it loops over all the elements in an array, with no way to stop. All those made the code massive! Hey, I even made it longer than the Java answer! It's as long as [@Arnauld's](https://codegolf.stackexchange.com/users/58563/arnauld) [JavaScript answer](https://codegolf.stackexchange.com/a/193826/)! ... With all 3 alternatives combined. **Here's the code:** ``` {%macro a(b,n=1)%}{{n<2?b}}{%set b=b*n%},{{b}}{%set b=b+n+1%},{{b}}{%set b=b-(n+2)%},{{b}}{%set b=b/(n+3)%}{%if(b//1)==b%},{{b~_self.a(b,n+4)}}{%endif%}{%endmacro%} ``` You can try it on <https://twigfiddle.com/zw5zls> --- ## How to use: Simply import the file and call the first macro. ``` {% import 'file.twig' as a %} {{ a.a(21) }} {# 21,21,23,20,5,25,31,24,3,27,37,26 #} ``` To have an usable array, you can do `a.a(21)|split(',')`. --- ## Ungolfed: ``` {% macro calc(number, index = 1) %} {% if index < 2 %} {{ number }} {% endif %} {% set number = number * index %},{{ number }} {% set number = number + index + 1 %},{{ number }} {% set number = number - (index + 2) %},{{ number }} {% set number = number / (index + 3) %} {# verifies if it is an integer. this is done with an integer division with 1 and compare with itself if both values are the same, the number is an integer otherwise, it is a floating-point number #} {% if (number // 1) == number %} ,{{ number ~ _self.calc(number, index + 4) }} {% endif %} {% endmacro %} ``` Should be easy to read. This ungolfed answer will NOT give the correct output, as it will throw random whitespaces. It exists merely to be humanly readable. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ×+_÷4ƭ‘ɼ$ḞƑпṖ ``` A full program\* that accepts an integer and prints the resulting sequence. **[Try it online!](https://tio.run/##AScA2P9qZWxsef//w5crX8O3NMat4oCYybwk4biexpHDkMK/4bmW////MjE "Jelly – Try It Online")** ### How? ``` ×+_÷4ƭ‘ɼ$ḞƑпṖ - Main Link: integer, n п - collect while X, initially n, is: Ƒ - ...invariant under Ḟ - floor to the nearest integer $ - ...last two links as a monad - f(X): ɼ - apply to the register (initially zero) and yield: ‘ - increment (i.e. get the next right operand) 4ƭ - calling these four links in turn: × - multiply + - add _ - subtract ÷ - divide Ṗ - pop off the trailing, non-integer - implicit print ``` \* Note: this is not a reusable Link since the tie quick, `ƭ`, does not reset between calls to a Link. ]
[Question] [ ## Final results # 1st place goes to *Follow*! Honourable mentions to **The diff predictor** (2nd), and **Simple Killer**, **Low Blow** and **High to Low** (joint 3rd). Other winners: ### (score competition) 1st - Simple Killer Honourable mentions: **The diff predictor** and **Naiive**. ### (wins competition) 1st - Crab Honourable mentions: **Follow** and **High to Low**. Full results: ``` By score: 1: Simple Killer with 1208099 points 2: The diff predictor with 1053087 points 3: Naiive with 1051505 points 4: Follow with 905731 points 5: The dedicated counter with 769680 points 6: The Desperate Fighter with 769663 points 7: Low Blow with 763357 points 8: High to Low with 734011 points 9: Naughty or Nice? with 714912 points 10: Grim Trigger with 713702 points 11: Tit for tat with 713067 points 12: The primitive looker with 621028 points 13: Hard-coded with 428934 points 14: Zoidberg with 395702 points 15: FunnyNumber with 335179 points 16: Random with 329023 points 17: Shortcut with 257190 points 18: Meandian with 223051 points 19: Hawk with 47608 points 20: Crab with 14852 points By wins: 1: Crab with avg. 19.0/19 wins 2: Follow with avg. 17.1/19 wins 3: High to Low with avg. 15.8/19 wins 4: Low Blow with avg. 14.9/19 wins 5: The diff predictor with avg. 14.1/19 wins 6: Meandian with avg. 13.7/19 wins 7: Hawk with avg. 13.0/19 wins 8: Hard-coded with avg. 11.7/19 wins 9: Naughty or Nice? with avg. 11.0/19 wins 10: Simple Killer with avg. 10.4/19 wins 11: The primitive looker with avg. 8.0/19 wins 12: Naiive with avg. 6.6/19 wins 13: Zoidberg with avg. 6.3/19 wins 14: Shortcut with avg. 5.0/19 wins 14: Grim Trigger with avg. 5.0/19 wins 16: FunnyNumber with avg. 4.0/19 wins 17: Random with avg. 3.0/19 wins 18: Tit for tat with avg. 1.0/19 wins 19: The dedicated counter with avg. 0.0/19 wins 19: The Desperate Fighter with avg. 0.0/19 wins Combined leaderboard (fewer pts = better): 1: Follow (6 pts) 2: The diff predictor (7 pts) 3: Simple Killer (11 pts) 3: Low Blow (11 pts) 3: High to Low (11 pts) 6: Naiive (15 pts) 7: Naughty or Nice? (18 pts) 8: Hard-coded (21 pts) 8: Crab (21 pts) 10: The primitive looker (23 pts) 11: The dedicated counter (24 pts) 11: Grim Trigger (24 pts) 11: Meandian (24 pts) 14: The Desperate Fighter (25 pts) 15: Hawk (26 pts) 16: Zoidberg (27 pts) 17: Tit for tat (29 pts) 18: FunnyNumber (31 pts) 18: Shortcut (31 pts) 20: Random (33 pts) ``` --- # Cooperative Counting - Python 3 KOTH Have you ever tried to count to 100 in an online forum or comment thread? It normally goes something like: ``` 1 >2 >>3 >>>4 >>>>69 xD xD ``` the point being that someone will always try to ruin the fun. # The game This is a bit like the counting example above, except to make sure that neither player has an advantage from going first, each player will count at the same time as the other. Your bot will be pitted against another bot. Your goal? Cooperatively count to 100. Each round, your bot decides how far it is willing to cooperatively count with its opponent. ## Possible outcomes **One player stops counting before the other** The player who stopped counting first is awarded twice as many points as the value they counted up to. The other player gains no points. **Both you and your opponent stop counting at the same time** Neither of you gain any points. **Both you and your opponent count all the way to 100** Each player gains 100 points. ## Example * Player 1: decides to count to 80 * Player 2: decides to count to 30 Player 2 gets 60 points, player 1 gets 0 points. --- In another round: * Player 1: decides to count to 57 * Player 2: decides to count to 57 Neither player gets points. --- In yet another round: * Player 1: decides to count to 100 * Player 2: decides to count to 100 Each player gets 100 points. # Overall game flow Your bot will be matched against other bots. It will play some number of rounds in a row, `n`, against the same bot. `n` will be somewhere in the range of 100 - 1000. This allows your bot to adapt to the other bot's strategy. # Winning the KOTH Each bot will have a go against each other bot. Your bot can win in three categories: * **Score:** the total scores will be summed and the bot with the most points at the end will win. * **Wins:** a 'win' is counted for the bot with the highest score after the `n` rounds have been played. * **Overall:** both the other categories combined # Technical details Write a function in Python 3 with this signature: ``` def strategy(last_results: list[tuple[int, bool]]) -> int ``` * `strategy` is called once at the beginning of each round. + `last_results` is a list of previous results against the same opponent. Each item in the list is the result of a round in the form `(value reached, won)`, where `won` denotes whether the player won or not. If the player won through cooperation, this will be `True`. + e.g.: if you lose your first round because your opponent stops counting at 79, `last_results` looks like `[(79, False)]` at the start of round 2. If you then win round 2 by stopping counting at 34, `last_results` will look like `[(79, False), (34, True)]` at the start of round 3. + `strategy` should return the value at which the bot will stop counting. `1` stops counting immediately, `100` is an agreement to count cooperatively with the other bot all the way to the end, and e.g. `47` will stop counting when the value is `47`, earning the bot 84 points. ## Example bot 'Naiive' counts up to one before the number that was reached last round if it lost, otherwise it counts up to and including the number it won on. ``` def strategy(last_games): if len(last_games) == 0: return 100 # Count up to one before the last number that was counted if we lost, # otherwise just up to the last number that was counted. if last_games[-1][1]: return last_games[-1][0] else: return max(1, last_games[-1][0] - 1) ``` ## Legacy format (don't use) **I've decided on a simpler format since the last one was causing confusion. Here is the old one for reference purposes. New submissions should be in the new format. Submissions using the legacy format do not need to update their submission.** ``` # Don't use this, see above def strategy(last_results: list[tuple[int, bool]]) -> tuple: pass def turn(current_value: int, *args) -> bool: pass ``` # Rules * No cheating by interfering directly with your opponent (through global variables etc.). * Your function should be relatively quick to execute - the quicker it is, the better. * You *may* submit multiple entries. * Submissions close a week from the start of this post, at 2021-04-17 11:00 UTC # Controller, sandbox, arena **The controller is available at <https://github.com/jthistle/KOTH-counting>.** A couple of example bots are provided along with it to demonstrate how to use it. `sandbox.py` provides a place to try out your bot against others and debug it. `arena.py` is what I'll be using to calculate final scores. It pits each bot against each other bot. [Answer] # Crab ``` def strategy(last_results): return 1 ``` Crab *always* stops counting, because it'd rather not get points than have the other bot beat it. It is because of Crab that we can't have nice things. [Answer] # Low Blow ``` import random import statistics def strategy(last_results): scores = list(map(lambda a: a[0], last_results)) if not scores: return 99 if len(scores) > 420 and scores[:3] == [69, 68, 68]: return 67 decrements = [50, 69, 48] if all(score == 1 for score in scores): return 1 for decrement in decrements: mold = [decrement] for _ in scores[1:]: mold.append(decrement - 1) if scores == mold: return decrement - 1 if scores[0] == 65: if scores[-1] == 1: return 1 return random.randint(1, 48) if scores == [98]: return 97 if len(scores) == 1 and scores[0] < 48: return scores[0] if last_results[:2] == [(99, True), (99, False)]: return max(scores[-1] - 1, 1) if scores[:2] == [47, 31] : return max(min(50, int(sum(scores) / (len(scores) * 1.5))) - 1, 1) if scores[:2] == [99, 97] : return max(scores[-1] - 3, 1) if scores[:2] == [99, 98] : return max(scores[-1] - 2, 1) if scores[:3] == [99, 99, 98]: return max(scores[-1] - 1, 1) if scores[:2] == [98, 97] : htl_losses = [result[0] for result in last_results if result[1]] return max(min(htl_losses) - len(htl_losses) - 2, 1) if len(scores) > 1 and scores[0] == scores[1] != 99: mean = round(statistics.mean(scores)) median = round(statistics.median(sorted(scores))) if mean == median: return max(mean - 1, 1) return max(abs(median - mean) - 1, 1) if scores[-1] == 1: return 1 if len(scores) <= 3: return 99 deltas = [scores[~0] - scores[~1], scores[~1] - scores[~2]] if any(deltas): return random.randint(37, 50) return 99 ``` Low Blow's strategy is somewhat "kamikaze". It aims to reduce the opposition bot's score as much as possible, even if that means that Low Blow scores fewer points. However, it does aim to capitalise on points against specific bots where possible. It does this by identifying the bot it's against, then playing their own strategy against them, but one lower than what they'd return. Either, the values are constant and Low Blow collects a bunch of points, or the values eventually reach 1, at which point Low Blow will likely\${}^\*\$ have more points and neither bot will get more \${}^\*\$"Likely" because of randomness from Hard-coded [Answer] # Follow ``` def strategy(last_results): n = len(last_results) if n == 0: return 100 if all(i == (1,False) for i in last_results): return 2 # nice to the crab a,b = last_results[-1] if n == 1: if b: return 100 return 1+int(.97*(a-1)) c,d = last_results[-2] if n >= 99 and a == 100: return 99 if b and d: # won previous two rounds if (a+1,False) not in last_results: return min(100,a+1) return a else: a,c = sorted((a,c)) return max(1,a*a//c-1) ``` Starts out by counting to 100. After round 99, if it previously counted to 100, it will only count to 99 (the reasoning is that it would otherwise tie with everything else that keeps counting to 100). If it detects the crab, it's nice (because it doesn't matter anyways). If it lost the previous round, then it counts lower than whatever won in the previous round (between 1 to 3 less). If it won the previous round, then it counts one further if it hasn't lost by counting that far before. Edit: Made it use the ratio between the previous two moves to decide what to count to, made it only start increasing if it won the previous two rounds, and figured out a better way to check for the crab [Answer] # Simple Killer ``` def strategy(last_results): if not len(last_results): return 100 if len(last_results) == 999 and last_results[-1][0] == 100: return 99 last_move = last_results[-1] if last_move in last_results[:-1]: pos = last_results.index(last_move) if last_results[pos + 1][1]: return last_results[pos + 1][0] return max(last_results[pos + 1][0] - 1, 1) return 100 ``` Simple Killer targets a certain class of bot: those who consider only the most recent move (or don't look at the past). By determining exactly how the opposing bot typically reacts, Simple Killer is able to slowly figure out the optimal move in any given circumstance. It either loses by a narrow margin, wins by a huge margin, or plays nice (if the other bot is happy to just sit at 100). [Answer] # The dedicated counter Updated to use the new format (slight performance gain, which adds up): ``` def strategy(last_results): return 100 ``` Original: ``` def strategy(last_results): return () def turn(current_value, *args): return True ``` No matter what the opponent does, this bot will always count up. With determination it keeps going in the face of potential trolls. I'll be writing a more thought out bot once I can see the examples. [Answer] # The primitive looker This is a bot which learns from its previous rounds. New version: ``` def strategy(last_results): if not last_results: return 100 if any(not x[1] for x in last_results): if last_results[-1][0] - 2 > 0: return last_results[-1][0] - 2 return 100 return 99 ``` Legacy version: ``` import random def strategy(last_results): try: return (last_results, ) except: return ([], ) def turn(current_value, res): v = 99 m = 2 g = True for i in res: if not i[1]: g = False break if res == []: c = True else: if res[-1][1] and g: if current_value == v: c = False else: c = True else: if current_value == res[-1][0] - m: c = False else: c = True return c ``` Lucky this is not [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")... [Try it online!](https://tio.run/##rZHBboMwDIbveQofW6mVxnpqJa57gt1QVEVgaCQIyHFQeXqWhDIajeNy@mN//n9HGSZ@9OYyz7obemIgZaq@E6LCGiyTYmymQ6ss3wmta9kebwL8YZoWEQ4hOzKQcCc4xj4@Sxz4L1vIQMScUDiUjggN30fVOjx5bE0aIYfrNcrOy8@oGq@@yWG81D2BBm3C0BYUkAb8c0AXmfwtR6HrwEKeQyG3ifLdFFuLW2sZKM6Z9F7RtNmaLyB5QfAeU2SN@FLeOumkWbvr7GN7qeueHxLO0P3TCuLt60oh5vkH) [Answer] # Shortcut Updated to use the new format (slight performance gain, which adds up): ``` def strategy(last_results): return 50 ``` Original: ``` def strategy(last_results): return () def turn(current_value, *args): return current_value != 50 ``` Not the patient type. Takes the reward of 100 on turn 50, instead of being a team player and getting taken advantage of down the line. Shortcut has some trust issues. I'll start on a more complicated bot soon. [Answer] # FunnyNumber ``` def strategy(last_results): if len(last_results) > 420: return last_results[420][0] return 69 ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TaG4pCixJDW9UiMnsbgkvii1uDSnpFjTioszM00hJzUPVVjBTsHEyAAoyVmUWlJalKeALBsNlIqNNojlgkmaWf7/DwA "Python 3 – Try It Online") Like the joke itself, this bot is very uncreative. If there has been more than 420 rounds, FunnyNumber returns the result of the 420th (0-indexed) round. Otherwise, it counts up to 69 to try to earn 138 points. Interestingly, this isn't the worse bot. Running a couple of arenas locally with this as a contestant, FunnyNumber gets 3/6 wins [Answer] # Zoidberg ``` def strategy(_): return 48 ``` Zoidberg is like a crab, but different. Credit to [user](https://codegolf.stackexchange.com/users/95792/user) for [the original idea](https://chat.stackexchange.com/transcript/message/57613061#57613061). I brute forced what number provides an optimal score with this approach. Surprisingly, this is better overall than Crab. Running locally I get | Bot | Score | Wins | Overall | | --- | --- | --- | --- | | Crab | 12th | 1st | 6th | | Zoidberg | 5th | 5th | 5th | [Answer] # High to Low ``` def strategy(last_results): if last_results: losses = [r[0] for r in last_results if not r[1]] if losses: return max(1, min(losses)-len(losses)) num_of_rounds = len(last_results) if num_of_rounds>15 and len(losses)/num_of_rounds>0.6: return 1 return 98 ``` This bot always counts to `98` unless it has lost a round. Once this bot loses a round, it only counts to numbers lower than its lowest loss. If it has lost more than `60%` of the rounds, it plays `1`. **Edit:** Changed the algorithm for calculating the number the bot should count to after losing from `max(1, min(losses)-1-len(losses))` to `max(1, min(losses)-len(losses))`. Hopefully, this should allow the bot to capitalize on static bots because it now counts to `1` below and not `2` below. [Answer] # Copycat ``` import urllib.request import bs4 as bs import random contents = urllib.request.urlopen("https://codegolf.stackexchange.com/questions/223202/cooperative-counting").read() html = bs.BeautifulSoup(contents, 'html.parser') answers = html.findAll('div', {"class": "answer"}) strategies = [] for answer in answers: code = answer.find('div', {"class": "answercell"}).findAll('code') for any in code: strategies.append(str(any.contents[0])) def newStrat(badOne = None): if not badOne == None: strategies.remove(badOne) return random.choice(strategies) pick = newStrat() def strategy(games): global pick try: exec(pick.replace('strategy','strategycopy'),globals()) return strategycopy(games) except: pick = newStrat(pick) return strategy(games) ``` I didn't really feel like making a strategy up, so this bot will just copy someone elses answer. [Answer] ## Tit for tat ``` def strategy(last_results): return last_results[-1][0] if last_results else 100 ``` Very basic strategy. [Answer] # Meandian ``` import random import statistics as stats def strategy(last_results): def clamp(minimum, x, maximum): return max(minimum, min(x, maximum)) last_results = sorted(map(lambda a: a[0], filter(lambda a: not a[1], last_results))) if not len(last_results): return random.randint(1,47) else: mean = round(stats.mean(last_results)) median = round(stats.median(last_results)) if mean == median: return mean elif mean > median: return clamp(1, median - random.randint(1,mean - median), 100) else: return clamp(1, mean - random.randint(1,median - mean), 100) ``` This bot calculates the mean and median, and uses those calculations to predict a range of values that will be less than the other bot's choice, and will randomly choose one of them. It is also designed to be difficult to hardcode a solution to beat it but still handle other bots robustly. edit: Meandian now only considers the round where the other bot wins during calculations to prevent itself from driving down itself unnessecarily. [Answer] # The diff predictor ``` def strategy(last_results): previous_values = list() diffs = list() for num,result in last_results: if result: oppo_play = min(100,num+1) else: oppo_play = num if len(previous_values)>0: diffs.append(oppo_play-previous_values[-1]) previous_values.append(oppo_play) if len(previous_values) == 0: move = 100 elif len(previous_values) == 1: move = previous_values[0] else: diffs = diffs[-10:] if len(diffs)>2: # remove outliers diffs.remove(min(diffs)) diffs.remove(max(diffs)) meandiff = sum(diffs)/len(diffs) move = previous_values[-1] + meandiff -1 if move==99 and len(last_results)<950: # Let's be nice (for a while) move=100 return min(100, max(1, round(move))) ``` Predicts what the opponent will play next based on the average difference between consecutive previous plays (discarding highest and lowest, to avoid being fooled by FunnyNumber). Assumes the opponent played N+1 whenever it wins with N. It plays 100 as long as the opponent does the same, until towards the last games, where it decides there's no use in being nice anymore. [Answer] # Lumberjack The plan is get to a winning position and then head towards 1 faster than the opponent can recover. Partly inspired by other bots here! ``` def strategy(last_results): round_number = len(last_results) if round_number == 0: return 100 if all(i == (1, False) for i in last_results): return 1 # lumberjacks don't like crabs score, success = last_results[-1] if round_number == 1: if success and score == 100: return 100 return max(1, score/2) old_score, old_success = last_results[-2] if success and old_success: # won previous two rounds if score == 100: return 97 # try and get in under fair bots else: # minimal pruning, light regrowth return max(1, (score+old_score)*0.4 + 15) if not success: if not old_success: # heavy pruning return max(1, score*0.5) # light pruning return max(1, score*0.75) else: # regrow by small amounts return min(100, score + old_score*0.2 + 10) ``` I dreamt this up on Thursday, but I wasn't able to write it down and experiment until today. It's a late entry so I'm not expecting any prizes. [Answer] # The Desperate Fighter # [Python 3](https://docs.python.org/3/), 285 bytes ``` def strategy(last_results): if len(last_results) == 0: return True, pos = last_results[-1][0] if pos in [49,50]: return False, if pos in list(range(10,21)): return False, else: return True, def turn(current_value, *args): return args[0] ``` [Try it online!](https://tio.run/##dY/dCsIwDIXv9xS57GRC58@FQm99Au/GGEWzOSjdSFNhT19bdeBvrpKc8yWcceLLYNchnLEFx6QZu0kY7bghdN6wy/cZxBoHBwpehWpZ1pWs72rfgkH7zoFSIB8wACF7snAkj8VMpJO9hWqzK7ay/nAetHFfVtM7FqRth6KUxarM8/8Uxu7n9yxFTbM4eSK03Fy1iQIsNHVz3CeRNjFjCDc "Python 3 – Try It Online") This bot will try to win in anyways it can.... # Bot handling * Lyxal: I stop at 50 to attack his bot * math: I stop at 10 to 20 for defence to his bot * Redwolf: I stop at 49 to attack his bot [Answer] # Naughty or Nice? ``` def strategy(last_results): scores = list(map(lambda a: a[0], last_results)) if all(score == 100 for score in scores): if len(scores) == 999: return 98 return 100 constant_bots = { 69: 68, 68: 67, 50: 49, 48: 47 } return constant_bots.get(scores[-1], 1) ``` Naughty or Nice? works on a very simple premise: Every match, one bot must be Naughty. * If the opponent counts to 100, Naughty or Nice? considers it "nice", and so Naughty or Nice? must be Naughty. It counts up to 100 with its opponent until it reaches the final round, where it stops at 98 * Otherwise, the other bot is Naughty, and so doesn't deserve any points. In this case, either: + The opponent is a "constant" bot (FunnyNumber, Zoidberg, Shortcut), so we return 1 less than them + The opponent is not a constant bot, so we throw a tantrum and play 1 for the rest of the match [Answer] # Hard-coded ``` import random def strategy(last_results): if len(last_results) == 0: return 65 if last_results[-1][0] in [50,49]: return 49 # Shortcut detected, attack! if last_results[-1][0] in [69,65]: return 65 # FunnyNumber detected, attack! if last_results[-1][0]==1: return 1 # Crab detected, defend! else: return random.randint(1,100) # give away, my mind is boggling with numbers ``` It is mainly designed to compete against caird and Redwolf and user [Answer] # Grim Trigger ``` def strategy(last_results): if any([not r[1] for r in last_results]): return 1 else: return 100 ``` This bot prefers to cooperate and count to `100`, but if the opponent tries to troll it, it pulls the trigger and only counts to `1` for the rest of the round. [Answer] # Hawk A quick internet search reveals hawks eat pythons >:). This strategy takes the average, weighted a bit, of the winning scores and returns its floor, or 47 at the beginning. Purely functional and not python >:). --- A Pure Python version (untested), courtesy of caird coinheringaahing: ``` def strategy(last_results): if not last_results: return 47 return max(1, min(50, sum(map(lambda t: t[0], last_results)) // (len(last_results)*1.5))) ``` --- ## In [Hy](http://hylang.org/) ``` (defn strategy [last-results] (if last-results (max 1 (min 50 (// (reduce + (map (fn[t] (get t 0)) last-results)) (* 1.5 (len last-results))))) 47)) ``` ]
[Question] [ March 13 is recognized as [National Jewel Day](http://www.nationaldaycalendar.com/2017/03/12/362971/), which is the theme of this challenge. So, given an integer `n` where `n` is greater than 0, create an ASCII jewel. For example: ``` n = 1 n = 2 n = 3 ______ ____ / \ __ / \ \ / / \ \ / \ / \ / \ / \ / \/ \/ \/ ``` The bottom is defined as the very bottom of the jewel to the highest pair of of `\/`. The rest is the top. For the above example where `n = 1`: ``` Bottom: \ / Top: __ \/ / \ ``` As you can see, the bottom is made of `n + 1` layers of `\/` with `(1 * lines from the bottom) * 2` spaces in between with a maximum of `n` lines from the bottom of the jewel. If we take the second jewel (`n = 2`), we can see that: ``` ____ / \ \ / 2 (or n) layers from the bottom with 1*2*2 or 4 spaces in between \/ \ / 1 layer from the bottom with 1*1*2 or 2 spaces in between \/ \/ The bottom (0 layers) with 1*0*2 spaces or 0 spaces in between \/ ``` The top is made of one pair of `/\` with `n*2` spaces in between with `n*2` underscores on top. **Rules** * Must be able to take in any nonzero positive integers as user input * Must create a jewel with the specs defined above (restated here): + The top is made of one pair of `/\` with `n*2` spaces in between with `n*2` underscores on top. + The bottom is made of `n + 1` layers of `\/` with `(1 * lines from the bottom) * 2` spaces in between with a maximum of `n` lines from the bottom of the jewel. * Trailing newlines after the jewel, or trailing spaces on each line are allowed. * No standard loopholes allowed **Winning Criteria** Least bytes wins! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes Code: ``` NβG←β_↙↙¹→↘⁺β¹‖M→ ``` Explanation: ``` Nβ # Place the input into β G←β_ # Draw a line of length β with _ as the filling character ↙ # Move the cursor one down and one left ↙¹ # Draw a line from the cursor position to one position ↙ → # Move the cursor 1 to the right ⁺β¹ # Add one to the input and.. ↘ # Create a line pointing ↘, with the size calculated above ‖M→ # Mirror to the right ``` A *very neat* command is `‖M`, which also automatically mirrors `/` into `\`. Uses the [**Charcoal** encoding](https://github.com/somebody1234/Charcoal/wiki/Code-page). [Try it online!](https://tio.run/nexus/charcoal#@/9@z7pzm97vWf6obcK5TfGP2mYC0aGdj9omPWqb8ahx17lNQE7DtPd71gKF/v83BgA "Charcoal – TIO Nexus") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~27~~ 20 bytes ``` ƒN·ð×…\ÿ/}¹·'_×)R.c ``` [Try it online!](https://tio.run/nexus/05ab1e#ASMA3P//xpJOwrfDsMOX4oCmXMO/L33DgsK5wrcnX8OXKVIuY///Mw "05AB1E – TIO Nexus") **Explanation** ``` ƒ # for N in range[0 ... n] N·ð× # push N*2 spaces …\ÿ/ # push the string "\ÿ/" with "ÿ" replaced by the spaces } # end loop  # push a reversed copy of the top of the stack # (the largest row of the bottom of the diamond) ¹·'_× # push input*2 underscores ) # wrap the stack in a list R # reverse the list .c # join the list on newlines, padding each row to equal length ``` [Answer] # Python 2, 101 98 95 bytes ``` lambda n:'\n'.join([' '+'__'*n,'/'+' '*n+'\\']+[' '*i+'\\'+' '*(n-i)+'/'for i in range(n+1)]) ``` [Try it Online!](https://tio.run/nexus/python2#RcpLCgIxEIThvafoXaWnfTC6EzyJGYaIRlq0ZgjeP0ZF3H3FX/kQ6z09Tuck3CMS69vkDEcIDOOIjktsGkUaDTFisHfs/DO@IXDlau2XpyIuTimJ10ug9TponYvzKTn0uvhx@@dO6ws) Anonymous function that takes in a positive integer and returns a string # Python 3.6, 92 bytes (Thanks to Ben Frankel) ``` lambda n:f' {"__"*n}\n/{" "*n}\\\n'+'\n'.join(' '*i+'\\'+' '*(n-i)+'/'for i in range(n+1)) ``` I couldn't find an online interpreter for this version, but it is a bit shorter due to f-strings in v3.6 [Answer] # PHP, 123 Bytes ``` echo($s=str_pad)(" ",$z=1+2*$a=$argv[1],_).$s("\n/",$z+1," ")."\\\n";for($i=0;$i<=$a;)echo$s($s("",$i)."\\",$z-$i++)."/\n"; ``` ## 143 Bytes first version ``` for(;$i<3+$a=$argv[1];$i++)echo 1-$i?str_pad("",$i?$i-2:1):"/",str_pad($i>1?"\\":"",$i<2?2*$a:2*($a-$i+2)+1,$i?" ":_),$i<2?$i?"\\":"":"/","\n"; ``` [Try it here!](https://tio.run/nexus/php#NYzNDoMgEIRfxWz2AK6mYb2ttDxIaQzpn1wqoU1fn6Kmx29mvrEuzak8lqxGjHYgDEcM@fk9m0sNiPT9Oi@N6TG69ydPKdwUQFcJY89itMABun@D8WQceA@ybSw7bjEItwpDfSDWZFYXGpBJ74sVd2O7Av@CsZQy/AA) [Answer] # [V](https://github.com/DJMcMayhem/V), ~~28~~ ~~27~~ 26 bytes *1 bytes saved thanks to @DJMcMayhem by using `>` instead of `É`* ``` Ài__<esc>É ÙÒ r/Á\Ùr\$r/òÙlxx> ``` `<esc>` is `0x1b` [Try it online!](https://tio.run/nexus/v#@3@4ITM@Xvpwp8LhmYcnKRTpH26MOTyzKEYFyNp0eGZORYXd////jQE "V – TIO Nexus") Hexdump: ``` 00000000: c069 5f5f 1bc9 20d9 d220 722f c15c d972 .i__.. .. r/.\.r 00000010: 5c24 722f f2d9 6c78 783e \$r/..lxx> ``` ### Explanation Top: ``` Ài__<esc> " Write argument times __ É<space> " Prepend a space to the line Ù " Duplicate line below cursor, cursor also moves down Ò<space> " Replace every character with a space r/ " Change the first character in the line to a / Á\ " Append a \ to the end of the line ``` Bottom: ``` Ù " Duplicate r\ " Change the first character in the line to a \ $r/ " Replace the last character with a / ò " Until a breaking error occurs do: Ù " Duplicate lxx " Remove 2 middle characters (spaces) > " Indent by one space (implicit ending >) " Implicit ending ò ``` [Answer] # [Röda](https://github.com/fergusq/roda), 71 bytes ``` f n{a=" ";[a,"__"*n," /",a*2*n,`\ `];seq n,0|[a*(n-_),`\`,a*2*_1,"/ "]} ``` [Try it online!](https://tio.run/nexus/roda#Hcq7CoNAEEbhOv9TDFPFZYKuxksQn8TI7hQRUjgQUqrPvord4eOkmWzVgYn7UYVDYGfCyFnUlWfGN@LU/z8/Mim2Ud3dHiE7OV5D8MI5eNrTol@jFbeZKuzJo0SFJ2o0aNHhBV8c "Röda – TIO Nexus") [Answer] ## JavaScript (ES6), 80 bytes ``` f= n=>` ${"_".repeat(n*2)} /${s=" ".repeat(n)}${s}\\`+s.replace(/|/g,"\n$`\\$'$'/") ``` ``` <input type=number oninput=o.textContent=f(this.value)><pre id=o> ``` [Answer] # C, 131 bytes ``` i;f(n){for(printf(" ",i=0);i++<n*2;)printf("_");for(printf("\n/%*c\n",n*2+1,92,i=0);i++<n+1;)printf("%*c%*c\n",i,92,(n-i)*2+3,47);} ``` [Try it online!](https://tio.run/nexus/c-gcc#TctBCsIwEEDRdXOKEhBmkkhNI4iM3iQgRQjMwqkEd6VnjxEqzfq/X5gSCC5pzvDOLJ8EuteO7ycktvYmZiT8h4dGamGU4WCeUbSrzHp3HZvR@n2saoP8QyBHxnoEd74graWi/jWxAKpFdQkCklrLFw) [Answer] # Python 3, ~~107~~ 105 Bytes ``` n,s=int(input())," " print(s+n*"__","/"+n*2*s+"\\",*[i*s+"\\"+2*(n-i)*s+"/"for i in range(n+1)],sep="\n") ``` Takes an int from Stdin [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 76, 74 bytes ``` param($n)" "+'_'*2*$n;"/$(' '*$n*2)\";$n..0|%{' '*($n-$_)+"\$(' '*$_*2)/"} ``` Note: the online example contains a bit of wrapping as a demonstration. Place in a PoSH function or script to execute. [Try it online!](https://tio.run/nexus/powershell#LcpBCoAgEEDRq8gwZSqpCa08Soq4apVELcuzT0btPp9HmI/1XGzU@qsp3t3VX3s@8jZgEcBA8cSlk1g8GBw44y2lEwE8Fq1t8@9reMQkFITfpGYM1MowVSKyND8 "PowerShell – TIO Nexus") [Answer] # [MATL](https://github.com/lmendo/MATL/), 34 bytes ``` QE:qgOO(t~E3O(GQXy3*tPgEhv'_/\ 'w) ``` Try it at [MATL Online!](https://matl.io/?code=QE%3AqgOO%28t%7EE3O%28GQXy3%2atPgEhv%27_%2F%5C+%27w%29&inputs=3&version=19.8.0) ### Explanation ``` QE:qg % Create array [0 1 1 ... 1 1] of size2*(n+1) OO( % Turns last 1 into a 0: [0 1 1 ... 1 0] t~ % Duplicate and negate: [1 0 0 ... 0 1] E3O( % Multiply by 2, turn last 2 into 3: [2 0 0 ... 0 3] GQXy % Push identity matrix of size n+1 3* % Multiply by 3 tPgE % Duplicate, flip, turn 3 into 2 h % Concatenate the two matrices horizontally v % Concatenate all arrays vertically into a matrix '_/\ ' % Push this string w) % Index (modular, 1-based) with the matrix into the string. Implicitly display ``` [Answer] # Pyth, 44 Bytes ``` +" "*Q"__"++\/**2Qd\\jm+++*d\ \\**2-Qd\ \/hQ ``` [try it!](https://pyth.herokuapp.com/?code=%2B%22+%22%2aQ%22__%22%2B%2B%5C%2F%2a%2a2Qd%5C%5Cjm%2B%2B%2B%2ad%5C+%5C%5C%2a%2a2-Qd%5C+%5C%2FhQ&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6&debug=0) ### explanation The code consists of 3 parts: ``` +" "*Q"__" # pretty straightforward " "+input()*"__" ++\/**2Qd\\ # d is defined as " ": "/"+2*input()*d+"\" jm+++*d\ \\**2-Qd\ \/hQ # The third part is a bit more complex so I'll explain it further: jm hQ # Map some lambda function onto range(input()+1) and join the result on newlines +++*d\ \\**2-Qd\ \/ # Here d is the lambda argument (so I can't use it for spaces -.-) +++*d\ \\**2-Qd\ \/ # In Python: d*" "+"\\"+2*(Q-d)*" "+"/" ``` [Answer] # Python3, 104 bytes ``` n=int(input());print(" "+"__"*n+"\n/"+" "*n+"\\") for i in range(n+1):print(" "*i+"\\"+" "*(n-i)+"/") ``` The program takes an integer from STDIN and returns the jewel into STDOUT. [Answer] # [Pip](https://github.com/dloscutoff/pip), 43 bytes 42 bytes of code, +1 for `-n` flag. ``` Ps.'_Xa*2P"/\"JsXa*2sX_.'\.sXa-_X2.'/M,a+1 ``` Takes input as a command-line argument. [Try it online!](https://tio.run/nexus/pip#@x9QrKceH5GoZRSgpB@j5FUMYhZHxOupx@gB2brxEUZ66vq@Oonahv///9fN@28CAA "Pip – TIO Nexus") ### Explanation Constructs the first two lines separately, then the rest of the jewel with a map operation: ``` Ps.'_Xa*2 a*2 Cmdline arg, times 2 '_X That many underscore characters s. Concatenated to a space character P Print (with newline) P"/\"JsXa*2 a*2 Cmdline arg, times 2 sX That many space characters "/\"J Join the string "/\" with the above as the separator P Print (with newline) sX_.'\.sXa-_X2.'/M,a+1 ,a+1 Numbers from 0 up to and including a M Map the following lambda function: sX_ Space, repeated (fn arg) times .'\ Concatenate \ . Concatenate: sXa-_ Space, repeated (a - (fn arg)) times X2 repeated twice .'/ Concatenate / Print result list, newline separated (implicit, -n flag) ``` ### Another solution Also 42+1 bytes, this time with the `-l` flag: ``` Ys.tAL'_.sX2+,a.0(yALRVyRXD1-_)R0'\R1'/ZDs ``` [TIO](https://tio.run/nexus/pip#@x9ZrFfi6KMer1ccYaStk6hnoFHp6BMUVhkU4WKoG68ZZKAeE2Sorh/lUvz//3/dnP8mAA) [Answer] # Pyth, 38 bytes ``` j[*yQ\_j*yQpd"/\\"jm+*\ dj*\ y-Qd"\/"h ``` [Answer] # C, 115 bytes ``` #define p printf( i;j;f(n){for(p" ");i++<n;p"__"));for(p"\n/%*c",2*n+1,92);j<=n;p"\n%*c%*c",++j,92,n*2-j*2+3,47));} ``` [Try it online!](https://tio.run/nexus/c-clang#JY1BCsIwEEX3OcUQEWYyETEKRabepFBEG0jAaSjuSs8eo27f@49fd88pJp2gQFmSviOaJFkiKq1xXrBYsCSJuVcpdhwtkfz5oMe9e1gfnPLJXwNJ7m/f0aCN/xRzbsKrC4fsAp/9pWv5Zkw7gtc9KRKsBgAidiQGtlo/ "C (clang) – TIO Nexus") # C, 123 bytes Though the challenge doesn't require it, at the expense of 8 bytes the function can be made reusable (the first solution saves 8 bytes by relying on the implicit initialization of global variables). ``` #define p printf( i;f(n){for(i=0,p" ");i++<n;p"__"));for(i=0,p"\n/%*c\n",2*n+1,92);i<=n;p"%*c%*c\n",++i,92,n*2-i*2+3,47));} ``` [Try it online!](https://tio.run/nexus/c-clang#RY3BCsIwEETv@YolImSzEW0qlJL2TwpFtIE9uA3FW@m3xxQVb495w0w@PKbIMkGCtLC8olEcohFc47wY7i8uadAYmKiTkPQ4asTwd4Ocj/Y@iHbeClWu9aXb9Xu15F9FxEU4sf7E1lPtrk0Z2ZQqh/C8sRiEVQFANBWGD/gf1DtsOb8B "C (clang) – TIO Nexus") [Answer] ## Batch, 152 bytes ``` @set s= @for /l %%i in (1,1,%1)do @call set s= %%s%% @echo %s: =_% @echo /%s%\ @set s=\%s%/ :l @echo %s% @if %s:~-2%==/ set s=%s:\ = \%&goto l ``` Tests: ``` n = 1 __ / \ \ / \/ n = 2 ____ / \ \ / \ / \/ n = 3 ______ / \ \ / \ / \ / \/ ``` [Answer] **C#, 187 bytes** I'm sure there is a more compact solution out there but this is my first attempt: ``` var a=" "+new string('_',2*n)+"\n/"+new string(' ',2*n)+"\\\n";for(int i=n;i>0;i--){a+=new string(' ',n-i)+"\\"+new string(' ',2*i)+"/\n";}a+=new string(' ',n)+"\\/";Console.Write(a); ``` [Try it online..](https://dotnetfiddle.net/19IOXF) [Answer] ## JavaScript (ES6), 93 bytes ``` n=>(` 0 /2\\`+` 1\\4/`.repeat(k=++n)).replace(/\d/g,c=>' _'[+!+c].repeat(c&1?k-n-2:+c+--n*2)) ``` ### Demo ``` let f = n=>(` 0 /2\\`+` 1\\4/`.repeat(k=++n)).replace(/\d/g,c=>' _'[+!+c].repeat(c&1?k-n-2:+c+--n*2)) console.log(f(1)) console.log(f(2)) console.log(f(3)) ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 121 bytes ``` ?d1+sa2*sb32P[0sq[lvPlq1+dsqlj>h]shlj0<h]srlbsj95svlrx2607Plbsj32svlrx[\]p0sd[ldsjlrx92Plbsjlrxlb2-sb[/]pld1+dsdla>k]dskx ``` [Try it online!](https://tio.run/nexus/dc#HcxBCoMwFATQ@1TE@KWKUOwVsk@zSPyFED@tcUC8eNdpdDXzGJj85LaCoxt8R9ooJCO7ltRWjCRxChZBonqU3MQjjnfssh3Uq0Gf7uiyedlVgY0wYuFI11iaeKrhTWNX4fOTxU2LZSxHzoP6fb717Obw/gM "dc – TIO Nexus") [Answer] # Perl 5 109 94 + 1 (for flag -p) = 95 Bytes [Try it Online!](https://tio.run/nexus/perl5#U1YsSC3KUdAt@K@SY6sSr2VkzaVSbKukoKSnFK9UoZKjpxSTpw/kKEA5MTF5SiAlerZgoXiQEERaQyVHF2SApp6SPlBRWn6RgoGenkq8NVdBUWZeiUrx//@GBgA) ``` $l=$_*2;$s=" "."_"x$l."\n/"." "x$l."\\\n";$s.=" "x$_."\\"." "x($l-$_*2)."/\n"for 0..$_;print$s ``` Can be run like so: ``` perl -p <name of file> <<< n ``` **Ungolfed** ``` $l=$_*2; $s=" "."_"x$l."\n/"." "x$l."\\\n"; $s.=" "x$_."\\"." "x($l-$_*2)."/\n"for 0..$_; print$s ``` **Explanation** ``` #Sets $l to twice the value of the input 'n' $l=$_*2; #Top 2 rows of jewel adding $l underscores then newline #followed by '/' and $l spaces. The '\\\n' is an escaped '\' and a newline $s=" "."_"x$l."\n/"." "x$l."\\\n"; #The meat of the jewel generation. It contains a for-loop #that iterates from 0 to $_ (the input value 'n') #The loop uses its iterator value ($_ (which overrides the outer $_)) #to determine how many leading spaces it needs to apply. #Then it adds a '\' with '\\' followed by $l-$_*2 number of spaces #(the inside of the jewel). Again, while under the umbrella of the for-loop, #the $_ refers to the iterator value of the for-loop. #After the inner spaces, it goes on to add in the '/' and a new line $s.=" "x$_."\\"." "x($l-$_*2)."/\n"for 0..$_; #Lastly, it prints the compiled Scalar value $s. (In Perl, Strings are Scalar values or references print$s ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 29 bytes ``` ð₴d\_*,\/₴d\\꘍,›(n\\꘍₴nεd\/꘍, ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C3%B0%E2%82%B4d%5C_*%2C%5C%2F%E2%82%B4d%5C%5C%EA%98%8D%2C%E2%80%BA%28n%5C%5C%EA%98%8D%E2%82%B4n%CE%B5d%5C%2F%EA%98%8D%2C&inputs=3&header=&footer=) ``` === The top === ð₴d\_*, ð # ' ' ₴ # Print without newline d # (implicit input) doubled \_* # That many underscores , # Output with newline === Line 2 === \/₴d\\꘍, \/ # Forward slash ₴ # Print without newline d # (implicit input) doubled \\꘍ # That many spaces, plus a backslash , # Output with newline === The rest === ›( # (implicit input) incremented times do... n # Iteration number... \\꘍ # ...spaces plus a backslash ₴ # Print without newline nε # Difference of iteration number and (implicit input) d. # Doubled \/꘍ # That many spaces, plus a forward slash , # Output with newline ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 12 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` _× ;+/∔⁸╵\∔║ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=XyVENyUyMCV1RkYxQiV1RkYwQi8ldTIyMTQldTIwNzgldTI1NzUldUZGM0MldTIyMTQldTI1NTE_,i=NQ__,v=8) right tool for the job. ]
[Question] [ In this [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge, robbers must crack cop answers by finding out which languages the cops used. This is the **Cops** thread. For the Robbers' challenge, see [here](https://codegolf.stackexchange.com/q/212069/66833) Cops, you are to write a program, which, when executed in a specific language, does one of the following: 1. Outputs one of the 5 phrases below 2. Outputs a piece of code, which when executed in a specific language (not necessarily the same language as the first program), does either point 1. or point 2. This may be either a function or a full program, and should [output in a reasonable method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) That is, the first program should output the code for the second, which outputs for the third, and so on, until the final program outputs one of the below phrases. If any of the codes uses non-ASCII characters, you should output the *bytes* that represent the program, not the characters. None of the programs may be longer than \$65535\$ bytes long, to keep it somewhat sane. **You may repeat languages**, but the languages you choose should all meet all of the following criteria: * It has [an English Wikipedia article](https://en.wikipedia.org/wiki/Lists_of_programming_languages), [an esolangs.org article](http://esolangs.org/wiki/Language_list) or [a Rosetta Code article](http://rosettacode.org/wiki/Category:Programming_Languages) at the time this challenge was posted, or is on [Try It Online!](https://tio.run/#). Having an interpreter linked in any of these pages makes that interpreter completely legal. + Given that the influx of languages to TIO has been paused, languages that [have been requested to be added](https://gist.github.com/cairdcoinheringaahing/46f79623ea7b5cfe67286d0a5e96d307), but haven't yet been added, are also legal languages * It must satisfy our rules on [what constitutes a programming language](http://meta.codegolf.stackexchange.com/a/2073/8478) * It must have a free interpreter (as in beer), per [site standards](https://codegolf.meta.stackexchange.com/q/7822/66833) for [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") posts The phrases you may choose from are: * `Game Over!` * `Greetings!` * `Code Golf.` * `It's Done.` * `The Last 1` Despite being a possible interpretation of the initial task, you may *not* write a program which simply outputs one of these phrases, to avoid the challenge being to similar to [an existing challenge](https://codegolf.stackexchange.com/questions/54807/the-programming-language-quiz). Your submission must use a **minimum of 2 languages** In your answer, you should reveal the following information: * The number of layers your submission has (note "layers", not "languages") * The initial code that will output all following layers (but *not* the language this code was written in) * The final outputted phrase The robbers will be attempting to guess the languages you've used for each layer. Each robber must crack your entire submission for it to be a valid crack. Note that a crack is valid *even if the languages are different*. So long as the robber's languages, in the order they state them, produce the specified final phrase, the crack is valid, even if the languages are not the same as yours. If your answer has not been cracked within 14 days, you can claim it as safe. You should reveal the languages used and the codes in said languages. Note that your answer is not safe until you've revealed the languages and code and robbers can still crack your answer until then. The submission which is safe and uses the **least amount of distinct languages** wins! ## Formatting Cops, please format your original answer as so: ``` # <N> layers <code> <Final output> --- ``` And, when cracked, please edit in the following format (underneath the `---`): ``` Languages used (in order): - [<language 1>](<link to interpreter>), outputted <output> - [<language 2>](<link to interpreter>), outputted <output> ... - [<language N>](<link to interpreter>), outputted <final phrase> --- <anything else> ``` and you should edit your header to read ``` # <N> layers, cracked by [<robber>](<link to robber's post>) ``` If your answer is safe, edit this into the title, along with the complete list of intended languages. **Your answer can still be cracked until you do**. Good luck! [Answer] # 840,527,321,220,386 layers, safe ``` D'`Aq9\n[;|FyDUv4tc+OMLKJJHZG4~ffT@RQ>v{)LxZponm3qSongled*bJ`_^$bD`_XW{[Z<RWVUNr54JONMFKDhH*)E>b%;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9qvo5VUkpoh.ledchg`_^$bDZ_^]VUyYRWPOsS5KPIm0/EDhH*)?>b%A@9]=6;492V6543210/('K+$)"Fg%${z@xwv{t:xZputm3TSohmlkd*bJ`_^$baZ~XW\UTx;QVONMqQ3IHGLEihBG@?cC%;@?>7[;:9870v.3,P*p.-&J$j"!E}eBz!x}vu;yxwpun4rqji/gfedcb(`H^]\"!_X]V[ZYXQuONMLKPOHlLEJCBf@(>b%;:^>=}|Y9876/SR,1*/.'K%*#"!Efe#z@~}v{zyr8vuWsl2ponmlkdcb(`H^]\"!_X]V[ZYXQuONMLKPOHlFKDhHAF?cC%$@9>7[54927654-Q1q/('K+$#Gh~%${z!x>|utsxq7uWmrk10nmledihg`&Gcb[`_^W{[ZYXW9OTSLKPImlFKDCgGFE>=B;_?>=6;:981U54321q)M-,%$#G'&}eB"!x}v{zyr8pun4Ukj0hmlkdcba'Hdcb[`_^W{[Z<;QPUNMLKo21GLEi,+GFE>=aA#9>7[;:9870v.3,P*)(-&J$j"!E}eBz!x}vu;yxZpo5VUkpoh.ledchg`_^$bDCYX]VzyS;WPOsSLKPOHGk.JCHGF?>b%A@9]=6;492V6543210/('K+$)"F&}|{Abaw|{zsr8Yutmrqj0nmleMib(fHdcb[!Y^]VUy<RWVUNrRQP2HGFjJCHA@?cC<;:^>=}|Y9876/.R,10/('K%*#G'&}eB"y~w=^zyrwp6tVUkpoh.ledchg`_^$baC_^WVzZYRWVUNrRQP2HGFjJIBfF?DCB;_?>=6;4X2765.R21qp.-&J$j"!E}eB"!x}v{zyr87unmlqj0QPfkjchg`&Gcb[`_^W{[=<XWPOsS54JOHlFKJIBA@E>b%;:^>=}|Y9270/.RQP0).-&J*)"'~D$#z!~}v<zyxqYun43kpoh.lkdcb(`H^]\"`_X]V[TxXWVO7SLQPIm0/EDhBf)(>=<`@"8=6Z:9yx0543,P*p.',%$H('&fe#z@x}v{zsr8Yutmrqj0nmleMib(fHdcb[!Y^]VUy<RWVUNr54JONMFKDhH*)E>b%;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9qvo5VUkpoh.ledchg`_^$bD`Y^WVUySXQPUNMq4JONMFjDIHGF?>C<`@9]7<543870T4321*/.'K%*#"!E}$#"!x>|{ts9qpon4lTjohmf,Mibg`_^$baC_^WVzZYRWVUNrLQJINGkK-CHGF?cC%;@?>7[;:981w/4-,PO)o'&%I)i'~%|B"yx>v{t:xqYun4rqpohg-ejihg`&Gcb[`_^W{[=<XWPOsrq4JONMFjDIHGF?>C<`@9>=6Z:98705.RQ1*/.'K%*#"!E}$#"!x>=u;yrwpo5mrk1onmfejib(fe^c\"Z_X|?UZYRvPOsSRKJIHl/KDCHAFE>C<`@"8=6Z:9yx0543,P0)o-,%$H('&fe#z@x}v{zsr8Yutmrqj0Qglkd*b(fHdc\"C_^WVzZSXQPOsSRQ3IHGLEiCBA@?cC<;:^>=}|Y9876/.R21*p.-&J$j"!E}eB"!~}_uzs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@9>=<5Y98765.-Q1*/.'K%*#"!E%|#"y?}vu;yxZputm3TSohmlkd*Ka`edc\"ZY}@?UZSRvVO7SLQPIm0/EDhH*)?>b<;:?8\6;492V05.3,10/('K+$)"Fg%${z@a}|uzs9wvuWsl2ponmlkdcb(`_%]\"C_^WVzZSXQPOsSRQP2HGFjJCHA@?cC<;:^>=}|Y9870T4-21*/(L&+$)"!E}eB"y~w=uzsr8vuWsl2ponmlkdcb(`_%]\"C_^WVzZSXQPOsSRQP2HGFjJCHA@?cC<;:^>=}|Y9876/.R,+Op(-&J*#i!&}C#cy~}|{zs9wvon4lTjohmf,Mibg`_^$bDCYX]VzTYXWVOsS5KPIm0/EDhBfF?DC<`@?>=6Z:9yx0543,Pqp.-&J*j('&}C#cy~}|{zs9wvuWsl2ponmlkdcb(`e^c\"`_X]V[TxRQVONMLp3INMFjD,HGF?DCB;_?>=6;4XW765432+*N.',%I#('~D$#z!~}v<zyxqYun4rqpohg-ejihg`&Gcb[`_^W{[=<XWPOsrq4JONMFjDIHGF?>C<`@9>=6Z:98705.RQ1*/.'K%*#"!E}$#"!x>=u;yrwpo5mrk1onmfejib(fe^c\"Z_X|?UZYRvP8TSRQJONMLEiCBA@?cC<;:^>=}|Y9270/.R21*N('&%I)i'~%|B"yx>|u]s9qYun4lkpi/gfedcb(`_%]\"C_^WVzZSXQPOsSRQP2HGFjJCHA@?cC<;:^>=}|Y9876/.R,10/('K%*#G'&}eB"!x}v{zyr8pun4Ukjong-eMiha`&dcbaZY}@V[TxXWVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bDCYX]VzZSXQVOsS5KPIm0/EDhHAF?c=<`#">76;4X8xw/.R21q/.'&J*j(!~D|#"!x>|uzyrwpo5mrk1onmfejib(fHdcb[!Y^]VUy<RWVUNrRQP2HGFjJCHA@?cC<;:^>=}|Y9876/.R,+Op(-&J*#i!&}C#"y~w=uzsr8vuWsl2ponmlkdcb(fHdc\"Z_^]V[TxXWVO7SLQPIm0/EDhHAF?c=<`#">76;4X8xw/.R21q/.'&J*j(!~D|#"!x>|uzyrwpo5mrk1onmfejib(fHdcb[!Y^]VUy<RWVUNrRQP2HGFjJCHA@?cC<;:^>=}|Y981U/4321*N.'K%*#"!Efe#z@x}|uzsr8vuWsl2ponmlkdcb(fHdcb[!Y^WV[TxXQuONMLKPOHlLEJIBG@d>C<;_?>7<;:3Wxw/.R21q/.'&J*j(!E}${A!x}|u;sr8Yutmrqj0Qglkd*)gfHdc\"C_^WVzZSXQPOs6LKoIHMFEiIH*)?>b%;:^>=}|Y9270/.RQP0).-&J*)"'~D$#z!~}v<zyxqYun43kpoh.lkdcb(`H^]\"`_X]V[TxXWVO7SLQPIm0/EDhBf)(>=<`@"8=6Z:9yx0543,P*p.',%$H('&fe#z@x}v{zsr8Yutmrqj0nmleMib(fHdcb[!Y^]VUy<RWVUNrRQ3IHGLEi,HAF?cC%$@9>7[54927654-Q1q/.-&J*j(!E%|B"yx>|{zyr8vo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bDZ_^]VUyYRWPOsS5KPIm0/EDhBf)(>=<`@"8=6Z:9yx0543,P0)o-,+$H"'~}$#z@x}v{zsr8Yutmrqj0nPfkjc)Jf_%]b[!_XW\UyYRQVONMLp3INGFEiIHG@(>b%;:^>=}|Y9270/.R2+0)('K+*j(!E%|B"yx>v{t:9wvonsl2SRhmlkd*bg`&^Fb[`Y^]VzZSRQVOsSRQ3IHGLEiIHGFED=aA#9>7[;:981w/4-,PON(L,%*#"!E}$#"!x>|{ts98vuWsl2ponmlkdcb(`e^c\"!_^]\[TxRWVUNrRQPON0/EDhBfF?DC<`@?>=6Z:9yx0543,P0)o-,%$H('&}|B"baw|{zsr8Yutmrqj0nmleMib(fHdcb[!Y^]VUy<RWVUNrRQP2HGFjJCHA@?cC<;:^>=}|Y9870T4-21*/(L&+$)"!E}eB"y~w=uzsr8vuWsl2ponmlkdcb(`H^]\"Z_XWVzZ<XWPOsSLKPOHGkKJIH*)E>bB;:?>=6Z:98765432+*N.',%I#('~D|#"!~}v<tsr8vuWsl2ponmlkdcb(`e^c\"ZY}@?UZSRvVO7SLQPIm0/EDhBf)(>=<`@"8=6Z:9yx0543,P*p.',%$H('&fe#z@x}v{zsr8Yutmrqj0Qmf,dc)gfedcbaZ~^]VUTSwWPUTSLpJOHlFKDCgGFE>=B;_9876;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwWV87SLKoO1GLEi,HGF?DCB;_?>=6;:981UT4321*N('&J*j(!Efe{"y?}_uzsr8vuWsl2ponmlkdcb(`_%]\"C_^WVzZSXQPOsSRQP2HGFjJCHA@?cC<;:^>=}|Y9876/.RQ1*N('&J*j(!~D|#"!x>|uzyrwpo5mrk1ongf,diba'eGcba`_X|V[ZSXQuONMLKPOHlLEDIHG@dDCB;@9]7<5492V05.3,10/('K+*)('~D$#"!x>|uzyrwpo5mrk1onmfejib(`edcb[Z~XW\UTx;QVONMqQ3IHGLEihBG@?cC%;@?>7[;:981w543,P0)o-,+$Hi'~%${z!x>|utsxq7uWmrk1Rnmle+cha`&dcbaZY}@VzZSRQVONr5KPIm0/EDhHAF?c=<A:?>7[5:3876/St,10/(L,+*#i!&}C{"!x>|{ts9wvunVrk1onmfe+cKa`_^$baC_^WVzyYXQ9UNSRKoO1GLEi,HGF?DCB;_?>=6;4X2765.R,1*/('&J$j"!E}eB"!x}v{zyr876tslk1Rhmf,jihg`e^$\aZ_^]V[TxwQPUTSRKJnN0/EDhH*)?>b%$:?>7[;:32V0v43210/.'&J*)('~D$#"!x>|uzyrwpo5mrk1onmfejib(fHdcb[!Y^]VUy<RWVUNrRQP2HGFjJCHA@?cC<;:^>=}|Y9876/.R,+Op(-&J*#i!&}C#cy~}|{zs9wvotsrk1inmlejib(I_dcbaZYX|\[Z<;QVUNMRKoO10FKDhBG@?cC%;@?>7[;:981w543,P0)o-,+$Hi'~%${z!x>|utsxq7utVlkjoh.fNdc)a`edcb[!_XW\UySwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#"y~w=^zyrwp6tVUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#zb~w|{t:xwpon4lkpi/gfedcb(fHdcb[!Y^WV[TxXQuONMLKPOHlLEJIBG@d>C<;_?>7<;:3Wxw/.R21q/.'&J*j(!E}${A!x}|u;sr8Yutmrqj0Qglkd*)gfHdc\"C_^WVzZSXQPOs6LKoIHMFEiIH*)?>b%;:^>=}|Y9270/.RQP0).-&J*)"'~D$#z!~}v<zyxqYun43kpoh.lkdcb(`e^c\"!_^]\[TxRWVUNrRQPON0/EDhBfF?DC<`@?>=6Z:9yx0543,P0)o-,%$H('&fe#z@x}v{zsr8Yutmrqj0Qglkd*b(fHdc\"C_^WVzZSXQPOsSRQ3IHGLEiI+AF?cCBA@9>7[54927654-Q1q/.-&J$)"!Ef|{z!x>|utsxq7utVlkjoh.fNdc)a`edcb[!_XW\UyYXWPUTSLpJImGLKDCgGFE>=B;_9876;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bDCYX]VzZSXQVOsS5KPIm0/EDhHAF?c=<`#">76;4X8xw/.R21q/.'&J*j(!~D|#"!x>|uzyrwpo5mrk1onmfejib(fHdcb[!Y^]VUy<RWVUNrRQP2HGFjJCHA@?cC<;:^>=}|Y9876/.R,+Op(-&J*#i!&}C#cy~}|{zs9wvon4lTjohmf,Mibg`_^$bDCYX]VzyS;WPOsSLKPOHGk.DCHAFE>b<;:?8\6;492V05.3,10/('K+*)('~D$#"!x>|uzyrwpo5mrk1onmfejib(fHdcb[!Y^]VUy<RWVUNrRQP2HGFjJCHA@?cC<;:^>=}|Y981U5.-210/(L,+*#G'&}eBz!x}vu;yxwpon4lkpi/gfedcb(fHdcb[!Y^WV[TxXQuONMLKPOHlLEJIBG@d>C<;_?>7<;:3Wxw/.R21q/.'&J*j(!E}${A!x}|u;sr8Yutmrqj0Qglkd*)gfHdc\"C_^WVzZSXQPOs6LKoIHMFEiIH*)?>b%;:^>=}|Y9270/.RQP0).-&J*)"'~D$#z!~}v<zyxqYun43kpoh.lkdcb(`H^]\"`_X]V[TxXWVO7SLQPIm0/EDhBf)(>=<`@"8=6Z:9yx0543,P*p.',%$H('&fe#z@x}v{zsr8Yutmrqj0nmleMib(fHdcb[!Y^]VUy<RWVUNrRQ3IHGLEi,HAF?cC%$@9>7[54927654-Q1q/.-&J*j(!E%|B"yx>|{zyr8vo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bDCYX]VzyS;WPOsSLKPOHGk.DCHAFE>b<;:?8\6;492V05.3,10/('K+*)('~D$#"!x>|uzyrwpo5mrk1onmfejib(fe^c\"Z_X|?UZYRvP8NSLQPOHGFjJCHA@?cC<;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9wvon4lTjohmf,Mibg`_^$bD`YXW\UZSwWV87SLKoO1GLEi,HGF?DCB;_9876;4X87w/43,Pqp.',%I#('~Dedz@~}v<]yxwpo5mrk1ongf,dcbaf_%]ba`_XW{[Z<RWVUNrLQJINGkjJIH*)ED=a;@9]=}|Y9270/.RQ+0)('K+*#G'&}eB"!x}v{zyr8vunsl2johmled*Kg`&Gcb[`_^W{[=<XWPOsr54JOHlLEJIHGF?cC%;@?>7[;:981w/4-,PO)o'&%I)i'~%|B"yx>|u]s9qYun4lkpi/gfedcb(`H^]\"`_X]V[TxXWVO7SLQPIm0/EDhBf)(>=<`@"8=6Z:9yx0543,P*p.',%$H('&fe#z@x}v{zsr8Yutmrqj0nmleMib(fHdcb[!Y^]VUy<RWVUNrRQP2HGFjJCHA@?cC<;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9qvo5VUkpoh.ledchg`_^$bDZ_^]VUyYRWPOsS5KPIm0/EDhBf)(>=<`@"8=6Z:9yx0543,P*p.',%$H('&fe#z@x}v{zsr8Yutmrqj0nPfkjc)Jf_%]b[!_XW\UyYRWVUTMLKoONMLEDhHGFE>=a;@?8\<549870T.-,+*N.nm%$)"Fg%|{z!x>|utsxq7unVrk1ih.fejib(IH^cbaZ~^@VUTSw:PUNMLpoINMFKDhBAF?cC%;@?>7[;:981w/4-,P*p.-&J*)"'~D$#"y~}|u;yxZponm3qSihg-,+cha`&dcbaZY}WVUyS;QVUNrqKPONGkK-IBGF?cC<$:?>7<;4981Uvu-2+Op(-&J*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#c!~wv<zyr8vuWsl2ponmlkdcb(`_%]\[!Y^]\Uy<RWVUNrRQP2HGFjJCHA@?cC<;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#"y~w=^zyrwp6tVUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#zb~w|{t:xwpon4lkpi/gfedcb(fHdcb[!Y^WV[TxXQuONMLKPOHlLEJIBG@d>C<;_?>7<;:3Wxw/.R21q/.'&J*j(!E}${A!x}|u;sr8Yutmrqj0Qglkd*)gfHdc\"C_^WVzZSXQPOs6LKoIHMFEiIH*)?>b%;:^>=}|Y9270/.RQP0).-&J*)"'~D$#z!~}v<zyxqYun43kpoh.lkdcb(`e^c\"!_^]\[TxRWVUNrRQPON0/EDhBfF?DC<`@?>=6Z:9yx0543,P*p.',%$H('&fe#z@x}v{zsr8Yutmrqj0nPfkjc)Jf_%]b[!_XW\UyYRWVUTMLKoONMLEDhHGFE>=a;@?8\<549870T.-,+*N.nm%$)"Fg%|{z!x>|utsxq7unVrk1ih.fejib(IH^cbaZ~^@VUTSw:PUNMLpoINMFKDhBAF?cC%;@?>7[;:981w/4-,P*p.-&J*)"'~D$#"y~}|u;yxZponm3qSihg-,+cha`&dcbaZY}WVUyS;QVUNrqKPONGkK-IBGF?cC<$:?>7<;4981Uvu-2+Op(-&J*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#c!~wv<zyr8vuWsl2ponmlkdcb(`_%]\[!Y^]\Uy<RWVUNrRQP2HGFjJCHA@?cC<;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@9>=<5YX210T43,10/.'&J*j(!~D|#"!x>|uzyrwpo5mrk1ongf,diba'eGcba`_X|V[ZSXQuONMLKPOHlLEJCBfFE>C<;_98765Y9yx0543,P*p.',%$H('&fe#z@x}v{zsr8Yutmrqj0nmleMib(fHdcb[!Y^]VUy<RWVUNrRQP2HGFjJIBA@E>b%;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9qvo5VUkpoh.ledchg`_^$bDCYX]VzTYXWVOsS5KPIm0/EDhBf)EDC<;_98765Y9yx0543,P*p.',%$H('gf|B"baw|{zsr8Yutmrqj0nmleMib(`edcb[Z~XW\UTx;QVONMq4JINGLKDhHG)(D=a;@9]=}|Y9876/S321q)M-,%$#G'&}eB"!x}v{zyr8vunsl2ponmleMib(IH^cbaZ~^@VUTSw:PUNMLp3INGFEi,HAF?cC%$@9>7[54927654-Q1qp.-&JI#"!~}Cd"!x}|{t:xZponm3qSihg-kdchgf_%]\aZ_^]VzZSXWVOsSRQPON0/EDhHAF?cba;:?8=6Z:9yx0543,Pqp.-&J*j('&}CB"baw|{zsr8Yutmrqj0Qmf,diha'_d]\[!_XW\UySwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bDCYX]VzTYXWVOsS5KPIm0/EDhBfF?DC<`@?>=6Z:9yx0543,P*p.',%$H('&fe#z@x}v{zsr8Yutmrqj0nmleMib(fHdcb[!Y^]VUy<RWVUNrRQP2HGFjJCHA@?cC<;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}|u]s98vuWsl2ponmlkdcb(`H^]\"Z_^WV[TxXQuONMLKPOHlLEJIBG@d>C<;:9]=<;492V0/.-Q10/('K+$H('gf|B"baw|{zsr8Yutmrqj0Qglkd*Kgfedc\"Z_XW\UyYXQuONMLKPOHlFKDhH*)ED=a;@9]=}|Y9876/.R21q)M-,%$#G'&}eB"!~}_uzs98vuWsl2ponmlkdcb(`H^]\"`_XW\UZSwQVOTSRKoON0/EDhH*)?>b%A@9]=6;492V6543210/('K+$)"F&}|{A!aw|{t:xZputm3TSohmlkd*Kgfed]#aZ_XWVzZYXQuONMLKPOHlLEJCBf@(>b%;:^>=}|Y981U5.-,+O/.'K%*#"!Efe#z@?wv{zsr8Yutmrqj0nPfkjc)a`ed]\"C_^WVzZSXQPOs6LKoIHMFEi,HAF?cC%$@9>7[54927654-Q1q/.-&J*#i'&}C#"!x}|u;yxZponm3qSihg-kdchgf_%c\aZ~^]VUZSRv9ONMLKJIHl/KDCHAFE>bBA#"8\<5:3810T43,10/.'&J*j(!~Dedz@x`|uzyxwp6nmlkjong-kjibJ`_^$#aZB^WVzZSXQPOsSRQP2HGFjiIBfF?DCB;_?87<;:3W765.-Q1q).'K%*#"!Efe#z@x}|uzsr8vuWsl2ponmlkdcb(fHdcb[!Y^WV[TxXQuONMLKPOHlLEJIBG@d>C<;_?>7<;:3Wxw/.R21q/.'&J*j(!E}${A!x}|u;sr8Yutmrqj0Qglkd*)gfHdc\"C_^WVzZSXQPOs6LKoIHMFEiIH*)?>b%;:^>=}|Y9270/.RQP0).-&J*)"'~D$#z!~}v<zyxqYun43kpoh.lkdcb(`H^]\"`_X]V[TxXWVO7SLQPIm0/EDhBf)(>=<`@"8=6Z:9yx0543,P*p.',%$H('&fe#z@x}v{zsr8Yutmrqj0nmleMib(fHdcb[!Y^]VUy<RWVUNrRQ3IHGLEi,HAF?cC%$@9>7[54927654-Q1q/.-&J*j(!E%|B"yx>|{zyr8vo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X87w/43,Pqp.',%I#('~Dedz@~}v<]yxwpo5mrk1ingfe+iha'_d]#D`_X]VzZSRQPtTS54JImGLKDhHGF?DCB;_9876;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@9]7<543870T4321*/.'K%*#"!Efe#z@x}|uzsr8vuWsl2ponmlkdcb(`e^c\"`_X]V[TxXQPtTS5KPIm0/EDhHAF?c=<A:?>7[549870T43,+O).'&%*)(!E}$#"!x>={tyrqp6tsrqji/gfedcb(`e^c\"`_X]V[TxXW9OTSLKPImGkK-IBGF?c&BA:?>=<5YXWxw/.R21q/.'&J*j(!E}${A@x`|uzyxwp6nmlkjong-kjiKg`_dc\"`_X]V[TxXWVO7SLQPIm0/EDhBf)(>=<`@"8=6Z:9yx0543,P*p.',%$H('&fe#z@x}v{zsr8Yutmrqj0nmleMib(fHdcb[!Y^]VUy<RWVUNrRQ3IHGLEi,HAF?cC%$@9>7[54927654-Q1q/.-&J*j(!E%|B"yx>|{zyr8vo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#zb~w|{t:xwpon4lkpi/gfedcb(fHdcb[!Y^WV[TxXQuONMLKPOHlLEJIBG@d>C<;_?>7<;:3Wxw/.R21q/.'&J*j(!E}${A!x}|u;sr8Yutmrqj0Qglkd*)gfHdc\"C_^WVzZSXQPOs6LKoIHMFEiIH*)?>b%;:^>=}|Y9270/.RQP0).-&J*)"'~D$#z!~}v<zyxqYun43kpoh.lkdcb(`e^c\"!_^]\[TxRWVUNrRQPON0/EDhBfF?DC<`@?>=6Z:9yx0543,P0)o-,%$H('&fe#z@x}v{zsr8Yutmrqj0Qglkd*b(fHdc\"C_^WVzZSXQPOsSRQ3IHGLEiCBA@?cC<;:^>=}|Y9270/.R21*N('&%I)i'~%|B"yx>|u]s9wvonsrk1i/mlkdcb(`e^c\"ZY}@?UZSRvVO7SLQPIm0/EDhH*)?>b%$:?>7[;:32V0v43210/.'&J*j(!~D|#"!x>|uzyrwpo5mrk1ongf,diba'eGcba`_X|V[ZSXQuONMLKPOHlLEJCBf)(>=<`@"8=6Z:9yx0543,Pqp.-&J*#(!~Dedzy?}_{zyxwpo5mrk1onmfejib(fHdcb[!Y^]VUy<RWVUNrRQP2HGFjJIBGFE>b%;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwW9OTSLKPImGkK-IBGF?cCBA@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwWV87SLKoO1GLEi,HGF?DCB;_?>=<;4X8765.R21*/.'K%*#"!E%${A!xwv<]yxwpo5mrk1ingfe+cba'_d]baZ~^]VUTSw:PUNMLpJOHlLKDhBAF?cC%;@?>7[;:981w543,P0)o-,+$Hi'~%${z!x>|utsxq7utVlkjoh.fejiha'_d]#D`_X]VzZYRQu8NMq4JONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9wvunVl2pinmf,Mibg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9wvon4lTjohmf,Mibg`_^$bDCYX]VzTYXWVOsS5KPIm0/EDhBf)EDC<;_98765Y9yx0543,P0)o-,%$HG'~%|B"yx>|u]srq7onslkjongf,jiha`&dcbaZY}WVUyxXQPUTSLKPImGkK-IBGF?cCB;@?>7[5{3276/.-Q1q).'K%*#"!E%|#"y?}_uzs9wvuWsl2ponmlkdcb(fHdc\"`_^]\[TxXWVOTSRKoON0/EDhH*)?>b%A@?876Z43810T43,10/.'&J*j(!~Dedzy?}_{zyxwpo5mrk1onPle+ihgfeG]#aZB^WVzZSXQPOs6LKon10FKDhBG@?cC%;@?>7[;:981w543,P0/(L&%$)(!E}eB"!x}v{zyr8pun4rqSonmf,dcba'Hdcb[`_^W{[ZYXW9OTSLKPImGFKJIHG@dDC<;:^>=}|Y9810/.R2+*N.',%I#('~D${"!~}v<zyxwpon4lkpi/gfedcb(fHdcb[!Y^WV[TxXQuONMLKPOHlFKDhHG)(D=a;@9]=}|Y9270/.R2+0)('K+*)i!&}${Abaw|{zsr8Yutmrqj0Qglkd*Kgfedc\"Z_X|VUZYXQuONMLKPOHlLEJIBG@dc=<A@9876Z43810T43,10/.'&J*j(!E}${A!~}|u]s9qp6Wsrqpohg-kdiba`&%$bD`_XW{[Z<RWVUNrLQJINGkK-,BGF?cb%;:^>=}|Y9876/.R21*p.-&J$j"!E}eB"!~}_uzs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#c!~wv<zyr8vuWsl2ponmlkdcb(`_%]\[!Y^]\Uy<RWVUNrRQP2HGFjJCHA@?cC<;:^>=}|Y981U5.-210/(L,+*#G'&}eBz!x}vu;yxwpon4lkpi/gfedcb(fHdcb[!Y^WV[TxXQuONMLKPOHlLEJIBG@d>C<;_?>7<;:3Wxw/.R21q/.'&J*j(!E}${A!x}|u;sr8Yutmrqj0Qglkd*)gfHdc\"C_^WVzZSXQPOs6LKoIHMFEiIH*)?>b%;:^>=}|Y9270/.RQP0).-&J*)"'~D$#z!~}v<zyxqYun43kpoh.lkdcb(`e^c\"!_^]\[TxRWVUNrRQPON0/EDhBfF?DC<`@?>=6Z:9yx0543,P0)o-,%$H('&fe#z@x}v{zsr8Yutmrqj0Qglkd*b(fHdc\"C_^WVzZSXQPOsSRQP2HGFjJCHA@?cC<;:^>=}|Y981Uvu32+0)Mnm%$#(!E}eB"!~}|u]s9wvonsrk1i/mlkdcb(`e^c\"ZY}@?UZSRvVO7SLQPIm0/EDhH*)?>b%$:?>7[;:32V0v43210/.'&J*)('~D$#"!x>|uzyrwpo5mrk1onmfejib(fHdcb[!Y^]VUy<RWVUNrRQP2HGFjJIBA@E>b%;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9qvo5VUkpoh.ledchg`_^$bDCYX]VzTYXWVOsS5KPIm0/EDhBf)EDC<;_98765Y9yx0543,P*p.',%$H('gf|B"baw|{zsr8Yutmrqj0nmleMib(`edcb[Z~XW\UTx;QVONMqQ3IHGLEi,HAF?cC%$@9>7[54927654-Q1q/('K+*)i!Ef|{z!x>|utsxq7uWmrk1Rnmle+cha`&dcbaZY}WVUyS;QVUNrRQP2HGFjJIBfF?DCB;_?>=6;4X2765.R21qp.-&J$j"!E}eB"!x}v{zyr87unmlqj0QPfkjchg`&Gcb[`_^W{[=<XWPOsS54JOHlFKJIBA@E>b%;:^>=}|Y9270/.RQP0).-&J*)"'~D$#z!~}v<zyxqYun43kpoh.lkdcb(`H^]\"`_X]V[TxXWVO7SLQPIm0/EDhBf)(>=<`@"8=6Z:9yx0543,P*p.',%$H('&fe#z@x}v{zsr8Yutmrqj0nmleMib(fHdcb[!Y^]VUy<RWVUNrRQ3IHGLEi,HAF?cC%$@9>7[54927654-Q1q/.-&J*j(!E%|B"yx>|{zyr8vo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#zb~w|{t:xwpon4lkpi/gfedcb(fHdcb[!Y^WV[TxXQuONMLKPOHlLEJIBG@d>C<;_?>7<;:3Wxw/.R21q/.'&J*j(!E}${A!x}|u;sr8Yutmrqj0Qglkd*)gfHdc\"C_^WVzZSXQPOs6LKoIHMFEiIH*)?>b%;:^>=}|Y9270/.RQP0).-&J*)"'~D$#z!~}v<zyxqYun43kpoh.lkdcb(`e^c\"!_^]\[TxRWVUNrRQPON0/EDhBfF?DC<`@?>=6Z:9yx0543,P*p.',%$H('&fe#z@x}v{zsr8Yutmrqj0nmleMib(fe^c\"Z_X|?UZYRvP8NSLQPOHGFjJCHA@?cC<;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9wvunVl2pinmf,Mibg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9wvon4lTjohmf,Mibg`_^$bDCYX]VzZSXQVOsS5KPIm0/EDhHAF?c=<`#">76;4X8xw/.R21q/.'&J*j(!~D|#"!x>|uzyrwpo5mrk1onmfejib(fHdcb[!Y^]VUy<RWVUNrRQP2HGFjJIBGFE>b%;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwW9OTSLKPImGkK-IBGF?cCBA@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwWV87SLKoO1GLEi,HGF?DCB;_?>=<;4X8765.R21*/.'K%*#"!E%${A!xwv<]yxwpo5mrk1ongf,diba'eGcba`_X|V[ZSXQuONMLKPOHlLEJCBf)(>=<`@"8=6Z:9yx0543,P*p.',%$H('&fe#z@x}v{zsr8Yutmrqj0nmleMib(fe^c\"Z_X|?UZYRvP8NSLQPOHGFjJCHA@?cC<;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9wvunVl2pinmf,Mibg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9wvon4lTjohmf,Mibg`_^$bD`YXW\UZSwWV87SLKoO1GLEi,HGF?DCB;_9876;4X87w/43,Pqp.',%I#('~D$#z!~}v<tyxwvo5m3Tpohmlkd*bg`&^F\[ZY}W{[ZYXQuONMLKPOHlLEJIBG@d>C<;_?>7<;:3Wxw/.R21q/.'&J*j(!E}${A!x}|u;sr8Yutmrqj0Qglkd*)gfHdc\"C_^WVzZSXQPOs6LKoIHMFEiIH*)?>b%;:^>=}|Y9270/.RQP0).-&J*)"'~D$#z!~}v<zyxqYun43kpoh.lkdcb(`H^]\"`_X]V[TxXWVO7SLQPIm0/EDhBf)(>=<`@"8=6Z:9yx0543,P*p.',%$H('&fe#z@x}v{zsr8Yutmrqj0nmleMib(fHdcb[!Y^]VUy<RWVUNrRQ3IHGLEi,HAF?cC%$@9>7[54927654-Q1q/.-&J*j(!E%|B"yx>v{t:xqYun4Ukpoh.lkjiha`&dcbaZY}WVUyS;QVUNrLQJINGkK-CHGF?cC%;@?>7[;:981w/4-,PO)o'&%I)i'~%|B"yx>v{t:xqYun4rqpohg-ejihg`&Gcb[`_^W{[=<XWPOsrq4JONMFjDIHGF?>C<`@9>=6Z:98705.RQ1*/.'K%*#"!E}$#"!x>=u;yrwpo5mrk1onmfejib(fe^c\"Z_X|?UZYRvP8TSRQJONMLEiCBA@?cC<;:^>=}|Y9270/.R21*N('&%I)i'~%|B"yx>|u]s9qYun4lkpi/gfedcb(`_%]\"C_^WVzZSXQPOsSRQP2HGFjJIBGFE>b%;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwW9OTSLKPImGkK-IBGF?cCBA@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwWV87SLKoO1GLEi,HGF?DCB;_?>=6;:981U5.-Q1*/.'K%*#"!E}$#"!x>|u;sxwvonm3Tpohmlkd*bg`&^F\[Z_^]Vz=SXQPUNMq4JONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9wvotsrk1inmlejib(I_dcbaZYX|\[Z<;QVUNMRKoO10FKDhBG@?cC%;@?>7[;:981w543,P0)o-,+$Hi'~%${z!x>|utsxq7utVlkjoh.fkdiha'edc\[!_XW\UySwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9wvon4lTjohmf,Mibg`_^$bDCYX]VzZSXQVOsS5KPIm0/EDhHAF?c=<`#">76;4X8xw/.R21q/.'&J*j(!~D|#"!x>|uzyrwpo5mrk1onmfejib(fHdcb[!Y^]VUy<RWVUNrRQP2HGFjJIBGFE>b%;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwW9OTSLKPImGkK-IBGF?cCBA@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwWV87SLKoO1GLEi,HGF?DCB;_?>=6;:981U/4-Q1*/.'K%*#"!E%${A!xwv<]yxwpo5mrk1Rnmfkjiba'e^$bD`_XW{[Z<RWVUNrLQJINGk.JIHAF?c=<A@?>=6Z43810T43,10/.'&J*j(!~D|#"!x>|uzyrwpo5mrk1onmfejib(fHdcb[!Y^]VUy<RWVUNrRQP2HGFjJIBGFE>b%;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwW9OTSLKPImGkK-IBGF?cCBA@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwWV87SLKoO1GLEi,HGF?DCB;_9876;4X87w/43,Pqp.',%I#('~D|#"!x>|{tyxqpo5mrqpi/gfedcb(fHdcb[!Y^WV[TxXQuONMLKPOHlLEJIBG@d>C<;_?>7<;:3Wxw/.R21q/.'&J*j(!E}${A!x}|u;sr8Yutmrqj0Qglkd*)gfHdc\"C_^WVzZSXQPOs6LKoIHMFEiIH*)?>b%;:^>=}|Y9270/.RQP0).-&J*)"'~D$#z!~}v<zyxqYun43kpoh.lkdcb(`H^]\"`_X]V[TxXWVO7SLQPIm0/EDhBf)(>=<`@"8=6Z:9yx0543,P*p.',%$H('&fe#z@x}v{zsr8Yutmrqj0nmleMib(fHdcb[!Y^]VUy<RWVUNrRQ3IHGLEi,HAF?cC%$@9>7[54927654-Q1q/.-&J*j(!E%|B"yx>|{zyr8vo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bDZ_^]VUyYRWPOsS5KPIm0/EDhBf)(>=<`@"8=6Z:9yx0543,P0)o-,+$H"'~}$#z@x}v{zsr8Yutmrqj0nPfkjc)Jf_%]b[!_XW\UyYRQVONMLp3INGFEiIHG@(>b%;:^>=}|Y9270/.R2+0)('K+*j(!E%|B"yx>v{t:9wvonsl2SRhmlkd*bg`&^Fb[`Y^]VzZSRQVOsSRQ3IHGLEiIHGFED=aA#9>7[;:981w/4-,PON(L,%*#"!E}$#"!x>|{ts98vuWsl2ponmlkdcb(`e^c\"!_^]\[TxRWVUNrRQPON0/EDhBfF?DC<`@?>=6Z:9yx0543,P0)o-,%$H('&}|B"baw|{zsr8Yutmrqj0nmleMib(fHdcb[!Y^]VUy<RWVUNrRQP2HGFjJIBGFE>b%;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwW9OTSLKPImGkK-IBGF?cCBA@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwWV87SLKoO1GLEi,HGF?DCB;_?>=<;4X8765.R21*/.'K%*#"!E%${A!xwv<]yxwpo5mrk1ingfe+cba'_d]baZ~^]VUTSw:PUNMLpJOHlLKDhBAF?cC%;@?>7[5{3276/.R21q/('K+*#G'&}eB"!x}v{zyr8pun4Ukjong-eMiha`&dcbaZY}]Vz=SXQPUNMq4JONMFjDIHGF?>C<`@">76;4X870/.R21*/.'K%*#"!E%edz@a}|{tyxqp6tVUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/.R21*N('&J*)('~D$#"!x>|uzyrwpo5mrk1onmfejib(fHdcb[!Y^]VUy<RWVUNrRQP2HGFj-,HGF?>b%;:^>=}|Y9876/.R,+Op(-&J*#i!&}C#c!~wv<tsr8vuWsl2ponmlkdcb(`_%]\"C_^WVzZSXQPOsSRQP2HGFjJIBGFE>b%;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwW9OTSLKPImGkK-IBGF?cCBA@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwWV87SLKoO1GLEi,HGF?DCB;_9876;4X87w/43,Pqp.',%I#('~D|#"!~}v<;yxZputm3TSohmlkd*Ka`edc\"ZY}@?UZSRvVO7SLQPIm0/EDhBf)(>=<`@"8=6Z:9yx0543,P*p.',%$H(!~%|{A!x}|u;yxZponm3qSongled*bJ`_^$bD`_XW{[Z<RWVUNrRQP2HGFjJCHA@?cC<;:^>=}|Y981U5.-,+0/(L,+*#G'&}eB"!~}_uzs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X87w/43,Pqp.',%I#('~D|#"!~}v<;yxZputm3TSohmlkd*Kgfed]#D`_X|V[ZSXQuONMLKPOHlLEJIBG@d>C<;:9]=6|:3Wxw/.R21q/.'&J*)('~D$#"!x>|uzyrwpo5mrk1onmfejib(fe^c\"Z_X|?UZYRvP8NSLQPOHGFjJCHA@?cC<;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9wvunVl2pinmf,Mibg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9wvon4lTjohmf,Mibg`_^$bD`YXW\UZSwWV87SLKoO1GLEi,HGF?DCB;_?>=6;:981UT4321*N('&J*j('~Dedzy?}_{zyxwpo5mrk1Rnmfkjiba'_^cbaZ~^]VUZSRv9ONMLKJIHl/EDIHA@?cC<;@98\<5:3810T43,10/.'&J*)"!E%|#"!~w=uzyrwpo5mrk1ongf,dcbaf_%]baZ~^]\[ZYXQuONMLKPOHlLEJIBG@d>C<;_?8=6;4X810T43,10/.'&J*j(!EDedzy?}_{zyxwpo5mrk1ongf,dcbaf_%c\[!_X]V[ZYXQuONMLKPOHlLEJIBG@dcb%;:^>=}|Y9270/.R2+0)('KJ$j"!E}eB"!~}|u]s9qYun4lkpi/gfedcb(`_%]\"C_^WVzZSXQPOsSRQP2HGFjJCHA@?cC<;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}|u]s9wvo5VUkpoh.ledchg`_^$bD`YXW\UZSw:PUNMLp3INMFjD,HGF?DCB;_?>=6;4X2765.R2+0)Mnm%$#(!E}eB"!x}v{zyr8vunsl2jonmf,dihg`&Gcb[`_^W{[=<XWPOsr54JONMFKDhBAF?cC%;@?>7[;:981w/4-,P*p.-&J*)"'~D$#"y~}|u;yxZponm3qSihg-,+cha`&dcbaZY}WVUyS;QVUNrqKPONGkK-IBGF?c&BA:?>=<5YX870v.3,P0)('K%*)"'~Dedz@~}v{zyr8vuWsl2ponmlkdcb(`H^]\"Z_XWVzZ<XWPOsSLKPOHGkKJIH*)E>bB;:?>=6Z:98765432+*N.',%I#('~Dedz@a}|{tyxqp6tVUkpoh.ledchg`_^$bD`YXW\UZSw:PUNMLp3INMFjD,HGF?DCB;_9876;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwW9OTSLKPImGkK-IBGF?cCBA@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwWV87SLKoO1GLEi,HGF?DCB;_?>=<;4X8765.R21*/.'K%*#"!E%${A!xwv<]yxwpo5mrk1onmfejib(fHdcb[!Y^]VUy<RWVUNrRQP2HGFjJIBGFE>b%;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwW9OTSLKPImGkK-IBGF?cCBA@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwWV87SLKoO1GLEi,HGF?DCB;_9876;4X87w/43,Pqp.',%I#('~Dedz@~}v<]yxwpo5mrk1ohgf,jibgf_%]b[!_XW\UyYRWVUTMLKoONMLEDhHGFE>=a;@?8\<549870T.-,+*N.nm%$)"Fg%|{z!x>|utsxq7unVrk1ih.fejib(IH^cbaZ~^@VUTSw:PUNMLpoINMFKDhBAF?cC%;@?>7[;:981w/4-,P*p.-&J*)"'~D$#"y~}|u;yxZponm3qSihg-,+cha`&dcbaZY}WVUyS;QVUNrqKPONGkK-IBGF?cC<$:?>7<;4981Uvu-2+Op(-&J*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#c!~wv<zyr8vuWsl2ponmlkdcb(`_%]\[!Y^]\Uy<RWVUNrRQP2HGFjJCHA@?cC<;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9wvon4lTjohmf,Mibg`_^$bD`YXW\UZSwWV87SLKoO1GLEi,HGF?DCB;_?87<;:3Wx05.-,+O/.'K%*#"!Efe#z@x}|uzsr8vuWsl2ponmlkdcb(`e^c\"`_X]V[TxXQPtTS5KPIm0/EDhHAF?c=<A:?>7[549870T43,+O).'&%*)(!E}$#"!x>={tyrqp6tsrqji/gfedcb(`e^c\"`_X]V[TxXW9OTSLKPImGkK-IBGF?c&BA:?>=<5YXWxw/.R21q/.'&J*j(!E}${A@x`|uzyxwp6nmlkjong-kjiKg`_dc\"`_X]V[TxXWVO7SLQPIm0/EDhBf)(>=<`@"8=6Z:9yx0543,P*p.',%$H('&fe#z@x}v{zsr8Yutmrqj0nmleMib(fHdcb[!Y^]VUy<RWVUNrRQ3IHGLEi,HAF?cC%$@9>7[54927654-Q1q/.-&J*j(!E%|B"yx>|u]srq7unmlqj0QPfkjchg`&Gcb[`_^W{[ZYXQ9UNSRKo21GLEi,+GFE>=aA#9>7[5{3276/.R2+*N.',%I#('~D$#z!~}v<zyxqYun4Ukpoh.lkjiha`&dcbaZY}WVUyS;QVUNrLQJINGkK-CHGF?cC%;@?>7[;:981w/4-,PO)o'&%I)i'~%|B"yx>v{t:xqYun4rqpohg-ejihg`&Gcb[`_^W{[=<XWPOsrq4JONMFjDIHGF?>C<`@9>=6Z:98705.RQ1*/.'K%*#"!E}$#"!x>=u;yrwpo5mrk1onmfejib(fe^c\"Z_X|?UZYRvP8TSRQJONMLEiCBA@?cC<;:^>=}|Y9270/.R21*N('&%I)i'~%|B"yx>|u]s9qYun4lkpi/gfedcb(`H^]\"Z_XWVzZ<XWPOsSLKPOHGkKJIH*)E>bB;:?>=6Z:98765432+*N.',%I#('~D|#"!~}v<tsr8vuWsl2ponmlkdcb(`e^c\"ZY}@?UZSRvVO7SLQPIm0/EDhH*)?>b<;:?8\6;492V05.3,10/('K+$)"Fg%${z@a}|uzs9wvuWsl2ponmlkdcb(`_%]\"C_^WVzZSXQPOsSRQP2HGFjJIBGFE>b%;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwW9OTSLKPImGkK-IBGF?cCBA@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwWV87SLKoO1GLEi,HGF?DCB;_?>=6;:981U5.-Q1*/.'K%*#"!E%|#"y?}vu;yxZputm3TSohmlkd*Ka`edc\"ZY}@?UZSRvVO7SLQPIm0/EDhH*)?>b<;:?8\6;492V05.3,10/('K+$)"Fg%${z@a}|uzs9wvuWsl2ponmlkdcb(`H^]\"Z_XWVzZ<XWPOsSLKPOHGkKJIH*)E>bB;:?>=6Z:98765432+*N.',%I#('~D|#"!~}v<tsr8vuWsl2ponmlkdcb(`e^c\"ZY}@?UZSRvVO7SLQPIm0/EDhBf)(>=<`@"8=6Z:9yx0543,P*p.',%$H(!~%|{A!x}|u;yxZponm3qSongled*bJ`_^$bD`_XW{[Z<RWVUNrRQP2HGFjJCHA@?cC<;:^>=}|Y981U5.-,+0/(L,+*#G'&}eB"!~}_uzs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X87w/43,Pqp.',%I#('~D|#"!~}v<zyr8vuWsl2ponmlkdcb(`_%cb[Z~XW\UTx;QVONMqQ3IHGLEihBG@?cC%;@?>7[54381U54t2+*N.',%I#('~D|#"!~}v<t:xZputm3TSohmlkd*hgIe^]#[Z~XW\UTx;QVONMq4JINGLKDhHG)(D=a;@9]=}|Y9876/S321q)M-,%$#G'&}eB"!x}v{zyr8vunsl2ponmleMib(IH^cbaZ~^@VUTSw:PUNMLp3INGFEi,HAF?cC%$@9>7[54927654-Q1qp.-&JI#"!~}Cd"!x}|{t:xZponm3qSihg-kdchgf_%]\aZ_^]VzZSXWVOsSRQPON0/EDhHAF?cba;:?8=6Z:9yx0543,Pqp.-&J*j('&}CB"baw|{zsr8Yutmrqj0Qmf,diha'_d]\[!_XW\UySwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bDCYX]VzTYXWVOsS5KPIm0/EDhBfF?DC<`@?>=6Z:9yx0543,P*p.',%$H('&fe#z@x}v{zsr8Yutmrqj0nmleMib(fHdcb[!Y^]VUy<RWVUNrRQP2HGFjJCHA@?cC<;:^>=}|Y981U5.-210/(L,+*#G'&}eB"y~w=^zyrwp6tVUkpoh.ledchg`_^$baZ_XW\[ZSwQ9UNSRKoO1GLEi,HGF?DCB;_?>=6;:981U54321q)M-,%$#G'&}eBz!x}vu;yxwpon4lkpi/gfedcb(fHdcb[!Y^WV[TxXQuONMLKPOHlLEJIBG@d>C<;_?>7<;:3Wxw/.R21q/.'&J*j(!E}${A!x}|u;sr8Yutmrqj0Qglkd*)gfHdc\"C_^WVzZSXQPOs6LKoIHMFEiIH*)?>b%;:^>=}|Y9270/.RQP0).-&J*)"'~D$#z!~}v<zyxqYun43kpoh.lkdcb(`e^c\"!_^]\[TxRWVUNrRQPON0/EDhBfF?DC<`@?>=6Z:9yx0543,P0)o-,%$H('&fe#z@x}v{zsr8Yutmrqj0Qglkd*b(fHdc\"C_^WVzZSXQPOsSRQ3IHGLEiCBA@?cC<;:^>=}|Y9270/.R21*N('&%I)i'~%|B"yx>|u]s9wvonsrk1i/mlkdcb(`e^c\"ZY}@?UZSRvVO7SLQPIm0/EDhH*)?>b%$:?>7[;:32V0v43210/.'&J*j(!~D|#"!x>|uzyrwpo5mrk1ongf,diba'eGcba`_X|V[ZSXQuONMLKPOHlLEJCBf)(>=<`@"8=6Z:9yx0543,Pqp.-&J*#(!~Dedzy?}_{zyxwpo5mrk1onmfejib(fHdcb[!Y^]VUy<RWVUNrRQP2HGFjJIBGFE>b%;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwW9OTSLKPImGkK-IBGF?cCBA@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwWV87SLKoO1GLEi,HGF?DCB;_?>=<;4X8765.R21*/.'K%*#"!E%${A!xwv<]yxwpo5mrk1ingfe+cba'_d]baZ~^]VUTSw:PUNMLpJOHlLKDhBAF?cC%;@?>7[;:981w543,P0)o-,+$Hi'~%${z!x>|utsxq7utVlkjoh.fejiha'_d]#D`_X]VzZYRQu8NMq4JONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9wvunVl2pinmf,Mibg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9wvon4lTjohmf,Mibg`_^$bDCYX]VzTYXWVOsS5KPIm0/EDhBf)EDC<;_98765Y9yx0543,P0)o-,%$HG'~%|B"yx>|u]srq7onslkjongf,jiha`&dcbaZY}WVUyxXQPUTSLKPImGkK-IBGF?cC<$:?>7<;4981UT4321*N('&J*)('~D|#z!x>v{tyxwpo5mrk1ingfe+*b(I_dcbaZYX|\[Z<;QVUNMRKo21GLEi,+GFE>=aA#9>7[;:981w/4-,P*p.-&JI#G'&}eB"!~}|u]s9qvon4lTjohmf,Mibg`_^$baZ_XW\[ZSwQ9UNSRKoO1GLEi,HGF?DCB;_?>=6;:981UT4321*N('&J*)('~D$#"!~}v<]yxwpo5mrk1ongf,diba'_^]b[Z~XW\UTx;QVONMq4JImMLEDhHA@E>=a;@?8\}54381U54321q)M-,%$#G'&}eBz!x}vu;yxwpon4lkpi/gfedcb(fHdcb[!Y^WV[TxXQuONMLKPOHlLEJIBG@d>C<;_?>7<;:3Wxw/.R21q/.'&J*j(!E}${A!x}|u;sr8Yutmrqj0Qglkd*)gfHdc\"C_^WVzZSXQPOs6LKoIHMFEiIH*)?>b%;:^>=}|Y9270/.RQP0).-&J*)"'~D$#z!~}v<zyxqYun43kpoh.lkdcb(`H^]\"`_X]V[TxXWVO7SLQPIm0/EDhBf)(>=<`@"8=6Z:9yx0543,P*p.',%$H('&fe#z@x}v{zsr8Yutmrqj0nmleMib(fHdcb[!Y^]VUy<RWVUNrRQ3IHGLEi,HAF?cC%$@9>7[54927654-Q1q/.-&J*j(!E%|B"yx>|{zyr8vo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@9]7<543870T4321*/.'K%*#"!Efe#z@x}|uzsr8vuWsl2ponmlkdcb(`e^c\"`_X]V[TxXQPtTS5KPIm0/EDhHAF?c=<A:?>7[549870T43,+O).'&%*)(!E}$#"!x>={tyrqp6tsrqji/gfedcb(`e^c\"`_X]V[TxXW9OTSLKPImGkK-IBGF?c&BA:?>=<5YXWxw/.R21q/.'&J*j(!E}${A@x`|uzyxwp6nmlkjong-eMibgfe^c\"!_^]\[TxRWVUNrRQPON0/EDhBfF?DC<`@?>=6Z:9yx0543,Pqp.-&J*#(!~Dedzy?}_{zyxwpo5mrk1ingfe+cba'_d]baZ~^]VUTSwWPUTSLp3INGFEiIHAF?cC%;@?>7[;:981w543,P0)o-,+$Hi'~%${z!x>|utsxq7utVlkjoh.fejiha'_d]#D`_X]VzZYRQu8NMq4JONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9wvunVl2pinmf,Mibg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9wvon4lTjohmf,Mibg`_^$bDZ_^]VUyYXWPtTS5KPIm0/EDhHG@d>C<;_98765Y9yx0543,P*p.',%$H('&fe#z@x}v{zsr8Yutmrqj0nmleMib(fe^c\"Z_X|?UZYRvP8NSLQPOHGFjJCHA@?cC<;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9wvunVl2pinmf,Mibg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9wvon4lTjohmf,Mibg`_^$bDCYX]VzTYXWVOsS5KPIm0/EDhBf)EDC<;_98765Y9yx0543,P*p.',%$H('gf|B"baw|{zsr8Yutmrqj0Qglkd*b(fHdcb[!Y^]VUy<RWVUNr54JINGLKDhHG)(D=a;@9]=}|Y9876/S321q)M-,%$#G'&}eB"!x}v{zyr8vunsl2ponmleMib(IH^cbaZ~^@VUTSw:PUNMLp3INGFEi,HAF?cC%$@9>7[54927654-Q1qp.-&JI#"!~}Cd"!x}|{t:xZponm3qSihg-kdchgf_%]\aZ_^]VzZSXWVOsSRQPON0/EDhHAF?cba;:?8=6Z:9yx0543,Pqp.-&J*j('&}CB"baw|{zsr8Yutmrqj0Qmf,diha'_d]\[!_XW\UySwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bDCYX]VzTYXWVOsS5KPIm0/EDhBfF?DC<`@?>=6Z:9yx0543,P*p.',%$H('&fe#z@x}v{zsr8Yutmrqj0nmleMib(fHdcb[!Y^]VUy<RWVUNrRQP2HGFjJCHA@?cC<;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}|u]s98vuWsl2ponmlkdcb(`_dcb[Z~^]V[ZYRvPUTSRKoON0/EDhHAF?cb<;_?8=65Y9yx0543,P0p.'&%$H('&%|{"y?wv{zsr8Yutmrqj0Qmf,jiba`e^$bD`_XW{[Z<RWVUNr54JIm0/EDCHAe?DC<;:^>=}|Y9270/.R2+0)('K+*)i!&}${Abaw|{zsr8Yutmrqj0nmleMib(`edcb[Z~XW\UTx;QVONMq4JONGFjJIBA@E>bB;:?>=<5Y3810T43,10/.'&J*j('~Dedz@x`|uzyxwp6nmlkjong-kjihgIed]#D`_X|V[ZSXQuONMLKPOHlFEDCBf@(>b%;:^>=}|Y9876/.R2+0)('K+$j"!E}eB"!~wv<tsr8vuWsl2ponmlkdcb(`_dcb[Z~^@?UZYRvPUNMLpPON0/EDhHA@?cC<;@98\<5:3810T43,10/.'&J*)"!E%|#"!~w=uzyrwpo5mrk1ongf,dcbaf_%]baZ~^]\[ZYXQuONMLKPOHlLEJIBG@d>C<;_?8=6;4X810T43,10/.'&J*j(!EDedzy?}_{zyxwpo5mrk1ongf,dcbaf_%c\[!_X]V[ZYXQuONMLKPOHlLEJIBG@dcb%;:^>=}|Y9270/.R2+0)('KJ$j"!E}eB"!~}|u]s9qYun4lkpi/gfedcb(`_%]\"C_^WVzZSXQPOsSRQP2HGFjJCHA@?cC<;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}|u]s9wvo5VUkpoh.ledchg`_^$bD`YXW\UZSw:PUNMLp3INMFjD,HGF?DCB;_9876;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bDCYX]Vz=SXWPONMq4JONMFjDIHGF?>C<`@9>=6Z:98705.R2+0)Mnm%$#(!E}eB"!x}v{zyr8vunsl2jonmf,dihg`&Gcb[`_^W{[=<XWPOsr54JONMFKDhBAF?cC%;@?>7[;:981w/4-,P*p.-&J*)"'~D$#"y~}|u;yxZponm3qSihg-,+cha`&dcbaZY}WVUyS;QVUNrqKPONGkK-IBGF?c&BA:?>=<5YX870v.3,P0)('K%*)"'~Dedz@~}v{zyr8vuWsl2ponmlkdcb(`e^c\"ZY}@?UZSRvVO7SLQPIm0/EDhH*)?>b<;:?8\6;492V05.3,10/('K+*)('~D$#"!x>|uzyrwpo5mrk1onmfejib(fe^c\"Z_X|?UZYRvP8NSLQPOHGFjJCHA@?cC<;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9wvunVl2pinmf,Mibg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9wvon4lTjohmf,Mibg`_^$bDZ_^]VUyYXWPtTS5KPIm0/EDhHG@d>C<;_98765Y9yx0543,P*p.',%$H('&fe#z@x}v{zsr8Yutmrqj0nmleMib(fe^c\"Z_X|?UZYRvP8NSLQPOHGFjJCHA@?cC<;:^>=}|Y981U5.-210/(L,+*#G'&}eB"!~}_uzs9wvunVl2pinmf,Mibg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9wvon4lTjohmf,Mibg`_^$bD`YXW\UZSwWV87SLKoO1GLEi,HGF?DCB;_9876;4X87w/43,Pqp.',%I#('~D|#"!x>|{tyxqpo5mrqpi/gfedcb(fHdcb[!Y^WV[TxXQuONMLKPOHlLEJIBG@d>C<;_?>7<;:3Wxw/.R21q/.'&J*j(!E}${A!x}|u;sr8Yutmrqj0Qglkd*)gfHdc\"C_^WVzZSXQPOs6LKoIHMFEiIH*)?>b%;:^>=}|Y9270/.RQP0).-&J*)"'~D$#z!~}v<zyxqYun43kpoh.lkdcb(`H^]\"`_X]V[TxXWVO7SLQPIm0/EDhBf)(>=<`@"8=6Z:9yx0543,P*p.',%$H('&fe#z@x}v{zsr8Yutmrqj0nmleMib(fHdcb[!Y^]VUy<RWVUNrRQ3IHGLEi,HAF?cC%$@9>7[54927654-Q1q/.-&J*j(!E%|B"yx>|{zyr8vo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X816/St,10/(L,+*#i!&}C#cy~}|{zs9qvo5VUkpoh.ledchg`_^$bD`YXW\UZSwQVOTSLpJONMFjDIHGF?>C<`@">76;4X87w/43,Pqp.',%I#('~D|#"!~}v<zyxZpo5VUkpoh.ledchg`_^$baZ_XW\[ZSw:VOTMq4JONMFjDIHGF?>C<`@9>=<5Y38765.-Q1q).'K%*#"!E}|{A!~}_uzs9wvuWsl2ponmlkdcb(`e^c\"ZY}@VzZ<XWPOsSLKPOHGk.JCHGF?>b<A:98\<;492VC ``` Final output: `Game Over!` That escalated quickly. --- **Solution** > > Safe despite some valiant efforts (particular credit to @Sisyphus and @DomHastings). It's now clear I could have got away with using only two languages instead of four! > > > > > You probably don't have time to run every layer so here are the [first seven](https://tio.run/##7V1nVyJNE/3@/goEUZBgQAWMGBEDiIqIiSTJRJAo6F/ft6p6BmaGHkBBfXadL3t23XOKsrrq1q3QTSL@kv3zJ5XM5nX6w3gjVdLN6kzHe8dmXb5SLlTKS/r/FbIFnT33DP@wl3N53ZoumS9Ey9l42f6UWNYl42XpD/6Hojp/iELndKaj@GMi/5hJSSRP5wvl6Sfh5@2/SMVJPy2RKyezig@kn6l8pkNnov@WfOB9vBrX2ZIFHX0y/a@O/WlLKoRKP7mk/D1Lar/nvM50Ukk0JB9Zgn/qbKVCKfeUkgoY5jdb@IHfbPFbfjPnUL/Znz/bk7GNovv6@Wq5tdvYDlXny0lL4OjwYH9/79I7/55On3lOgmvVpvmwflnIPz85iqf558xj6m4qsR@L3o4ntmPRi3Dz6nLlJHwe8pcW5vcD/qPdg@3s3pR5Zy1hXF66XVt9a0XcrtnQgt02NzszbTq0WqYM3smJt9Smfuz9LVp5fXEXq/mF89BDIZ@1g/RkNsOkX0Zvb85DjchJ@DjwcrpwcOx7mpneIenrIH3D475ZXVyed8@dLy7MO0j65IFl3KzfzRjHm6@eeq3aLC@B7pXyk@PsNJ99enxo6x6/fL8IX4fO6svBc9C6GHT49ryHO7nsptezntwyLnvW15xXy0tul3OmandYj6cKdtvE/vi9fmwHdH8dq79VK8uNeq1QeZ4vFe9z05k06J4wxfZub671Y9GLm/Ory8hFsALSDw@OA3uPhzv7W5tpj0lmGefi9OmJdXZq2j55YJwygPR0yvDqeX@rNl8bJVe1En55nEPrg@49pZPdN3ZR93GPG3RfAMs4wTK24GyRWcbgzb6jZcbqa61K@aVedFbCT6WH2RmQnrrLgd0nvMnEFdgHTzVyEXYHzk4P0e4ofSvj3d1ZW91cjq6vgd2X6FTR7kXzkc1qHG@fal3QHS0TerifyTLd45N7dx3pK8vB4xDqnp@bRbtbLSQ9vmFwK@xuNvHsDh7J85mtCFjmtXG6TD5DlvE@2Pe39ry7fXxm4q3V3EjEa63m60vJFQGfgVMlyxzlEqY06T4WIY8U/P0keDwHcu9B@gb6zIrsVO1wqiTd2Pb3xntt9RYsUysslrt1j2@BZc5fLyMK6b7N9O769pZo9/kLPFX7Cdhd5pEduzsroDXoHjxOP9wn5ae6unLBogliFX0GpG94ZLE655wB3YPHM2aUPmXWT75vjxteIVarK6@NejECp@pguks8MkYeeVa/CJ8HnKeHQTFWN9Nm09rqSsyjd60uXi65G/UZsDtF0yT4zJ5pcoL8nXQf0O6jxplYBOweapxekEcWmfT7bR/5zBbo7r5xroDW4JFn6DOSWH0bhz8hmpplkA5ROv94dg84k7aC7txTPQzu@/zehwMbeaQMZ2Zr0/M263HAnJ@cMPrMucl3Ywt8pr5GKEZ2L8FnZDO21H2Oe6olnu5rZHfQHXwmyNF9FaIJPDK/gEgAOJMG6WD31G3yWn8ZvWith0D3KvrMCXjL3uM0IAHgzA5JV5zqjDlv63WqwQwhMJ3qtV6wDNodpYsIvLXJjSawu8Lf@50q4vvlaQ3wHVCswLPMygJJB5@RWcbYMugb6yLOyLLHQTyWQt0vI28esMzpSVXu7yw3ge7rrmuGM2B3h7UrN8XfWqh7rQvfo8abbsuo4wx4pA090nQ4gdKZZRBnKmj3YaUTilkCBUTgKUNubOJty5BsvL8hRoLuPH8XEPgsgkggzdoMxcDu62syn2EoNnUPPiOXrtSdPFLEmRPK2ocFh49O1YqnKsXIsJPw3TLlR5zxGUwcFPvBaHKdgd1ROs/fGQLDqfpNCiRoVW7A31H3x4dCh3F85lSVuUmZtYHp2QCBs/HYBOZu9HcR37nRpF9zot1ds8BnytY2Ait8RiVWmc@g7nKfIT4D2cMgSq/XyDJFsDv5zNj7doshcOWVZ/fPZG2Fv6tHE0MxYqmczPfNus@Gpik3@eU8sk44w9edpIdJdzlL9QEHvoNTxWhywmc4wl26g783N8ZQ@nIXvpszHHxfBKbn2zva3cn5BP7@FzGOdm6yqjNsAcUwe7BYZfz9c7lpqGhSq5vULENZ2zK@B3YHFONYhnikeT8NOAOWiaLuIL2DwF46Va@8shFQzDJjxswntQzyGcoe4JGnJ0JVBgh8uwsIjHYHnzkhJGjbHS2zsy2tDkS25AfLdHMxFz97jIFlrjF7iNEU8PfMTRI@8wa6j6w6@GDWJn@H7IHRJPB3obJBRkYceBMYh5ibujMf4gxGU5knneUmFT7z2WgKAie4S5pZhoJaGy1zdloLH4eYv@/JK0rU@tP@3o6m8LkLdD/IB1hFKecEVK8y/o55lcVqOtVEphcdGVsKSqSr4HsGLJODajgFjCMOKNaCSv5UjsCIBJ471F2oPRQ8Empiwkj17IEsNXE1cI9jtiZDAmQcnD7BCfq7JSnjBEKsQlWmzNobSyh9YclBPQ7lqTbbsQpM7/lc1N2SBIYtqZsakYugO@SH2oN/qmI1jB0UtDunGl4svzyC7shSiemlbsev42LWrgXRI6GyefZLe0vjS8wyDrB7lfUJKPP1tfsoGIeUYUPEPszm0O4o3Rdldr9oXVMHBaQfkWVmsBr@@KmWzx@B6WXtaT/Eapz5jIDvn8xNfXocQ2a@18Q7IDBUwzWqtSUc@K/mM8Pmps/X2j4L8RmoQLh8hnJTujWoz8DZCvjue/Iejgzf/8vVwWDVsLIfKXRQVPsEI8cZbl9M0sP@l6JJqw4GiKYv8MiuHocf7R74iEe2e3oq0dSX6Yk444TqgPWW2hw4dUdTlZUb8ncJF4OMSpVNXD7NEjq194xhQ@2BXEzqkWJl09VBAT4DPBJ1x1nZAbe3xPrvGE2D94FVuj8/4O8fw5nPzvk@rTu/XgXdz3DeRF03yB5s3gR2d10jw8aqzA48Ceqm5ycj69TKMx@x1BxkPsbF9m5ZZeOhymaJplmFvI9NJjY3@KfKetgiiukxVoVpFs1XgZ@CClKGTZMJYnqlIsQqzQ4AgVH6CrHUFYhVsHu1YptTy03FL8GZsfcaIrBK3UQ@c/1lPjOc7hpL/S6WqsWqFqsDTuIuQO7ZPDEO@9AdFNy0oBkl4wQLkdFmvq6p@ecsoz4rA8bRU/dMulc/ktv9mUc@c4hTc6/ZJOUz1J/pscfB@Az5DEnnR5PQB1bnwBRNPupEbt2h9BbbzulE0wNaBpFA6M8gioVZH1jEGZKeiCNLVZ8icixD/chcNj4ZvUN/H6rHMRjDHnwC@t1cjHikape5d25aAp9ZYdXBNE7Nhbm2qkey3HRA@Y/1sKlPoNxbUjBsceKv9EghmlR0j0WlOIN9Mf@A@2K0@zMWr7U4@2Kk@40hLvTf@290kd2tloBio2u9xs182EG5Uc3a/SpKQ46m5nrGCRrcaEpeC/137O67SXfZHkdic8Ogx7y65HBxEBjrpnoMERj4zCJanGbDD5BXaZMOLLPJ65DnJHtLLsZnhE2LolmbUf72LsTA0ger5HPACVIWAd8N22R3mkwcl89w1431I7NdfYKv1f1rpKtvo/WMJvn@zAWzjMrMhjFssLslALE6YZwymzobLs1yo1SEuulFtvUql97ZHO1w4IlNlE5MTyVWVXDmACxzl9Si6as8UqtXv3qDsc9GF@1CIIpNDzST7zOjHLpu4keTwLANAifAqXnzVdpLHWQygUgwko1dsQ/MwRm0/miiqcc@wQrlJraHLd0cJX@vcXIT7r9DbpLsQgh1E/WB@V2IQae3uMEoz3yRk2DFxd1lHswyNJOH7JF75vffh0OxD2@O8qthMVa9smgqFZ24WUTZgyb@8v4MZr4Qx2eY3ReajjmsPeQsVdgHjnI3dhkSxAScYfuRnNoDOPDi5bwaw@6OpuNH5DPgOd4bBcNGjHzuM/HHzSLjOGVt5W5nCW/xPLG5h@xGhvS@hxdvBrAdFGlFyTa6ZDu1Tb2IwB/IHrucLoRiX8yMPjPOuZHRVVG2oLKJ8HIT8hmPW83uLDcJ1TDwmfCLsA/8gBgZA/Mp7ze1d/et5DOKWzxfsKH@gz29f3Q2/AOcoIfdqxUH@vsR9rANprbPfAEnGG6f4G/sdg7A30WcUW64qOy6Sbr72t0srW7S6qZP@cxot0R@jKV@8zbab6ybhqxXf49HDrMVJSJBGewOp/rkOCvkpTcyrq8w8zWv@Axb678Pl/k6N3uFaHroqlcFxvHX3hv@vpuO/wxGim8rKG4li/ebIJowVp95sUpT81X1m@wD48w33Tt4oJk8VvKjmslrWfvrPHJ6XnFPnpO1oW5K42wYTvVWrYNi3/eJ8ybGI/l9sV9u9x5ZuyXedITMR5Yparv72s1e7WbvN9/s1aZZg02zxKkK4Qz/zoTqqxOD8RmRR0p0xy2R@JuAkUNvebdZ6pC9VJtVeImq370y6u6XP3or@VdkPsweH3@Zp2/2GIPaQ8x8jcFevOs3VbFavuhWw8cswzYYt1U6KLLdzsVWFyf47ptf/8UOitoLApPc6W2HA0dv268fKLYv8Y6/YBmPm7t9aRYmz2P0LoRyj6N9aw2lX/fsz7hWmWW6JqD8yXNHOqvKeO8YsvmqGieQTUBH8mZR713mWp9o6myoc9@KEmY2XZM45X2@Z7ZDrnqf79tuk0g26cRXEsnuRiZd2I/s8X7kMG@JfCCvqtl9RK99/BU9bK1eVbl7m6XtnERGu/ml3dL8qqwt3DsApse7kaFtSv9YB4Xt6fXYhbjsvPvDex@4U1H2fOFRm6oM/oLAz7wv9qXvpf7rE6GffKf2v/wm3T9Syatk7UHfdcM7QvhCe1nF7l03HbMZX@r2xqDdG9buDXdjZJ@36@lm7xX6e6/X@tS@M0DbNtZuIGk3kLQbSL/5BpKsTyDtMptZ1ka7V7HrJj/VKdXtHLXvVZH1OHzKXmqRa5mP4HuX7uMC4@DudgI68l4qeWLdH9x/F7o/byKf@S3Z49/fhfhdN9nR7pn0pzhBn8ynhu/Ca6ztPY5fj@/i/gzUq3KfEZHgs29F/SO3GkZ3N0vKUjnf36RVlFpFqf4SVZTd57ulyTNEU0h2o5rsLsy1pVysgPhOuhtb@Kp/rfsbCXAmH0txv7mQWQZ0T61vd9dNfW8l93l5LeCX3KNkfTHIHt1br5O93lvC/ozaHscu6M77bsGO7pKZvOpmkWB3j4BiFE0df9e2FX50W2EEb6ivnmKnlv8dd9LJxC/ZhRhiMvEbtqI0tvQVN@603X3trvnnJ0Iq33vb6c8sgXQVfCfG0f0GI719@a7yuk0HI7vmfO1v1YVaGzkBYeTW/wE "Bash – Try It Online") and [last seven](https://tio.run/##zVNdb5swFH3Pr7BSsuDGOOYjkGZJ@gf2tFfqWUCJYFMKImRrFZW/ntowwmfSVJq0Egnb93LOuedex3V2wfHoe0EEhioCGgK7X2EMHLDx/wCM8XAgcoPig2/Oi5@AuUHQTLOQrqlI0wjS5wTI3/fuCwTRPo336WI4SPgRKEmchFsf4PCJR3EaRmANvChmaeCk2A1TL/gKPCdtxSrFd2RVIOeAmu5P57cDFC8G0yhOp3kWFG/Fa8nUa0ncViGJe3UV2mXzNcp/617/FO6N/@R@9incm1e7Px7ZirEVedaRdodUS0e6YSHybBgzZGhEM3XTJKZK1Pl8wNjtauunQfQoMyZgi0Vx3NmZkik8eMuXjLHlkjFIoV1mlUzkMuXvCy6XYqElXLBBm@WcFaUseAo@KL5GfIPEiSLWRTbLKQRLOQ4QTxfE43yl/BnwxjylsszaXOcU@thy1R9CkPZ4402dbQziqWRDVNcyfGfjqJZ316NEKbxnZ2pu2hQ/OW@SnUtT0bJyz42PkpF6j/FoRw@y9KXNVmdidr18eFm4VBD9PQlXe0pfG/D6WLrI2hY2WN67HzXLNdMVHp2CqMpTJK0XZ6qrGCsnveNpBqU1rjkshnIyVxwbQ5FInzWJfGyw6AE9PE4kRA@XBiv@lh1XUAyoe0H5ZcGjLT2Mb8aTLieuKK/t02Q8Hb/CNw "Bash – Try It Online"). Note that version-dependent Ruby code is used so both links will likely break if/when TIO's Ruby is updated. > > > > > **Layer 1: PHP** > > > > > Just a (cheating) quine. The purpose of this 'invisible' layer is to mask the simple alternating pattern of Layers 3–840,527,321,220,386 by giving the false impression that after Layer 2, an *odd* number of layers remain. > > > > > **Layer 2: Malbolge** > > > > > This layer, created using [this generator](http://zb3.me/malbolge-tools/#generator), was a last-minute addition. It serves two purposes: > > > 1. *Obfuscation.* Layer 3 is easy to crack even without knowing the language (as noted in @Dion's comment). I wanted some protection against this first-glance weakness. > > > 2. *Red herring.* A cracker stuck at Layer 4 (missing the `-rprime` flag) might wrongly guess that there is code in another language hidden in Layer 2. > > > > > **Layers 3, 5, 7, ..., 840,527,321,220,385: bitch `-c`** > > > > > The bitch layers don't do any real work; they simply spit out the next Ruby layer. The (implementation-specific) `-c` flag activates character I/O. I chose bitch for its simple ASCII-code-based character I/O and because it is relatively unknown/unpopular on CGCC (only used in four previous answers). > > > > > **Layers 4, 6, 8, ..., 840,527,321,220,386: Ruby 2.5.5 `-rprime`** > > > > > The Ruby layers rely on obfuscation, the nasty version-dependent practice of calling methods *by index*, and the even nastier 'feature' that the default method indexing is disrupted by loading certain libraries via the `-r` flag. Specifically, the `-rprime` flag (which loads the `Prime` library) alters the `methods` array for objects of `Integer` type, inserting `:prime_division` and `:prime?` at indices 20 and 21, respectively. Thus, by including calls by index to `Integer` methods with index greater than 19, the code is made to break if executed without `-rprime`. > > > > > The code works as follows. The hex integer `0x5f40c10f01b74eafa17c9` is \$7197109101327911810111433\$ in decimal, which is the ASCII codes of `Game Over!` concatenated. The prime factorisation of this integer is \$3^2\times29\times173\times347\times1093\times420263660610191\$. Each of these prime factors, except the last, appears in the first line of Layer 4 (\$3\$ and \$1093\$ are expressed in hex; this is a red herring). Call the last integer in the first line \$n\$, so \$n=0\$ in Layer 4. The code tests whether \$3^2\times29\times173\times347\times1093\times{}n=7197109101327911810111433\$. If so (as occurs only when \$n=420263660610191\$), the integer is broken into an array of ASCII codes (basically via `7197109101327911810111433.to_s.scan(/1?../)` in de-obfuscated form), converted to characters, and printed. If not (as occurs for all \$n<420263660610191\$), the code prints itself, with \$n\$ incremented by 1, as a bitch program. This program is simply a string of ASCII codes sandwiched between `#` and `/` characters. > > > > > *Why `-rprime`?* > > > > > No methods provided by the `Prime` library are actually used (the prime factorisation was done separately), so why `-rprime`? The original plan was not to increment \$n\$ by 1 at each iteration, but rather to replace it by the next higher prime. This would have added another level of frustration to any cracker who stumbled on the `-rprime` flag because the required execution time would have gone through the roof. I gave up on this approach because I was unable to calculate the required number of iterations (i.e. the number of primes \$\le420263660610191\$) in reasonable time! > > > [Answer] # 33 layers, cracked by [HyperNeutrino](https://codegolf.stackexchange.com/a/212088/68942) ``` i=496;a= 0 print('gREETINGS!'.swapcase()if a==447775else'i=%3s;a=%6s%s'%(i-16,a+(int(1/2*2)*int('syd0s6ncczl7ka1ioletm9t1atoqjq2awpshwfxcorai94tcmzim91j2zzq2c08wxjmfmzr0x9euhjojhltjpay0g8t1o78y83a',36)>>i&0xFFFF),open(__file__).read().strip()[14:])) ``` Final output: `Greetings!` Hint: Python. --- Solution: > > This uses Python 2 and Python 3 to encode a [Subset Sum](https://en.wikipedia.org/wiki/Subset_sum_problem) problem. `int(1/2*2)` is `1` in Python 3 and `0` in Python 2, which allows you to pick whether you want to include or exclude a number per layer from a packed list. With strong parameters, subset sum is NP-complete. However, the subset sum has weak parameters (~16 bits per number for 32 numbers) so it can be solved by many methods. > > > [Answer] # 2 layers, safe! ``` "D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3SUUnUUUwCiudIbEAt33wwWt0GD3wwpDDGDDDGpDDwGGtpDt33333sw03333sDDfBDKgGQskWwQ" "1 gfnY ruG" '" +\ ``` Output: `The Last 1` This one will hopefully stand for a bit longer. Hint: Both languages are available on TIO. That's only \$681^2\$ possibilities to try! --- Solution: > > [Foo](https://tio.run/##S8vP//9fycUgtMDAMyo0DxOEhppCGMbBoaFAXmi5c2ZpimeSq2OJsXF5eXiJgbsLkC5wcXF3AWIgXe7uXlLgApQFguJyAzDl4pLm5OKd7h5YnB1eHqikoGSokJ6WF6lQVOqupKCupKAd8/8/AA) followed by [Bubblegum](https://tio.run/##bZBRSwMxDMff/RR5FyTXJA3zTa0cw6chZSi@rPM2RB3D3dGPf6a3uqEYaJq2//yaJA0pfXTb4XMcsdo1MBOCiCIQ8gxkJQK@891fBwHjHufPcVft4khojPGfvjqjiVBFwu5sMcqJ4X4xiIQsaapjSjenygR@pnJk0GOMRoj57m2oDCoMtg68YwFulA1EZJmqIFqOyFraJYDXebq/6YlyXvbYBqoMNsakV2Q26aT/ieqdvbLaEXLeh9AGW7bntq0MKQy2cZq0llCdlmJs2Oc76PehLxEdMpatMnxh0PSd98CuRMmXj6WxB59KQ9ZVQw3AIYTNbXjYtovD@zIvmspQYzi0JO9tpjJzCOpsfqwWuSRrwBWcbLvZPcHX0MLly9U4fgM). > > > > The idea here is that the Bubblegum string is printable ASCII but also a valid DEFLATE stream. The solution was zipped with [ascii-zip](https://github.com/molnarg/ascii-zip), which was originally designed to exploit the [Rosetta Flash](https://molnarg.github.io/ascii-flash/#/) vulnerability but has also found esoteric use in CTFs, such as [PlaidCTF 2019 Potent Quotables](https://blog.pspaul.de/posts/plaidctf-2019-potent-quotables/). The first layer is also valid CJam, but this is a red herring. The `1 gfnY ruG` is also designed to mislead; in fact everything after the last `1` can be discarded. > > > > Note that Bubblegum meets Code Golf's definition of 'programming language', but only on a [technicality](https://esolangs.org/wiki/Bubblegum#Examples). > > > [Answer] # 3 layers, [Cracked](https://codegolf.stackexchange.com/a/213940/95792) by [Aiden4](https://codegolf.stackexchange.com/users/97691/aiden4) ``` class Main: print( """class Main {public static void main(String[] args) {String a="ɗefine";char c=10;String z="pɼint";char d=23;String y="⁸fẇ×ịṛs⁷";String e="";char x=90;String b="⁺°`¬²ịĿ°£Oḋ®ẋṄ¢¦";String w="⁸Ḷ⁸Ŀ~ʋ^ḋ*Ẓ>{S";String i="return";String n=" ";String f="Game";String s="main";String t="def";String k="#";String u="ƈlass";String m="Іt'ѕ Dоnе.";String o="¨";String g="ƊƝƤƬƲȤɓ"; if (""") print(((1 ^ (29 * -54) + 23 & 103) / 3)) print(">") print(302 - 67 + (2 % 590) | 930 - 123 * (-169)) print(""") { System.out.printf("73----T---|---111-T T46%c | / | 1%c 39- 1 %c | 0%c/ %c 1 | 1 1%c| -6 / 1 |%cL115---- | 0 /%c %c 8 L76%c 3 6%c 2-J",10,10,92,10,92,10,10,10,92,10,10,10); } else if (""") print((65 % (59 - 20 * 24)) / -193 * 134) print(">") print((624 & 13 + 3012) / 23 * 9) print(""") { System.out.printf("%cm=%cIt's Done%c;print %c$m%c;", 36, 34, 34, 34, 34); } else if (""") print(12345 * 4 / 910 - 2 * 401) print(">") print((1 + 3 / 3) % (24 - 36 * 90)) print(""") { System.out.printf("Flexibility speaks for yard%cairport announces all lies%cring a ring a rosie%ccaesars sat bad%csay %cIt's Done.%c%cAmerica is great",10,10,10,10,34,34,10,10); } else if (""") print((393 / 91 * 56) - 12 * 78 + 192) print(">") print(67 | -123 + 21 * 34 - 193) print(""") { System.out.printf("You are done%cSay %cIt's Done.%c(It really is that simple!!)",10,34,34); } else if (""") print(154 % 91 * 10 + 345 - 2) print(">") print(89 + -920 | 65 * 2 ^ 12) print(""") { System.out.printf("4@abƤḞ⁹%dỴ !Ṙȯ/ṣƥA^?rCs>Y|°ỵ4$m(0a+4r /ZÐæ⁽e)D1ṖÐ,Ḅ Ḃ &ẉ1ɗḌ¢ġʋḞṬŒ$c “¢¤ƲgṖḳ®[⁾»",29,10,90,3,102,11,1234,95,666); } else if (""") print(10203 / 192 + 182) print(">") print(12 - 45 * 69 | 3) print(""") { System.out.println("YoucAnTryTofIguReoUtwHatThislaNgUagEiSButyOUwoNtBeaBleTobEcaUseiamToOpoWeRFulmWahAHaHaAnDhEreIssOmefilLeRteXtCOmmeNTcOmmeNtCommenTpRInTLpAreNcAPeitSiNGLeQsCaPeDonEdoTrpArencoMmEntCoMMentCoMMeNTfOOBaRyAbBaDabbadAbBAdOOcAnyOuFIndoUtTHEsEcREtBUrIEdINtHIsMEaNInGLeSStEXtNOYoUcaNTbEcaUseIhaVetHepOweRofNopUncTUatIoNandilItERaCYoNmySiDEbyeByePPl"); } else { System.out.printf("%s"+e+"ẊD.%1$s",o); } } }""") def main(Main:Main): Main=Main @main def mian(): Main=main(Main()) ``` Outputted phrase: "It's Done." This is a pretty easy one to crack, but here's a hint anyway - at least 2 of the languages can run on the JVM. And choose your version carefully. > > Okay, it's cracked now, so here are the possible branches: > * Python 3 + Java + Perl 5 - prints "It's Done" (no period) > * Python 3 + Groovy + Perl 5 - prints "Іt'ѕ Dоnе." (wrong Unicode chars) > * Hypothetical Cython 2 version (or other Python 2 version that allows type hints with `:`) - imaginary 2-D language > * Third branch in layer 2 - TrumpScript program that outputs "it's done." because TS is case-insensitive. > * Fourth branch in layer 2 - Rockstar program with correct output but never reached > * Dotty + Java - nonsensical Jelly-ish program > * Sixth branch - oOo Code, never reached > * Last branch - Husk, never reached > > > > > > [Answer] # 4 layers, [cracked](https://codegolf.stackexchange.com/questions/212069/peel-away-the-layers-robbers/212138#212138) by Sisyphus ``` "/-G^A_:;aT$e}qz\"7\"y^&'7T|-q3ZO@,]GN6==3g4U^Y)S_L7:fVp6_4'!s,a8IUK1[ Sp.)Ae)/P%ZY&D*K>j6feVfN1Fky,Vl2Z'?ie%\"<f,nv\\VS&T^e]5ZP}j!6/AivE` 0>9x<DdQL# kdzrz~sSO\"7[&U"{32-}%95base 3base{' '1/=}% ``` This isn't a serious answer by any means, but it was fun to make. Final output: `Code Golf.` Hint: Love is a great mystery, [but I couldn't really explain it](https://mcaweb.matc.edu/winslojr/vicom128/final/). This was cracked quickly. [Answer] # 2 layers, [cracked](https://codegolf.stackexchange.com/a/212104/52210) by *@Sisyphus* ``` ,322,241,245,241,245,313,245,241,241,315,245,241,245,241,315,245,245,245,245,245,245,315,315,245,245,241,241,315,313,245,313,245,245,315,241,241,241,241,241,315,245,245,315,245,241,245,315,322,241,245,245,245,245,245,241,315 ``` Output: `Greetings!` --- EDIT: Solution after being cracked: > > I thought it was fun to try some languages I've never used before, since printing text to STDOUT is pretty straight-forward in most languages. > > > > The first language used is [μ6 `-a`](https://github.com/bforte/mu6), for which the leading `,` will take some integers and encode them as a nested tuple. The integers are in base-6, so `322,241,245,241,245,313,245,241,241,315,245,241,245,241,315,245,245,245,245,245,245,315,315,245,245,241,241,315,313,245,313,245,245,315,241,241,241,241,241,315,245,245,315,245,241,245,315,322,241,245,245,245,245,245,241,315` is actually the list `122,97,101,97,101,117,101,97,97,119,101,97,101,97,119,101,101,101,101,101,101,119,119,101,101,97,97,119,117,101,117,101,101,119,97,97,97,97,97,119,101,101,119,101,97,101,119,122,97,101,101,101,101,101,97,119`. These are the codepoints for the characters `zaeaeueaaweaeaweeeeeewweeaawueueewaaaaaweeweaewzaeeeeeaw`, which we can output with the argument flag `-a`. > > > > The second language used is [evil](https://esolangs.org/wiki/Evil), which is generated by [this Python program (second method)](https://tio.run/##jZPBcpswEIbP@ClUHTpS4SAx0x5cyLWnPgFlOorZxEyxYDBqnEzf3d2VXIRxkwk@ePh39X@/WGl4nva9zc@tHdzESsa/jQBTax@PH/jXs0GlM4f7xjC7FcKmWn5U9/ryyA2s6lhUSmn6yaLI5Z@geQEL8u5u1rxAWlHoWfOPpj40d2v4gnyVgm0OMBk4DeMRl1RVXX/KP39B@aEfGZVa28ApCw2tZWDdAUYzgZjXye0mmQ04DwZBqWaHmr7PE2ftQ3Rl0B2B8ReOuKQD@zjtsUvT29O@7YDZfmKm68SMSShVTHQdKHYlSEE/r0hWliyY@1KyM7ZpG1zwkyZkhLeTqxINB/5fok/rliWECUoadrywryXDuCLAU82KOdSqLYROktsSxUAx5Ya/yYL3seB1FkQWvM1y72O511kushyxLrNPL8OfT9b18fES1oextZPg3wFvX8P0lkt/WHd74w@Ev40I9m0seqm66sdGUJusUzyLWfTi8sY3/@c7jPA727nRm7@0g@A/TkpxlgZSFv5oq/MGNaaNYKKSibwEQKsQYLUivlR6W9NNWSiqLku6P/7KRH1hkV9B1S0sfJBjP07QiDgNnUWLOvsFzyWOQ6JBdj7/BQ). Here, `z` resets \$A\$ to 0; `a` increments \$A\$; `u` decrements \$A\$; `e` [weaves](https://esolangs.org/wiki/Evil#Weaving) the 8 bits of the binary representation of \$A\$; and `w` outputs \$A\$ as character with this codepoint. > > > > [Answer] # 4 Layers, [сracked](https://codegolf.stackexchange.com/a/212102/48931) by Sisyphus ``` 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+1+1+1+=A1 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+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 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+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+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+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+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+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+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+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+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+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+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+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+;A;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+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+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+;A;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+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+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+;A;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+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+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+;A;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+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+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+;A;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+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+;A;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+;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+;A;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+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+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+;A;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+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+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+;A;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+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+;A;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 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+;A;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+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+;A;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+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+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+;A;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+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+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+;A;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+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+;A;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+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+;A;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+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+;A;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+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+; ``` Output: `The Final 1` [Answer] # 2 layers, [cracked after 18 minutes by Sisyphus](https://codegolf.stackexchange.com/a/212179/48931) ``` printf("Code %s." % "Golf") # Python doesn't use printf?? (Of course I know what Python uses. (print)) # ^ The letter i. Superb letter. Seriously, it's one of the only two letters that can be a word by itself. ``` It outputs `Code Golf.` This will probably be cracked very quickly. [Answer] # 2 layers. [cracked by Sisyphus](https://codegolf.stackexchange.com/questions/212069/peel-away-the-layers-robbers/212168#212168) ``` //"/pr/in/t('C/o/de /G/o/lf./')"#ec/ho/'C/o/d/e/ G/o/l/f/.'#con/sole/.l/og/('C/o/d/e/ G/o/l/f/.')#g))#:jd@#$%6a ``` Options, options... Output: `Code Golf.` [Answer] # 5 layers, Safe ``` #include <iostream> \/\/ "sgnitreeG"<._@ /x/zzzz//z/mmmm//m/nnnnn//k/p //h/ o//j/ / xznjkxmmmnnnnjkxznnnnjkxzmmnjkzmmnnjkxzmmmnnjkzzmmmnnnjkzznnnnjkxzzhjzmmmjkzzmnjkxzmjkxzmmjkxzmmmnnnjkzmmnnjkxxxxxxmmnnnhjxxxxxxxxzmmmhjzmmnnjkmmnnnnhjxmmmnhjzzmmhjmhjzmmnnjkxxmnnnhjzmnhjznhjzmmnnjkmmmnhjzzmmhjxxzmmnhjzmmnnjkxzzznnhjNever gonna give you up.... Never gonna let you down... Never gonna run around and desert you....hjzzzmmmnnnhjzmmnnjkxzzzmmnnnnhjzzznhjzznnnnhjt ``` Just a first attempt, so probably won't be too hard. Final output: `Greetings!` ## Solution: Layer 1: [///](https://esolangs.org/wiki////) ``` #include <iostream> // "!sgnitreeG"<._@ nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn p nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn p nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn p nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn p nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn p nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn p nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn p nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn p nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn o nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn p nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn p nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn p nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn p nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn p nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn p nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn o nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn o nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn p nnnnnnnnnnnnnn o nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn o nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn o nnnnn o nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn p nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn o nnnnnnnnnnnnnnnnnnnnnnnnnn o nnnnnnnnnnnnnnnnnnnnn o nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn p nnnnnnnnnnnnnnnn o nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn o nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn o nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn p nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn o Never gonna give you up.... Never gonna let you down... Never gonna run around and desert you.... o nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn o nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn p nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn o nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn o nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn o t ``` Layer 2: [Grocery List](https://esolangs.org/wiki/Grocery_List) ``` echo u:,120#.inv 493675 1496505 1682621 1650191 1429778 1546144 ``` Layer 3: [J](https://www.jsoftware.com/indexno.html) ``` "!sgniteerGGc"bk,@ ``` Layer 4: [Befunge-98](https://esolangs.org/wiki/Funge-98) ``` cGGreetings! ``` Layer 5: [V](https://esolangs.org/wiki/V_(DJMcMayhem)) ``` Greetings! ``` [Answer] # 3 layers, cracked by [Sisyphus](https://codegolf.stackexchange.com/a/212094/78410) ``` 101;1111011;0000;11011111;{110000;11100010;11011110;00110;10111011;000110;10001;0100000;11011;000;11010101;0000010000;10100000;101101;0100000;1101111;0101111;}1001010;0000;100000;10110001;011001;011"00001101110100100010011001000;{111;011111;}1000\1101100;010110;110011;0\;110001;0111010;110010\10110;110001;0110000;\11011;0010;11001;011\11;0100000;11010100\;10110001;101110;1\001;001010;110111\0000;10110001;10\1011;0000;10100\000;0100110111\101101111111"@ ``` The phrase to print: `Code Golf.` Can you get through the binary hell? [Answer] # 3 layers, [Cracked by PKmnQ](https://codegolf.stackexchange.com/a/214035/97691) ``` "D'`;#]8JIY4jEhw5uRQ+rpLo98*Z('D2CAdbx>+<)yxZpunsl2SRngfe+Lhg`_^$EaZ_^]V[TxXQ9UNrLQJOHMLEiCBAF?>=a;@?8=<54X876/4-Q10/o-&Jkj"75*1-"F&%edAbaw|{tyr8vuWVlkj0Qgfejib(`H^]#a`YA]\[TxXWP8TSLQJnHlkE-CHAeED&B;_?>=}|4Xy1U543s+O/o-&Jk)"75*1-"!&}C{c!x>|{zyxqY6Wsrqpi/mleMiha'HG]#a`_^W?[ZYRvPUTMqQJ2NMLKDhBG@?>b%;:?876;:3W10543,P0/on&J*)('&%${z@~w|uts9Zvutmlk1oQPfkd*bg`_%cbaCYX|\U=YXWPtT6RKoOHMFEi,HGF?DC<A:^>~6;4381Uv4-2+*Non&+*#Gh~}|{"75*1-"y?wvuzyr8vXWsl2ponmfN+Lbgfe^c\"75*1-"`Y^WVUySRWVOTMqQPONM/EiCHG@EDCB;_?>=}|49870/.R,1*N.n&%$Hi!EDC#zb~}|uts9Zpo5Vlkj0Qgfejib(`edc\"75*1-"`B^]VUTxXWP8Nr54PImML.DhHA@EDCB;_?>~<5Y9270Tu-,+Op.-&+$)"75*1-"Fg%|B"75*1-"!~wv<)"rooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo; ``` This probably won't be too hard, but good luck fighting through my unidomatic code. Outputs `The Last 1` > > Okay, it was cracked pretty quickly, but it did take two people to do it (see comments). The first layer is pretty straightforward, just a string pushed to the stack then outputted in <><. The second layer is Malborge that came from a generator posted by another user in this thread. The third and final layer is an abuse of rust's macro system so egregious that it won't even run on the rust playground. The macro I defined creates a function that invokes a macro based on user input. I then invoked the macro so it created the main function with an invocation of the print macro. > > > [Answer] # 2 layers, safe ``` print "%s" % "Code Golf." # Ss4iSBr_Z*YWTR>:wTC`^ 5 # x red herring `-~DqD|`< # Xt1,i>-%qrFhK-`@eEw, ye # uI' | g[Wt7BU3A)N<[LsHG # >s}R"Ia:HF!s {k=)qxlo9h # $ia;,t"-,]xO3?VDC]<,\:# # G.-oHn9>.E%B,dx7db_Xs,Z # H RU"%+70+<G^$n|GT,qR2L # iB\7.n}-?w\&bF -r[6&G8> # _}*c%<qWW~E$/M0UiW/A8'Q # 5AJ"ineTc>g+c&PBS`dtU## # 7`w-H3|kj3Oz4t<;4zyI72q # 0jt}>,+=%;'{q837yZo)+ma # 'a7Upv&<(VG.m}`l}2!]4YX # ,M`jL>Xd%Igji\'cvim+fL] # !;S4u&Gv+oT%|G,rHVt?%N< # JkB*~M'&>er%W@TK7W% FxC # Wikiq#k*MrX!c<&QkZ?36R. # "GZu2E6p>qR&r'OF.f3,t0W # R1`UHS%- B+<PkmnQ8ExK;t # Le71:N>"(%05vtiPML$\_H. # 003:W%<P<(3j4vhr-s3,L.W # SJp`S ('![j,z>x#.cN6&(/ # |m(Bl[^(]<j,w={U$.6:-nm # @}h[>]c+HbV 7:11mn&)xWi # [%|&(<Y7V]Qq"a(1BlDs2dJ # >(~ET7A4+g#b^jhP|G3i^:4 # %<fO}(fRpC_G6f?G0jm@w(( # (?pV{WF9'X-n76IcXE>!hWW # VjNEAf.|97dvm4<Ph%MOS=X # >o%y'k44eGzFJE5r^skEy]v # Yg(mQf9Q.|&mTKHA<1kqBnJ # WK%v_zXXANpS>~Od3Fl\hKl # "g(;RkLx=,BT)JT[VXs<]'V # %g>v[h(z]%)4e`&`P=6^Q__ # Z`^sV3/m'(<=T?{Z})TccNW # {Cb>k]F?E>(\$IyZ+tS#i,# ``` Outputs `Greetings!` It works in Python 2, but it doesn't output the correct string. There's a bunch of gibberish in the comments, but how could that be executed? Also, just in case it's useful to anyone, [here's the code I used to create the original gibberish](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKEoMS8lP5crLb9IIVMhMw/ET0/VMDLWtOLiLCjKzCvRSM4o0oCo0gNRICFjIx1DIzNNTZ3UvBRbJSXN//8B "Python 3 – Try It Online"). ## Explanation The first layer is axo. In axo, string mode is different from other 2d languages, in that it can change direction, and do math with ASCII values. Also, `%` is down, probably because you'd be using `v` in your strings. I took advantage of those by hiding instructions in random gibberish. [Try it online!](https://tio.run/##FdLZcqpAEIDh@/MUiA5gWKKBSFTEiEHcVxSjohhXRFSWuOur5wzXX03XX90zPe///g6uufMRFHgoAhA0v58vEGW/XTLovzDS8TizI7mTwcu3prbF1EnNG2PkHcoZcRdzZL1w4esVYtDPL@frbghQ@n6cMkUaOG5hXaGNz4V8opDLAspvCUfuyGqo@bzUZXPRujCsekUFiug92mhpmioWQh5yszJR57zdJ9dQIuY0TfkoTennBpvtfeV1gRqlwlAUht4Xd0mRkYFEzc/8/GfS96gBlCLS7qKA5GOkoIwju7uiUk77rQrFlEY8s3vQ2dMI@ykgtDtMYMqHCGXyeJkBwdG0pxx5rcW6pvaa@8BbUN5zZdTcLdSZuCJnWFPqGHO/Gw4KeONEF9m7tWEbV84X0tz1UuLfHCixjf8QKTID0vjN@WD5y2AfJe0pFHzKdw9HTCB6CmM/jO3jLaRz330oVM3YVMX@HJRWG3OEz46mTS6rOpRQusP9YsqR3KvgrlBusednQT3YddmSXp41HBMXLtA@1QqvAaRwzkPRTMt0wtZLze2HZgLWsgZZNtFmoKDK4PdNThxEp425eKPALFnKj2lQ2nGjW@wAGpFIoWnZu9aHfK6kfSjVBR9P1UWUALH3o282a9XIaFIMpsVibEoDQlMg2A13XLu0x1JVJpjWKR@MDkLgoeGGuornMDOrJzDiFcrdJqTtcEzowoY6ZW7dCJNI0TsbyudjPRT1GVn86SF8Kh63d1j0rJlQhuCOEcI339NbDjol4tL2y3ubl4O/Qzxllc9x5Cr8M96sm3eFNccpDgoQlo0HsWwf8hMlscwqsY39eSIIKET20LtphSTep3d8ojTry2JorQXVvU1dzi2Ze5KfH21OaK5BrdHJBPcR9@CCWxy3UK6Fsvzujj1LvuhHKN8rwm4tky3mjtlqpZgT4pYj7YI2rQKOk2u/n6sfOuKzMWcL29G6sg2usCLSbat6zlCSGi2rw17fE3S8F1SvxONwTVx1EOUWBmY0M4lxazKBMjDGXo99tXFCyKjZ2@ARVWezelB9y/@Ill7IyiIxipQuA9LvhE0q/Pf3Hw "axo – Try It Online") Output: `"Greetings!"` The second is Foo. You can tell I only put my effort into the first layer. [Answer] # 7 layers, was invalid [Code too long to fit in post](https://gist.github.com/chunkybanana/7d0c638e40a0dad41ffbe56081f13f98) (65365 bytes) What it would've been: ## Layer 1: Javascript (v8) [Try it online!](https://tio.run/#javascript-v8) You'll have to paste the code in 'cos I haven't found a link shortener that supports TIO links. This layer is just something that doesn't prettyprint arrays, so Intcode's fine with it. ## Layer 2: [Intcode](https://esolangs.org/wiki/intcode) [Code still too long](https://gist.github.com/chunkybanana/cf8629cc7de3e389cee2bc4746f82c6d), paste it in [Here](https://tio.run/##5Vjbbts4EH3XV8zaL1KsBI6dXiLE@7IXoG8FdoF9MASBsWhbG90g0Y3dot@enSElmaRs10mLdhebAIGlOTM8c2Y4pFPuxLrIp0@sSkTCa5jBJwfw5zqAGx@Gf7IHDlsfdj58hEfE4NNoB6KAsqjho4ROFHQAA9heWLZpABO0/SU9k7zciNa@lfYbZX9fJbkAxGTAhGZ@FcAUze@W6h3MZjAO4O9NVrZhdhL32sL9dAT3RlFVdLZwBxbdt6Ydl7MAt4rvL2uWrzhUPGUi@cAJgPIVucLcBmMY/pbHUCyBb/liI02fYfgrX7JNKoDE3kFSw7XjLDf5guyG9CnL7mMGtWCLBx/Sde1DRX/SYsEI7ENWxLwOFOKq5iIi8dzOLgMp4wqNMRPMlWGk31VZlK7nwciGVDbE8522xt@J08XZnKY9TucywU4UruxGLdzNF8OV1KWunYGR3gt/7PQ@O44Tc@oeUbGFiBZFlrE8Rs6Cr3jlBXKx5i02Ti2qziZNyRJSnrsNwoO7GZawY1hxsalyaF18@INywrUlgqc132OLEuM3ceaXkyB0DNKaMbichIeWcIvSa5eY0/NizSoPlkUF9AmLoUKFtD7@LlJW1wqvaJASUZTkiYgit@bp0qdRUbH7lM/mobfnilm3hsAoBzldycIh3xbSIcyEe/h56DiGAbd9dM9qjraxaUlK@U5jjVVoSHs9/alC@5U83Q17llp2n28ecxzDH1i64WbCYldyV5o9mld1miysZJJ4S1kTBFfCeo5w7hzPXYMbSBIXTT/btE1vqmpEJa1oQrrkcWl7WC6m4FesLDm2@thz@sa5pBUiP6mErtjqkGI/WKrZ99eqaa2eZLpUMU8NqR7XTGjroFn3J6vm3g0@5Ysnn5qPptT0pjmth@@bw1G@NNPR2eolxKieprsWEA/H4bss43HCBD8UC10Pe07Mpaly5m4eGb6n6G21vVqUC1wgum30sHeotUSvcWnmW9Ohmd1H26ZXYnVwnOjTxkMbTN2ZqFjvj7qD/PV5ZEPVQZWxJHfLqlhVLGu86Qk11ua@eMjV2McP1PYN/qousR/dgT/wwub00sbo4zpJOb25k6qQj6efTqS@351F9oFJ8HlShnt11N1rBs2Fd64iaCM@aWtKFOfXPkxCU839sdvd3booOg7vNohpGNB8MM2VZZ5Y3o3OBmZqYsxhpNpGKiHn2xSIpXyej8MDW8BYZqTW6XrVOZSz1PPE5c8zGZUUVQrumHuyEZhIvkxbM9kz8jQT0ItC@15P/GAq/T3VD3rRRB1dQyBzV6mHX9TmiDQ3L5PmG5E6xuqVzSqPE61P9xdjXWPzAm9XsovRV5i@wkXtt6sTS0xOLdGNFCPaGfU9R4/X316PvBD/bU3eBEcG4bPVqE66nszw2AC11dYCfN2MpJmEdO@IdD@I5NBGohvs9Rli95zGzrM37Nv/czEwxr@rGrdmWHmHemk9pFN3/2yuY88mZDG6rzh7UOjm2jj4PclZqqgGMFCnp7p5Ok5CXyhylvEoomiDKKKrYBQNVFR5L2z/0/L09PQP) in the input box. This simply prints the number for layer 3 by building it from base 1000. ## Layer 3: [Golunar](https://esolangs.org/wiki/golunar) [Code still chonky](https://gist.github.com/chunkybanana/700a26a4207e3733cd6b44f64eb57db0) [Corresponding BF](https://gist.github.com/chunkybanana/78d2d792c5de16696103613d05a8b9fa) [Run the BF](https://tio.run/##3Vpbit0wDF1QiFYQspGhH9OBQinMR2HWn97rhyw7lm1ZSubSyzB5WI6lo2NZcvLz7/vvz19fH3@OY1vw97Y//@94vdPD9vitP57ngL99efwtsG3P890fY1N@eb5xEsju5K3kKp3i2flJ3Aj91n1f1@zG9sDHGekN9a1PEFx/fxXOXVveBAt5bBDxEhG2OGTe34@Fj@YeEq6cT1YoO6K0a49tqbdr73f0Q5edXdcomjAgz4qyhRk6KxhNEEMxCGXvrDttZ1VGZ1JQKrqUyjCYomPC9Ro4dAkper6NoNRGb478zY4I1HZqUGPn8CATBV6TIHVyNKJO1KGHBgtGFY6bmGHiBWs3QFW1exAxpSRxvx6aQLjCfXqEKI1lvURdpg22t1gVP@@MCfc4dyiWNzQN83V4VS2IrF5FxDDFnoNQkZWwry6nLE/ewZxW46C5KQCNXHAUZBHEEnM5e@dVvQKhK5J0mpBVx9QxuEVgyWhgPp7cIyDn37TW7dppyjMMc4Xxs80gE9J3bNDjPQf3pUs0ze/qQDTCy2QRdlESiarDWXmDSo2Jyx3Nx6LAYNWdW6PkrIKxUMkrm8FyfPrAzPqjKuLLytUA0RmKnPYmeFL/B26WxrkRK@YnXyc1n/MmDJebGoBaWZhRrWq1JvEZrMluC1xMUm3eNrMNY7eLLdz2MNsongygoImh5vFRVpR2Z4g65c2ZzmRqN6zK3UW5sXMoKBGNCtuXSfLb5BbWOopi8J7ZeEfSarPpNR7QzKYVmOzpvkR@2NPEqN4S79gPv/au8NW9f4f0Hn4NL/c9X7L33DgZiN5eCOWh8n0At@e3xA8PCIrE3PzzgCQbP1VAIXfMdEjaIZfi/SRFm@JIiACBAJszO87BFjOaJJt1L@drqUTh/sIWApfsmRTRIqAl6eS4hQLN8CDAv6I2iAzRonBD8tpx/AM) ## Layer 4: [Splinter](https://esolangs.org/wiki/Splinter) This is where I stuffed up. It was basically the output of the above program with some backslashes thrown in, but when running it through a converter, I forgot to escape them, so the program for this layer wouldn't work. Anyway, next layer: ## Layer 5: Brainfuck ``` ++++++++++[>+++++++++>++++++++++++++++++++++>>+++>+>+++++++++++++++++>+++++<<<<<<<-]>++++.>+.>++.>++.>+.>+.>----. ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fGw6i7eBMBAsF2NmB5TBlISI2EKAbC@bq2YEQDIORLhDo/f8PAA) This outputs the raw bytes `5e dd 02 20 0b ab 2e` ## Layer 6: Vyxal [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJgwqzqmI0gwrvigoYuIiwiIiwiIl0=) When the above bytes are interpreted as Vyxal in the Vyxal codepage, they produce ``¬꘍ »₆.`, which decompresses to `Code Golf.` ## Layer 7: PHP ``` Code Golf. ``` A cheating quine. [Try it online!](https://tio.run/##K8go@P/fOT8lVcE9PydN7/9/AA "PHP – Try It Online") Anyway yeah, this was invalid. ]
[Question] [ ## Overview The *sharpness* of a word is the sum of the sharpness of each of its letters, using the following rules: **Sharp letters** * `A`, and `V` each have a sharpness of **1** * `N` and `Z` each have a sharpness of **2** * `M` and `W` each have a sharpness of **3** **Dull letters** * `C` and `U` each have a sharpness of **-1** * `S` has a sharpness of **-2** * `O` has a sharpness of **-3** **All other letters** have a sharpness of **0**. ### Example The word `SAUCE` has a sharpness of **-3** since the `A` contributes 1, the `U` and `C` each contribute -1 and the `S` contributes -2. The word `MAZE` has a sharpness of **6** since the `M` contributes 3, the `Z` contributes 2, and the `A` contributes 1. ## Task Given as input a string containing only uppercase letters\*, determine the sharpness of that string. \*If you wish, you may instead take the input as a string containing only lowercase letters. Other common input formats are also acceptable (eg. a list of characters, a list of codepoints, etc.) ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")! ## Test Cases ``` CODE => -4 GOLF => -3 SAUCE => -3 CATS => -2 MOON => -1 NONSENSE => -1 ZUCKERBERG => 0 STRING => 0 CHALLENGE => 2 NAIL => 3 CARNIVAL => 4 COMPLIMENT => 4 WAVE => 5 UNKNOWN => 5 MAZE => 6 ``` **Extra test cases (Provided by [@Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum))** ``` MIZZENMASTMAN => 17 PNEUMONOULTRAMICROSCOPICSILICOVOLCANOCONIOSIS => -26 MANAGEMENT => 12 CONSCIOUSNESS => -13 ``` [Answer] # [Python 2](https://docs.python.org/2/), 53 bytes ``` lambda s:sum(3-"MWCUNZS_AVO".find(c)/2*4%7for c in s) ``` [Try it online!](https://tio.run/##VY99a8IwEMb/z6cIwrAd6tbqJggdZFnmgs2dNG2FMpBOLRZ8w1Zkn76rsdsQAnl@zz13lxy@y/V@51aZ91lt0u3XMqXFqDhtrX63pWY8gkTPWYytXpbvltbCfnDvB3fDbH@kC5rvaGFX53W@WVFnRGo@nMoO3Z/K@qYePabnufEsu1ccNnlptan3Qts2@c/ku9K6Qu0ejjXejiE0LYrVsaSZZXybel5T6lDrJtr5y9gVxzdx2dUdkDH670b2iWYRF43mLNRGukQhgpEOAQQt6tNgEvGJCF5FML4Yj0SHgYRG8w/m@wLGJusSYNK/qMvkAGTMDA0IRzX1pRIQXnnGYtPxRCKYAM7gCoolxn4mSiaJAMV0qJgpOkMyBREpBIz8MGBK8gA1x6nkWvqSY4w@Z4AcQaKWza/qQQzYWPxudtz6KaC5xEiD0NeU0/8B "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “CSO“ANM“U“VZX”iⱮ€§ḅ- ``` A monadic Link accepting a list of characters which yields an integer. **[Try it online!](https://tio.run/##y0rNyan8//9RwxznYH8g6ejnCyRDgTgsKuJRw9zMRxvXPWpac2j5wx2tuv///w/wcw319ffzD/UJCXL09XQO8g929g/wdA729PF09g/z93F29PN39vfz9A/2DAYA "Jelly – Try It Online")** ### How? ``` “CSO“ANM“U“VZX”iⱮ€§ḅ- - Link: list of characters, W “CSO“ANM“U“VZX” - list of lists of characters = [['C','S','O'],['A','N','M'],['U'],['V','Z','X']] € - for each (L in those four lists): Ɱ - map across (c in W) with: i - first (1-based) index (of c in L) or 0 if not found § - sum each resulting list - - literal minus one ḅ - convert (the list of four sums) from base (-1) ``` [Answer] # [Python 2](https://docs.python.org/2/), 52 bytes ``` lambda s:sum(3-"MCNSAO_WUZ_V".find(c)*4%7for c in s) ``` [Try it online!](https://tio.run/##VY9xa8IwEMX/z6cIg2E7VNbqJggdZFnmgs2dNK1CGYhTiwWtYiuyT9@1abchBPJ@797dJafvYnfM3DLxPsv96vC1WdF8nF8O1qB3pzhohstFFC/nd/0kzTbW2n4Y3o@S45muaZrR3C6vu3S/pc6YVHy6FF16vBTVTT16Xl2XxrPsfn7ap4XVod4L7djkP5NmhdVA5Z7OFd6OIXSV59tzQRPL@Db1vLbUpdZNtPuXsUuOb6Le1RuSCfrvRg6IZhEXreYs1Ea6RCGCkQ4BBC2q02Ic8akIXkUwqY1HosNAQqv5B/N9AROTdQkw6deqnhyAnDNDQ8JRzXypBIQNL9jcdDyRCKaAC2hAsdjYz0TJOBagmA4VM0VnRGYgIoWAkR8GTEkeoOY4k1xLX3Kco88ZIEeQqGX7q2oQAzYRv5sdt3oKaC4x0iB0k3IGPw "Python 2 – Try It Online") Improvement on @xnor's answer. ``` M C N S A O _ W U Z _ V ? c 0 1 2 3 4 5 6 0 1 2 3 4 6 "...".find mod 7 0 4 1 5 2 6 3 0 4 1 5 2 3 "...".find*4 mod 7 3-1 2-2 1-3 0 3-1 2-2 1 0 (3-"...".find*4 mod 7) ``` \*4 is to map -1 (failed find) onto 0 [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~61~~ 53 bytes A lookup table based on the ASCII code of each letter. Takes input as a list of codepoints. ``` a=>a.map(c=>t+='50363133463254'[(c^98)%22]-3|0,t=0)|t ``` [Try it online!](https://tio.run/##jZFba8JAEIXf/RWhUIykRk2ibR8ibLfbdHF3VrKJgmIhpNoLVsWEPvnf06i5NaXgMG8fZ@bMmc/gO4jC/ccubm@2r8tkZSeBPQz0r2CnhvYw1uxmv2sOzJ5pWgPT6FvNuRq@3N@1rg1j0TYP3ZvY7rYOcRIvo1ixlUixh0q43UTb9VJfb9/UlTrXdT1anCeeqB6@B3ucbkOx2kqr0TiK1SssHslVSymq01HaVsYcwZ7qzMyYRD6uCqsMI0/WdUbGuBBQZ72MgQBJ0s55lc18PCLuA3GdM02Z0s29eC4Fp5xaZfgZMUbAyYemTMu9AKKs5kUrb3CBThCreNGsIjM@ZpQT8AovBZuiST1PrZ8xH0YgpuX5VcbR7I9ukD@J09mMAEfS4@hXev/WUd67zeRjID4XIHzmuYhT7AqJxZhiSRnFYiIYRiCwACokPT/u9LFBYQ2QQ8pzL9xuFGmBxFT4EoiUl5pv98zkBw "JavaScript (Node.js) – Try It Online") ### How? By XOR'ing the ASCII code with **98** and applying a modulo **22**, we gather the characters with a non-zero sharpness into the range **[0..13]**. This results in a lookup table of **14** entries. If the result of the formula is out of range, we get `undefined - 3 | 0`, which is **0**. ``` char. | code | XOR 98 | MOD 22 | sharpness -------+------+--------+--------+----------- 'A' | 65 | 35 | 13 | +1 'B' | 66 | 32 | 10 | 'C' | 67 | 33 | 11 | -1 'D' | 68 | 38 | 16 | 'E' | 69 | 39 | 17 | 'F' | 70 | 36 | 14 | 'G' | 71 | 37 | 15 | 'H' | 72 | 42 | 20 | 'I' | 73 | 43 | 21 | 'J' | 74 | 40 | 18 | 'K' | 75 | 41 | 19 | 'L' | 76 | 46 | 2 | 'M' | 77 | 47 | 3 | +3 'N' | 78 | 44 | 0 | +2 'O' | 79 | 45 | 1 | -3 'P' | 80 | 50 | 6 | 'Q' | 81 | 51 | 7 | 'R' | 82 | 48 | 4 | 'S' | 83 | 49 | 5 | -2 'T' | 84 | 54 | 10 | 'U' | 85 | 55 | 11 | -1 'V' | 86 | 52 | 8 | +1 'W' | 87 | 53 | 9 | +3 'X' | 88 | 58 | 14 | 'Y' | 89 | 59 | 15 | 'Z' | 90 | 56 | 12 | +2 ``` [Answer] # APL+WIN, ~~42~~ 38 bytes. Prompts for string: ``` +/(2/¯3+⍎¨'4562103')['AVNZMWCUS O '⍳⎕] ``` [Try it online! Courtesy of Dyalog Classic](https://tio.run/##PY/BSsNAEIbveYreViml2qj3cVzj0N2Zks0mEPEQKhUhoNCTL6BeWrz4Dt48@AZ9lLxIumSDMIfvn/n/GaZ5bWePb0378jRbt812@7zuu/23Nd37V5p0nx@bfjo/WcwPv@m02@0PP@ri8mpxfpaq03sFJde2Qu8mMlHd7i8EH/qQ6TeJQrnRKgmQibkdwIHH2EIo3ABWhAdgYadDDaL2uNT5tc6zmCty4oh4B8ZozqKPgcy4L2cqYRRiV4as5mKQFZTR7XnJUsVzFurYtFTXmi24wkIcrVh7KyzeFDlYwlwcyorQkSGUUgwCCwqTOBqfAIZM/x8MM4ck3rF2wXAE "APL (Dyalog Classic) – Try It Online") Explanation: ``` ⍎¨'4562103' Split number as a string into individual digits and convert to integers 2/¯3+ Subtract 3 to give the non-zero letter values and double up each value ['AVNZMWCUS O '⍳⎕] Find the index position of non-zero letters that occur in the input. If a letter is not in list it is given an index of length of list + 1 +/ Sum the values corresponding to the indices of non-zero letters in string ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 31 [bytes](https://github.com/abrudz/SBCS) ``` -/1⊥¨4|(↓4 3⍴'ANMCSOVZWU ')⍳¨⊂ ``` [Try it online!](https://tio.run/##FcsxCsIwFIDh3VN0iw5FpL1AeAQNNHmlr6ngJkhdCroKTgodCi2KeAShm4OeoEd5F4l1@YcP/u2xCnenbXXYex/OF9y8hj4@T7l@xEHE7VdIa4Cw2KxdEIgZt5@h5@biS65v3HbcXId3xPWduydlMDZfafKlMNLKpTLK5mJSCkBLoNGRVUR/SK1yBi26JM@k0ZAhAaYaSCcasMAEpMXx0kiaxA8 "APL (Dyalog Unicode) – Try It Online") Tacit function. ### How it works ``` -/1⊥¨4|(↓4 3⍴'ANMCSOVZWU ')⍳¨⊂ ⍝ Input: string S (↓4 3⍴'ANMCSOVZWU ') ⍝ 'ANM' 'CSO' 'VZW' 'U ' ⍳¨⊂ ⍝ Find the index of each char in S in each of above ⍝ Index is 1-based, not found gives 4 4| ⍝ Modulo 4; convert 4 to 0 1⊥¨ ⍝ Sum of each row -/ ⍝ Alternating sum; (ANM score)-(CSO score)+(VZW score)-(U score) ``` [Answer] # C(GCC) ~~84~~ ~~73~~ 72 bytes *-11 bytes thanks to ceilingcat* ``` t;f(char*s){for(t=0;*s;t+=""[*s++-65]-4);s=t;} ``` (note that StackExchange strips some non-printing characters) [Try it online!](https://tio.run/##Vc9ra8IwFAZgNqtCf0UWKG21grvoB0MYXZe5YpuOegO3fSi13QTnxGQwEH97l3iJaykNfU7ynpO09ZGmRcFRbqWfyabB7G3@vbE4bqMGQ7yJYVWraKenXrsQ30utUq1rWg2@Nliz2ep23lt3NmKYo13BM8aPSQ5YrDjIftdZyrO5vdXlb5Lyn2QJMMgtZqM9rRPGBJwqWB1B@nojNuQWNFgPGHNgpFgulsHstxV0DifvAZQrBD0A82SxFH6IUnUTm6JoXpmOinaA6A70nb6f4CtZrCwbbPX99NCLHolIkZc6Sj8KnqTcKhm6Y4@UyXNHQyk3SsIoolKuldCIDol4yzobewMSP5C4L7x97jGKfVom79kNAkL7MuDch7p@IOD/KDH1J67E8yW8KHwJ/JDQUYmn7kSmdRSM6YBGU1qy0J3JTV0Bu@IP "C (gcc) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~62~~ 60 bytes -2 bytes thanks to @Neil! ``` lambda w:sum('AVNZMW'.find(c)/2-'CUS_O'.find(c)/2for c in w) ``` [Try it online!](https://tio.run/##TY9ha8IwEIa/51cc/RKFbgM/Cg6yLKvF5G40TQtlMFylWNAq6ij79V0Thw4O3jcv91zujj@X7aGbDc3iY9it91@bNfTz8/d@wkWBlSn5Y9N2m0k9fZo9cOnsJ/1LmsMJamg76KfDzXOy0v3BcwZwPLXdBeoY@OKZx9CMJGMhZMxDvYciSa8qiiFKSL95tcLJEEiRW6@GCL0ioVVjeV85uVLZi8qSgORZisHJpdBaYRKaUKT6OijDtBBXT@Zdp0Zh7l@lKEKnwxVSGX4xolLRffv@vv146i8 "Python 2 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 61 bytes Input is taken as a byte-string \$ s \$. ``` lambda s:sum(b''[c-65]-4for c in s) ``` [Try it online!](https://tio.run/##NY9ra8IwFIbZrAr5Fflm@0Gx3gaCgyzLumBzjjStgs4PtVYUvGErY7@@60VDCM97zvueJNe/dH8597Pd5Cc7hqfNNqTJOLmfzE2rbtSM52o2XvLz1ajVm4bRaK2i9mi4bg92lxuN6OFMEyv73R@OMbXHhEZhEtNJXr7eU9PqJNfjITVbdPJOWxahYZLEt5TuzMK26q478Tm6bGPTsuikCKVVw15bGcdPUcTaA@Kg@1Vin2gWcPFgznxdYo8oRCjRJoCgRb4fchnwqfA@hOcUhS7Rvifhwfybua4Ap/T2CDDpFlRM9kDOWakGhKOauVIJ8Cu9YPMyMSQBTAEXUAnFlmV5RJRcLgUopn3Fyqb9RmYgAoWAget7TEnuoeY4k1xLV3Kco8sZIEeQqOXjV/kgBswRz5vtXv4U0FxioEHoymX3/wE "Python 3 – Try It Online") We use a lookup table, where each element maps to the *sharpness* of a given letter. Note the `-4`, to display the negative *sharpness*. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~61~~ 60 bytes ``` M|W N# N|Z ## O S- S -- T`VAUC`##- +`\w|-#|#- ^(-)?.* $1$.& ``` [Try it online!](https://tio.run/##HY7BSgQxEETv9RtZZVWy4BdIG9sYNule0skMDCLjwYMXDyJ4mX8fg1CHR1FV1PfHz@fX@351jOtethniINsC56AwD4P3aOtEPazOedytr7@bd9tAvB39zcPpFof7w@l634M@MaLmZ9hIMwI1Q1EViIrxEJYezlwfuUZYq0kiwgvlzBIZQimPTpU00QAtl5wKS8NME6PLWXQWFFoYJS0LSyFrhQQX4V5UtOdWqaRQ1YJeUrCUU9BJcyDRoJLU0jhEQpH/h4dnIWk3YbM/ "Retina 0.8.2 – Try It Online") Link includes test cases. Edit: Saved 1 byte thanks to @mathjunkie. Explanation: ``` M|W N# N|Z ## O S- S -- T`VAUC`##- ``` Turn sharp letters into the appropriate number of `#` (sharp... geddit? any non-word non-magic non-`-` character would have worked) signs and dull letters into the appropriate number of `-` (because they have negative sharpness) signs. ``` +`\w|-#|#- ``` Delete other letters and all matching pairs of `#` and `-` signs. ``` ^(-)?.* $1$.& ``` Output the number of signs remaining, prefixed by the first one if it's a `-`. Since the regex matches a zero-length string, I have to ensure it only matches once. [Answer] # [Javascript (Node.js)](https://nodejs.org/), 115 bytes ``` let s=0;for(let b='w'+w,c=a=>Math.ceil(10*3**(4/~'OSCUAVNZMW'.indexOf(a[0])))-4||-1;b=b.slice(1);s+=9>c(b)?c(b):0); ``` [Try it online!](https://tio.run/##HZBRa8JAEITf71fkQcid1lSpL63Ecj2v6WFuV3KJQtqCMcaaEoyYUAtq/7qNwjIMA7N8zHfyk1TpPt/V3W25yi5pua1qa47B2FiutRA4lsRD/5UYHglJBA8N0YhAAMHI5kgciYkMXmTgERMGCjwi3rjvS/AkAa78phOAmvHGoJ76SksIyZzPJIlgAjgHonksiVZxLEFzE2oOZAoy0ggY@WHAtRIBGoFTJYzylcAZ@oIDCgSFRjVAHLgnb4@bzAiFkQFpzMKpdkVeU/tjazPirMu9TNINPVjuyDpeiqy2Krc3bGJ69UvXPtidw13qJu5IJ/XGSbO8oP1e@6HdpoP7P7uBiPgMYj23nXy7yn5xTZP33idjrDs4nbr94dJdOlWRpxnts2HVcR9HKV2y56s89djwNm9ZZE5RftFF63g4X1Fax@q8YOTMLv8) This puts all the characters in a string, 'OSCUAVNZMW', and uses a formula to map the character index to the "sharpness" of each letter. The formula is: \$f\left(x\right)=ceil\left(10\cdot3^{\frac{4}{x}}-4\right)\$ Where \$f(x)\$ is the sharpness, and \$x\$ is the negative index of the character + 1. Sounds convoluted, but there's a reason: the index is modified to make Javascript's `string.indexOf()` return 0 instead of -1. This formula does result in 0 instead of -1 for U. However, using Javascript's `||` functionality in variable assignment, we can just default zero values to -1 instead. Also, this is my first code golf, advice appreciated! [Answer] # [Java (JDK)](http://jdk.java.net/), 56 bytes ``` s->s.map(c->("XXAVNZMWOOSSCU".indexOf(c)/2+3)%7-3).sum() ``` [Try it online!](https://tio.run/##bU5da9swFH3PrxCBgL01HqwPg3YLqJrqiVr3BstOiksfNCfunMUfWHJoGf3tmuLtZaygi@49595zzkGf9PKw@@nqpu8GSw5@jkZbH6N317P/sGpsS1t37ZukscNeN2eqPGpjiNR1S37NCOnH78e6JMZq679TV@9I47lA2aFunx4eiR6eTDitEpJ1orW3f30@@15NsitSkS/OLFcmanQflMtVML@/pxso5BZRKZbPo7rd7Z@xCsrww8f3l@Hi0/IyjMzYBKG7nrSrbiDBSQ/E7o29@seWEPVi7L6JutFGvc9lq2C@MFdksVu084vp4oJUke774ws1PldwhqLyhx5MEIbhH4fX2blenWP4lbsYk1unaM64YzRTTiKCAwTF/XNFzu54esPT2KksFRA79o0mCYeYO6Ai8TcpiA31Dcp1IiSHzG3phrsc7gC34CQtuJOiKDhIqjJJwa2B5xIB8yRLqRQsRcVwLZgSiWC4wYRRQIYgUAkfiAKN@STsMcUE5gq4Ur8B "Java (JDK) – Try It Online") [Answer] # [Javascript (Babel Node)](https://developer.mozilla.org/en-US/docs/Web/JavaScript), 131 bytes ``` d=>(s=0,[...d].map(c=>{s+=/[AV]/.test(c)?1:(/[NZ]/.test(c)?2:(/[MW]/.test(c)?3:(/[CU]/.test(c)?-1:(c=='S'?-2:(c=='O'?-3:0)))))}),s) ``` [Try it online!](https://tio.run/##TctBC4IwGMbxj@NGOUtvwhQZHQa6V1waJB7W1CgspUmX6LOb0sXn9OcHz129ldGv2zDaF3VpOvvZ183U0qmmATJ0ty0JIXVFHmpAmgYfs6FOGRWVQ8bGjEjjcO8jpxTnlbiLJKeVeIuwfCX2fNOUWtIKbfefMKfn7/CyL94aPOn@afquIV1/RS2yUnHIExCQx8csSjjLQDJIOZM85gwKiFkkgIHgILm0MJ5@) This is my first code golfing. I hope I'm doing it right. I'll be glad to get some js golfing tips (before exploring new golfing languages) and overall golfing tips. [Answer] ## Javascript (ES6), 65 characters ``` x=>x.map(l=>s-=~(z='RosLucyEvanzmw'.indexOf(l))?~(z/2)+4:0,s=0)|s ``` ## Javascript (ES6), 67 characters ``` x=>x.reduce((s,l)=>~(z='RosLucyEvanzmw'.indexOf(l))?s-~(z/2)-4:s,0) ``` Takes an array of lowercase characters as input. [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~20~~ 19 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ô≈X╙R┤╠Φyf∙H¡»₧ßc≡╡ ``` [Run and debug it](https://staxlang.xyz/#p=93f758d352b4cce87966f948adaf9ee163f0b5&i=%22CODE%22%0A%22GOLF%22%0A%22SAUCE%22%0A%22CATS%22%0A%22MOON%22%0A%22NONSENSE%22%0A%22ZUCKERBERG%22%0A%22STRING%22%0A%22CHALLENGE%22%0A%22NAIL%22%0A%22CARNIVAL%22%0A%22COMPLIMENT%22%0A%22WAVE%22%0A%22UNKNOWN%22%0A%22MAZE%22&a=1&m=2) [Answer] # [Keg](https://github.com/JonoCode9374/Keg), 42 bytes ``` ?⑷¦A1|V1|N2|Z2|M3|W3|C1±|U1±|S2±|O3±║_0™⑸⅀ ``` Unfortunately, TIO doesn't have the latest version of the interpreter on its servers, so y'all can't try it online. Quite literally, this maps over each character in the input, assigns it a value based on the sharpness table, and sums the stack. [Answer] # [Zsh](https://www.zsh.org/), 73 bytes ``` a=(O S CU : AV NZ MW) for c (${(s[])1})(((x=a[(I)*$c*])&&(r+=x-4))) <<<$r ``` [Try it online!](https://tio.run/##HY/BagJBEETv/RVzWGTG4CGQU9BDp9PZDM50y/bOCiseRJTcAq4HSci3b1ahDkXBK6p@hq/x7IOH4XR1i9t4WHl15qi4V4edk97lbYDz98Udna9@/bDbh@e/4L2/rQ47H8O8Os73YTbzl6fVbfESQoDlclldxgAP7Hoars4DkL4z1Jo@wLAQA2FrkFUFRMV4EvSF1ty8cVODtU2UGugTU2KpGQRjmphGYoeT0bxJMbO0sMWOochadCuQsWfIse9ZMlqbUWAjXLKKltQ2mCM1aqSbSBZTJO00EYqSSlSL0yAUrPlRPGVGUYsJmwHc77jq/mb8Bw "Zsh – Try It Online") Get the last `(I)`ndex of the glob `*$char*` (with `(I)`, it is zero if not found). If it is non-zero, add to `$r`. [Answer] # [Perl 5](https://www.perl.org/) `-p`, 48 bytes ``` $_=y/AV//+2*y/NZ//+3*y/MW//-y/CUSO//-y/SO//-y;O; ``` [Try it online!](https://tio.run/##Lcw9C8IwEAbgPb@ig5NSov1wkQoxxlqa3EnSD@ji5CAUW9Slf97YpoWDe97j7vrHu42tXd2TgbKK0k2wHig0I8IRqqbUHygvDTrM7YAHazmehZccPT8iKcqLY0gMK7lYzFlhHAOiEMFxRwDBiLGW2JQ8F/okdDoNtsQUOoPF/MqkFJC63YAAy@Sk6bOGrGIuRYSjuslMCSjmXLPKXcSkhBywhjko1rjx/tf132f3@li/b/8 "Perl 5 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~25~~ 24 bytes ``` IΣES⁻÷⌕AVNZMWι²÷⌕UCSSOι² ``` [Try it online!](https://tio.run/##VY3BCoMwEER/RTxtwX5BT7K0sJBkxa0WegsW2kBMRWN/Pw16aecwMDMPZnjZeXhbn1IzuxAB7RJB1hG0nYDCtEaJeXjCoSq0C@sCjc92ceEBZW10WRUuT3vu77ct5@KHQuE/qtuZTaf8a86dZsOdura1JmxZkBtCIUXIPSusDSMbYiFJx4//Ag "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 1 byte by porting @ovs' answer. Explanation: ``` S Input string E Map over characters ι Current character ⌕ Find position in AVNZMW Literal string `AVNZMW` ÷ ² Integer divide by literal `2` ⁻ Minus ι Current character ⌕ Find position in UCSSO Literal string `UCSSO` ÷ ² Integer divide by literal `2` Σ Take the sum I Cast to string Implicitly print ``` The halved `Find` results in one less than the sharpness/dullness, but the other find returns `-1` in that case, thus correcting the value. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~39~~ ~~38~~ ~~36~~ ~~34~~ ~~33~~ 28 bytes ``` lε.•3и½:∍äaŠ•sk>4%„ݧuyåi(]O ``` [Try it online!](https://tio.run/##AUMAvP9vc2FiaWX//2zOtS7igKIz0LjCvTriiI3DpGHFoOKAonNrPjQl4oCew53Cp3V5w6VpKF1P//9DT05TQ0lPVVNORVNT "05AB1E – Try It Online") or [Verify all test cases (as arranged by @sporeball)](https://tio.run/##LY6xSgNBEIZfJSwIFtEmVhYJ42Q9h@zOHLu3FzhJEcEiKFgEhSsCKW18BEVE8QkEG5sctuIz3Iucu4cw8P//x8/M3KyXF6vLju7qiRocjAdqUk@765@Pw3b7Mvr93H0dt/cPzevy@zmC9dX4aK/dPjWPu/fbunlb7W820g27c4Uy1WqoMjGnUTwETBGh8FGsCEdhYa/jRFsFnGl3ol2W2oUjTgbPwBjNWWowkOk3OKYSeis2N2Q1FzHMoUytwDOWeVpuoUrAUlVptuALCwnnrIMVlmAKB5bQiUfJCT0ZQinFILCgMImn/lVgyPT/kcg9kgTP2nu1@AM) *-5 thanks to @Kevin* ## Explained ``` Original: lε.•3и½:∍äaŠ•sk>4%„ݧuyåi(]O Uncompressed: lε"anm vzw cso u"sk>4%"cosu"yåi(]O l | Take the implicit input and lowercase it. ε | Map the following to this input to find the sharpness of each letter: "anm vzw cso u" | Push the string "anm vzw cso u", representing the sharpness of each | letter. They are arranged in a way such the index of the character | is retrivable via mathematical caluclation. | sk | Swap this string, and the mapping item, and find the index of the | item within the big string | >4% | Increment the value, and then modulo 4 it in order to find the "raw" | sharpness of the string. The result will be in the range [0, 3] | "cosu" | Now comes the part where we determine if the sharpness needs to be | negated or not. First, we push a string containing all letters that | have negative sharpness | yå | We now push the letter being mapped, and test to see if it is in the | aforementioned string | i(] | If it is in the string, negate the sharpness value. After that, | close the if-statement and the loop | O | Summate the stack and implicitly output the total sharpness. ``` ## [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes ``` .•7ùZ9£nDн•#εXlSk>}O®β ``` [Try it online!](https://tio.run/##LU49SwNBEP0rYW2jrdgkjJPxHLI7c@zsXsKJhYKFKFoIQgrB36K9hWBhYRP74G/wj5y7hzDwPni8N/cPF5fXVwM/buZusj@buPkmDwe/zy@H35/90fb1bvHzVdTe7mN9azezJ92@7d6H6XDmUBfkpq5Rf1LAIGOVCMkKBFUpICpG5QrtMy4pHlNsajpFlkrwFLwnaWpCgP3YEIU7GKmG1nMgSUWsoKupLEvRVS0P0FcjcN@TBLAUoNqtUA4qmn2KEBijGmrLaOwZtVOPIIoqrMbjqyDQ0P9I8Q1ZswmZufM/ "05AB1E – Try It Online") A port of the Jelly answer suggested by @Kevin. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 28 bytes ``` J"MNA CSOWZV U"sm-3%xJd7@#JQ ``` [Try it online!](https://tio.run/##K6gsyfj/30vJ189RwTnYPzwqTCFUqThX11i1wivF3EHZK/D/fyVn/zBPFyUA "Pyth – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 70 bytes ``` ->s{'OAVNZMWCUS'.chars.zip(1226655440.digits).sum{s.count(_1)*(_2-3)}} ``` [Try it online!](https://tio.run/##TZBNT4NAEIbv/RV7A0zZtBS4oVnXFUlh1vCZQDjUmipNlaaUgwK/nbIGIslcnicz70zmUr/99AerV@@rRuIkhtRLaBRIeP@5u1T4tzjLa00zTcPQ9RV@Lz6Ka6Xgqv5q2mJ5bCu8L@vvq1wod/JR3Shd159RtkAokyh/YtISqXq@/GObu8@CNyMHJKJsLigJA8HayB7nIHg9MnAI2FBzl0Z0y/xH5tuDXU3Joe/AXNAX4roMbDE6pQNx3AH/l/vgxESo6WDKvVfX8RiEM5mQWKQYI0awBZ7AzHgkFQ1mvsjx7nR6QA0aPoXKFh2yIkeWhUrU9Tc "Ruby – Try It Online") (3 bytes longer because TIO doesn't suppoort ruby 2.7 `_1` syntax) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~88~~ 87 bytes Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` char*t="O_S_CU__AVNZMW",*i;v;f(char*s){for(v=0;*s;v+=i?i-t-6>>1:0)i=index(t,*s++);v=v;} ``` [Try it online!](https://tio.run/##TVFta9swEP6eX3EYAnZss6RpOzbPGZqmZaKWFCw7ASchFNfZbFhaImPCQn57JskpDO64t@fuHunK8FdZXq/l7@fjqI0dsZM7nO92aMkLtnKCUR110d61ZeWd969Ht4vH0UhFnR/XX@uwDR9ns8nnsVfH9eGlOrltMFK@70Vd3EWX65/n@uB65wH0CyrVqvU2PjtYfCdOAM5cJD@MlSjHNoFRJo1lQnBjueCSaDF@keMnkn4j6dy2ZCnl1sM/UZIQPrcgjmjSD0o5XaLeF2yRUEZ4ZqIVWlpkzp@4WNktDBU2xWhREM6QzBgyhQGAs@AkZ4KLPMlSxChOhcRiQbGkCcViKRKMuMCCUyFpTx1xNCfv23RFYipyyYmUziUaQH1ooTq9VWVrviK8DyCc3vRO66TXsRWd0Pl7Kw9WHgOYfDRQ41j81Ay1/wvH9RZiODubE7nbnD5hrQ@GxH/x1HLQhwTXEGn0NaGBL6Dqv9Xr3rUn8j7cIjvVi8D3Gw/0FS13pVfcgOtm6@lp8HbUhb3rDHVtBsMXGKrNwQneMYEKNDUVx7dnN1vbdhlcrv8A "C (gcc) – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/) + GNU utilities, ~~100~~ \$\cdots\$ ~~92~~ 91 bytes ``` sed 's/[AV]/+1/g s/[NZ]/+2/g s/[MW]/+3/g s/[CU]/-1/g s/S/-2/g s/O/-3/g s/[A-Z]//g'<<<0$1|bc ``` [Try it online!](https://tio.run/##LY9BS8NAEIXv@RVzKESRsFaPFmFcx7h0d6ZkswlEerBN0/aSQKt4UH97XBqHOXy8eW@Y2byfD2P32W8/jkMP3dU1fI/nXQvpWb1htVY3c7VPInMT@W5iV0e@n1iHtcomj1fZZBCV/U8xizG1TxeLxe1s/rPZjr9JN5zgazi1cOxByzNBLvYFPAZNoLH04EQYWNhTbGiCXlLxREUOviwM56Bf0VrinIDR2Jgp2FQYQdzKGkdcQo0VQeAlS83gsCFwpmmIHfrSIcOKKThhCbYs0BldiNeyMtoba7RUYjWyaGEj3sSDkDGny@KoeW0keCbvH6AdEoi12x4GyHqYXf5Ks0dIL3o3KUk79LvxDw "Bash – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 205 bytes ``` int u(String s){if(s.length()>0){int n=0;switch(s.charAt(0)){case'M':case'W':n++;case'N':case'Z':n++;case'A':case'V':n+=4;case'O':n--;case'S':n--;case'C':case'U':n--;}return n+u(s.substring(1));}return 0;} ``` [Try it online!](https://tio.run/##TY9fb4IwFMWf8VPc8CINk7BkTxJNOsacEcoi/klc9oCIisNqaNEshM/u2oKLCeGe/u7p6b2H@BL3TueUHjY/t3O5zrMEkjxmDII4o1B1OlpLGY@5KJdTtoGj6BkRLzK6@/qGuNgxpKyausRgADS9qgQDOQL/W3nKuGxXoLvhm6c/gT4K/XdZIzx3FXDxLJI1CEMiKwlJ5IlP6tXcnXjTV286Uldm0zFRyv3Avu@RkTCJ5zRNJ3jsN2FTMl7gRofBpz8OPDKTpyVeqMg5mZBwqV4K8MrToXbkJttTAe2KamroN8MjmR/9Mp4erVPJrbNw8JwaymOCDoOh@JnArFIxhGRc3bkJG5T3RIaqbGswK0/pju8NNLQFEAY6sB12zXiyF81kHxeYGzZCVRKztBt0@6ouu31qmo7SpGWrB4ZbtpBs8NLAUBx6vUZHD9ptzfOG1UXKy4ICNUsxASvXTA1sPIs97j3bqW/17Q8 "Java (OpenJDK 8) – Try It Online") [Answer] # T-SQL, 133 bytes Added some line changes to make it readable ``` SELECT SUM(iif('P'=type,nullif(substring( translate(@,'AVNZMWCUSO','4455662210'), number,1),substring(@,number,1))-3,0)) FROM spt_values ``` **[Try it online](https://data.stackexchange.com/stackoverflow/query/1246790/determine-the-sharpness-of-a-word)** [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 49 bytes ``` D,k,@,"MCNSAO_WUZ_V"$€=12Rz€¦*bM-1+4*7%3$_ L,€kBs ``` [Try it online!](https://tio.run/##bZHBSsNAEIbP9ilCqJeagklrCxbF6XaNS3dnyk42hVxKS29VKHhTvPgwnnwKH8UXiWkSITEuC7t8/zD/zr/b/f54zPNFcAjuAt8IZKDN2mWb1O9/v3/ehJF9Kc6vj8HODMOL8WB6Pupvejoo4GH@nOvr4PVx@7Tbb73wrdfr1/fo1he0kP7ZzBuOmzQmfV/SUZMyOCG7WEDCJY2a1BBhScMmRUKWxfa9jpQ5sZR2Lm1cipct58Qq/IeLB9BaYlz1a/kjKF3SP2@1qFKolHE7CLPSykhMutoa0srhqkkdLpHW2BUMZFX5pBW1UVkm0QAnBopoTmvmhdNmyQqlM4TkdGLBKGGJBa2UYKWVoJS0ACRBqIgVVxlGk7Y1QizrKX4tovacyEKRY5TMddHpK0b5Dw "Add++ – Try It Online") An implementation of [xnor's formula](https://codegolf.stackexchange.com/a/205536/66833), go upvote that. ## How it works The second line defines the main function which runs the helper function `k` over `€`ach character in the input, then sums the result. `k` works as follows: ``` D,k,@,"MCNSAO_WUZ_V"$€=12Rz€¦*bM-1+4*7%3$_ ; Monadic function, takes a single character **s** ; and returns the sharpness of **s** ; For example, **s** = 'C' STACK = ['C'] "MCNSAO_WUZ_V" ; Push this string STACK = ['C' 'MCNSAO_WUZ_V'] $€= ; Check each character for equality with **s** STACK = [[0 1 0 0 0 0 0 0 0 0 0 0]] 12R ; Push [1 2 3 4 5 6 7 8 9 10 11 12] STACK = [[0 1 0 0 0 0 0 0 0 0 0 0] [1 2 3 4 5 6 7 8 9 10 11 12]] z ; Zip arrays STACK = [[[0 1] [1 2] [0 3] [0 4] [0 5] [0 6] [0 7] [0 8] [0 9] [0 10] [0 11] [0 12]]] €¦* ; Product of each STACK = [[0 2 0 0 0 0 0 0 0 0 0 0]] bM ; Maximum (call the result **r**) STACK = [2] -1+4*7%3$_ ; Push 3 - ((**r** - 1) * 4 % 7) STACK = [-1] ``` [Answer] # [Perl 5](https://www.perl.org/) + `-pF`, 39 bytes ``` $\+=y/OSUBANMCBVZW/0-62-6/&&$_-3for@F}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lRtu2Ut8/ONTJ0c/X2SksKlzfQNfMSNdMX01NJV7XOC2/yMGttvr//wA/11Bffz//UJ@QIEdfT@cg/2Bn/wBP52BPH09n/zB/H2dHP39nfz9P/2DP4H/5BSWZ@XnF/3UL3AA "Perl 5 – Try It Online") ## Explanation For each character in the input (stored in `@F` via `-F`) we add to `$\` (defaults to `''`, implicitly output as the last argument for calls to `print`, which is triggered as part of `-p`) the value of `$_-3`, if we have `tr`anslated (`y///` is a synonym for `tr///`) any char in `$_` (the current char taken from `for@F`) using `OSUBANM` to `0-6` and `CBVZW` to `2-6`. [Answer] # SimpleTemplate, 118 bytes Yes, not short at all. :( My language has absolutely no way what-so-ever of creating an array with keys and values defined, so, everything has to be generated. ``` {@setA 1,1,2,2,3,3,-1,-1,-2,-3}{@setL"AVNZMWCUSO"}{@eachL}{@setA.[_]A.[__]}{@/}{@eachargv.0}{@incbyA.[_]R}{@/}{@echoR} ``` This simply outputs the sharpness of the word. --- **Ungolfed** The code above is just a mess! Here's a readable version: ``` {@set rates 1,1,2,2,3,3,-1,-1,-2,-3} {@set letters "AVNZMWCUSO"} {@each letters as letter key i} {@set rates.[letter] rates.[i]} {@/} {@set result 0} {@each argv.0 as char} {@inc by rates.[char] result} {@/} {@echo result} ``` Should be fairly easy to understand. The `{@inc by rates.[char] result}` will increment the `result` by `rates.[char]` (similar to `result += rates[char]` on other languages). --- You can try this on <http://sandbox.onlinephpfunctions.com/code/54adfe0b61fe1a12f3be085d0e058123a7842627> There you have the golfed version, ungolfed and a function implementation (the `{@echo result}` is replaced with `{@return result}`). ]
[Question] [ ## Background Consider a sequence defined as follows: * The first element is 0; * The second element is 4; * From the third element onwards, its value can be calculated by: + Taking the set of integers from 0 up to the previous element of the sequence (inclusive or exclusive, it doesn't matter); + Removing any integers that have already appeared earlier in the sequence from the set; + Adding together the remaining elements of the set; that's the value you want. Interestingly, this sequence doesn't seem to be on [OEIS](http://oeis.org/) yet. ## The task Write a program or function which takes an integer *n* as input, and outputs the *n*th element of the sequence. ## Test cases The first few elements of the sequence are: * 0 * 4 * 6 (1+2+3) * 11 (1+2+3+5) * 45 (1+2+3+5+7+8+9+10) * 969 (1+2+3+5+7…10+12…44) * 468930 (1+2+3+5+7…10+12…44+46…968) ## Clarifications * Your program should in theory be able to handle arbitrary *n* if run on a variant of your language that has unboundedly large integers and access to an unlimited amount of memory. (Languages without bignums are unlikely to be able to get much beyond 468930, but that's no excuse to hardcode the answers.) * You may choose either 0-based or 1-based indexing for the sequence (e.g. it's up to you whether *n*=1 returns the first element, *n*=2 the second element, and so on; or whether *n*=0 returns the first element, *n*=1 the second element, and so on). * There are no requirements on the algorithm you use, nor on its efficiency; you may implement the definition of the sequence directly (even though it's really inefficient), and you may also implement a different algorithm which leads to the same results. ## Victory condition This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest correct program, measured in bytes, wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ ~~12~~ 9 bytes ``` rSạo4¥ð@¡ ``` Uses 0-based indexing. [Try it online!](https://tio.run/nexus/jelly#@18U/HDXwnyTQ0sPb3A4tPD/fzMA "Jelly – TIO Nexus") ### How it works ``` rSạo4¥ð@¡ Main link. No arguments. Implicit argument: 0 ð Collect everything to the left into a chain and start a new, dyadic one. The arity of the first chain is unknown at this point, as it isn't prefixed by ø, µ, or ð. @ Swap the arguments of the first chain. Swapping arguments is only implemented for dyadic links, so this makes the chain dyadic. ¡ Read an integer n from STDIN and execute the chain n times. Taking the argument swap into account, the chain is executed first with 0 as left and right argument, then with the previous right argument as left argument and the previous return value as right argument. The return value of the last call is the return value of the quicklink and becomes the implicit output. Let's call the left argument x and the right argument y. r Range; yield [x, ..., y]. S Compute the sum of all integers in the range. ¥ Convert the two atoms to the left into a dyadic chain, and call that chain with arguments x and y. o4 Take the logical OR of x and 4, replacing a 0 with 4 and leaving positive integers untouched. ạ Take the absolute difference of the sum to the left and the result of the logical OR to the right. ``` [Answer] # Python, ~~66~~ 60 bytes Thanks to @Dennis for shaving off 6 bytes! ``` f=lambda n:n>2and(f(n-1)-~f(n-2))*(f(n-1)-f(n-2))/2or(5-n)*n ``` It's not the golfiest piece of code ever, but it uses a formula that I made: [![enter image description here](https://i.stack.imgur.com/Zd9uR.png)](https://i.stack.imgur.com/Zd9uR.png) Where `x` on the right-hand side is `f(n - 1)`, and `y` is `f(n - 2)`. ## Explanation: The sum of continuous integers from `a` to `b` (inclusive) can be described by this formula: ``` amount * average ``` Where `amount` (amount of numbers) is described like so: ``` ((a - b) - 1) ``` And `average` (the average of all numbers) is described like so: ``` (a + b) / 2 ``` So the full formula is now: ``` ((a - b) - 1)(a + b) / 2 = (a - b - 1)(a + b) / 2 ``` The way we implement this formula into the final formula is to substitute `a` for `f(n - 1)`, `b` for `f(n - 2)`, which basically calculates the sum of all of the new terms, and add another `f(n - 1)` (which is now `a`) on, which is the sum of all previous terms. Combining that together, we get: ``` a + ((a - b - 1)(a + b) / 2) = a + ((a^2 + ab - ab - b^2 - a - b) / 2) = a + ((a^2 - b^2 - a - b) / 2) = (a^2 - b^2 - a - b + 2a) / 2 = (a^2 - b^2 + a - b) / 2 = ((a + b)(a - b) + (a - b)) / 2 = (a + b + 1)(a - b) / 2 ``` Replace `a` with `x` and `b` with `y`, and hey presto, you have to formula above. [Answer] # [Python 2](https://docs.python.org/2/), ~~58~~ ~~54~~ 50 bytes ``` r=t=0 exec'r,t=t+r*~-r/2or 4,t-r;'*input() print r ``` [Try it online!](https://tio.run/nexus/python2#JY5BCsIwEADP2VfspWxbE6zSUyX@JSZRArotywqe/HqMep9hJq4po0ciquLVT5BfOZJY9bqT8e1kf1wFZ6tOTjQW3p7aD7BJYUWpTQO4NoCxMErgW@4P07CA@RPUJXRnwg7ZgvnZLXYPj0sKCzKYbw1je6gf "Python 2 – TIO Nexus") [Answer] # Mathematica, ~~49~~ 48 bytes ``` ±2=4;±1=0;±n_:=Tr@Range@±(n-1)-Tr@Array[±#&,n-1] (* or *) ±2=4;±1=0;±n_:=-Tr@Array[(k=±#)&,n-1]+Tr@Range@k ``` Uses CP-1252 encoding. Defines function `PlusMinus (±)`. 1-indexed. # Explanation ``` ±2=4;±1=0;±n_:=Tr@Range@±(n-1)-Tr@Array[±#&,n-1] ±2=4;±1=0; (* Define ±1 and ±2 *) ±n_:= (* ±n equals ... *) Tr@Range@±(n-1) (* Sum of (1, 2, ..., ±(n-1)) ... *) -Tr@Array[±#&,n-1] (* Minus the sum of previous terms *) ``` [Answer] # [Oasis](https://github.com/Adriandmen/Oasis), 11 bytes ### Code: ``` +>bc-*2/640 ``` ### Explanation: To visualize the relation of **fn**, let's take the example **f5**. To calculate **f5**, let's take a look at the following sum: **1 + 2 + 3 + 5** + 7 + 8 + 9 + 10 The bold part is just the same as **f4**. The **7 + 8 + 9 + 10** part is the range **[fn-2 + 1, fn-1 - 1]**. That makes the formula **fn-1 + Σ [fn-2 + 1 ... fn-1 - 1]** ([Wolfram link](https://www.wolframalpha.com/input/?i=f(n-1)+%2B+sum+n%3D(f(n-2)%2B1)+to+(f(n-1)-1)+n)): **fn = 0.5 × (fn-12 - fn-22 + fn-1 - fn-2)** Which can be rewritten to: **fn = 0.5 × ((fn-1 - fn-2)(fn-1 + fn-2) + (fn-1 - fn-2))** **fn = 0.5 × ((fn-1 - fn-2)(fn-1 + fn-2 + 1))** Which is the formula that we will be using in the code: ### Code explanation The `640` part gives us the base cases: ``` a(0) = 0 a(1) = 4 a(2) = 6 ``` The code that will be executed (which defines **a(n)**): ``` +>bc-*2/ + # Add a(n + 1) and a(n + 2) implicitly > # Add one to get a(n + 1) + a(n + 2) + 1 b # Push a(n + 1) c # Push a(n + 2) - # Subtract from each other * # Multiply with the previous result 2/ # Halve the result ``` [Try it online!](https://tio.run/nexus/oasis#@69tl5Ssq2Wkb2Zi8P//fxMA "Oasis – TIO Nexus") [Answer] # Julia, ~~39~~ ~~33~~ 32 bytes ``` !n=n<3?5n-n^2:sum(!(n-2)+1:!~-n) ``` 0-based. Thanks to @Dennis, saved 6 bytes. Thanks to @GlenO, saved a byte. [Try it online!](https://tio.run/nexus/julia5#@6@YZ5tnY2xvmqebF2dkVVyaq6GokadrpKltaKVYp5un@b@gKDOvJCdPQ9FA8z8A "Julia 0.5 – TIO Nexus") Previous answer 1- based: ``` !n=n<4?2(n>1)n:sum(!(n-2)+1:!~-n) ``` [Try it online!](https://tio.run/nexus/julia5#@6@YZ5tnY2JvpJFnZ6iZZ1VcmquhqJGna6SpbWilWKebp/m/oCgzryQnT0PRXPM/AA "Julia 0.5 – TIO Nexus") Previous ungolfed answer 1-based : ``` f(n)=n<4?n<2?0:n*2:sum(f(n-2)+1:f(n-1)) ``` [Try it online!](https://tio.run/nexus/julia5#@5@mkadpm2djYp9nY2RvYJWnZWRVXJqrARTWNdLUNrQCMQw1Nf8XFGXmleTkASXMgTwA "Julia 0.5 – TIO Nexus") [Answer] ## JavaScript (ES6), 47 bytes ``` f=(n,b=4,a=6)=>n?--n?f(n,a,(a+b+1)*(a-b)/2):b:0 ``` Uses the recurrence relation that `f(n) = sum(range(f(n-2) + 1, f(n-1) + 1))` for n > 2. [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), ~~84~~ ~~89~~ ~~88~~ 87 bytes ``` $OFS='+' for($a=0,4;$a.Count-le($n="$args")){$a+=("$(1..$a[-1])"|iex)-("$a"|iex)}$a[$n] ``` [Try it online!](https://tio.run/nexus/powershell#@6/i7xZsq66tzpWWX6ShkmhroGNirZKo55xfmleim5OqoZJnq6SSWJRerKSpWa2SqG2roaSiYainp5IYrWsYq6lUk5laoakLFEyEMGuBEip5sf///zcDAA "PowerShell – TIO Nexus") ### Explanation 0-based indexing. Only works through `n = 6` (on my Windows machine it crashes with a stack overflow for `n = 7`). Using the same method as [JungHwan Min's answer](https://codegolf.stackexchange.com/a/110533/30402) (sum of the range minus sum of previous terms). Summing a range/array in PowerShell is long, so I'm using a trick of joining a n array with `+` to create a long expression (like `1+2+3+4...etc`) and then sending it through `iex` (`Invoke-Expression`). Since I need to do it twice, instead of using `-join` I'm setting the special variable `$OFS`, which stands for output field separator. When you stringify an array, this is the character used to the join the elements; it default to a space. So by setting it to `+` (once), I can replace something like `$a-join'+'|iex` with `"$a"|iex`. A simple `for` loop keeps going until the sequence count is less than or equal to the input integer, then I return the `$n`th element. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~17~~ 16 bytes ``` OKi:"tP:yX-sv]G) ``` `1`-based indexing is used. The code is very inefficient. For `n = 6` it already exceeds the memory limit of the online compiler. [Try it online!](https://tio.run/nexus/matl#@@/vnWmlVBJgVRmhW1wW6675/78pAA) ### How it works ``` O % Push 0 K % Push 4 i % Input n :" % Do the following n times t % Push a copy of the top array (or number) P: % Range from 1 to the last element of array y % Push a copy of the second-top number/array X- % Set difference s % Sum v % Concatenate everything into a column vector ] % End G) % Get n-th entry of the array. Implicity display ``` --- For **20 bytes**, the following version avoids the memory limitation. But there's still the data type limitation (`double` type can only guarantee that integers are accurately represented up to `2^53`), so results are valid up to `n = 8` only. ``` OKi:"t0)tQ*2/ys-v]G) ``` [Try it online](https://tio.run/nexus/matl#@@/vnWmlVGKgWRKoZaRfWaxbFuuu@f@/OQA) too! [Answer] # [Haskell](https://www.haskell.org/), 42 bytes ``` f 0=0 f 1=4 f 2=6 f n=sum[1+f(n-2)..f$n-1] ``` [Try it online!](https://tio.run/nexus/haskell#@5@mYGBrwJWmYGhrAiSNbM2AZJ5tcWlutKF2mkaerpGmnl6aSp6uYez/3MTMPAVbhYKizLwSBRWF3MQChTSFaAM9PfPY/wA "Haskell – TIO Nexus") This directly implements the recurrence that for `n>2`, `f(n)` equals `f(n-1)` plus the sum of the open interval from `f(n-2)` to `f(n-1)` which again is equal to the sum of the half-open interval from `f(n-2)` to `f(n-1)` inclusive. ``` f(0) = 0 f(1) = 4 f(2) = 6 = 1+2+3 f(3) = 11 = 1+2+3+5 = 6 + 5 = 6 + sum]4,6[ = f(2)+ sum]f(1),f(2)[ = sum]f(1),f(2)] ... f(n) = sum]f(n-2),f(n-1)] = sum[f(n-2)+1,f(n-1)] ``` [Answer] ## Haskell, 31 bytes ``` m#s=m:s#sum[m+1..s] ((0:4#6)!!) ``` Usage example: `((0:4#6)!!) 6` -> `468930`. [Try it online!](https://tio.run/nexus/haskell#@5@rXGyba1WsXFyaG52rbainVxzLlWaroWFgZaJspqmoqKnwPzcxM0/BVqGgKDOvREFFIU3B7D8A "Haskell – TIO Nexus"). Simple recursion, that keeps track of the maximum element `m` so far and the next value `s`. [Answer] ## JavaScript, ~~123~~ 119 bytes ``` (a,i=x=y=0)=>{r=[0,4];while(r.length<a){x++;y=0;for(i=0;i<r[x];i++){if(!r.includes(i)){y+=i;}}r.push(y)}return r[a-1];} ``` [Try it online!](https://repl.it/FpG2/2) This solution is 1-based, `f(1) => 0`. [Answer] # [Perl 6](https://perl6.org), ~~52 49 44~~ 35 bytes ``` {(|(0,4 X 0),{[+](^.[0])-.[1],.[0]+.[1]}...*)[$_;0]} ``` [Try it](https://tio.run/nexus/perl6#fVBBTsMwELz7FSsV0Zh1LLt1TaKoiEdwQEoDihIjKkoSkaQiCkG8hofxB86pnaoCLlx2Z3Zn7N1tawN7zbOItBbdmLqJyHMH51mZG1iPvffmCabgFgRlfYyJd8djkVCfxzJhDqJDA@f8gsZn95FIhtH6rxv7EqzBIwCC2aBc0Axm4Elc4JJaKuUPx5WrqNXvCl5igCFK4VqhDv/2vj4@pUC5sFmpyayDcCn@EaHSNoc6oIRGhFS7tACcJrXsoXw5Ts2f9uBfwWZbVG3DYGNeK5M1Jofe/rGt/dyYateBO5A3aSiDk4bB@wlGZCB12sF8BlKAD3N2tNhtxu@i9LM0ezQH "Perl 6 – TIO Nexus") ``` {(0,(4,0),{[+](^.[0])-.[1],.[0]+.[1]}...*)[$_;0]} ``` [Try it](https://tio.run/nexus/perl6#fVBBTsMwELz7FSsVUZt1LLt1TaKoiEdwS1NUJUZUlCQiSUUUBfEaHsYfOAc7VQVcuOzO7M7Yu9vWFo5GZDFpHbqzdROT5w4uszK3sB57KjnVXDLeJ5jSrUhkygKRqJR7iB4NQogrllzcxzIdRme@bdwzsAZKACR3QftgOMyAKlzgkjmq1A/Hla/o1e8KXmOIESrpW5GJ/vY@3z@URLVwWevJbMJoKf8RoTYuRyZkhMWEVIddAThN6thD@XKaWjwdIbiBzb6o2obDxr5WNmtsDr37Y18HubXVoQN/HTppGIezhsPbGcZkIPWug/kMlIQA5vxkcduMX0UZZLvs0X4D "Perl 6 – TIO Nexus") ``` {(0,(4,0),{[+](^.[0])-.[1],.sum}...*)[$_;0]} ``` [Try it](https://tio.run/nexus/perl6#fVDNToNAEL7vU0xSY3edZbPbblcIqfEhvFE0BLaxsQUi0EgIxqfxwXwHz7jQNOqll5n5Zr5v/prKwtGINCSNix5sVYfk0MJ1WmQW1kNHJaeaS8a7CGP6KCIZM09EKuaiag69EOKGRVdPoYz7wenua9cB1kAJgOTO6NEYDjOgChe4ZA4q9YtxNWb06m8Gb9HHAJUcS4EJ/te@Pj6VRLVwXutJbPxgKS@QUBvnA@MzwkJCyn2SA06bOrQtXk9bi5cjeHew2eVlU3PY2LfSprXNoHMzdpWXWVvuWxgfQycO43DmcHg/hyHpSZW0MJ@BkuDBnJ8k7prhOy@8NEmf7Q8 "Perl 6 – TIO Nexus") ``` {(0,4,6,{[+] $^a^..$^b}...*)[$_]} ``` [Try it](https://tio.run/nexus/perl6#fVDLToNAFN3PV5ykxIIzTGba6QghNX6Eu7YYhDE2ViACjYRg/Bo/zH9wjQNNo27c3HvPPefkPprK4Kh5GpHGVremqiPy3OIiLTKD9dC5gimmWbehOzhxEnPuxPc95/zS2zh3u36w4pva2rCGSwDBbFBj0AwzuJIu6NKzUMofTFdjR61@d@gVDWhIpRipUId/uc/3DymoXNis1GTWQbgU/4io0jaHOvCIFxFSHpIcdNrUoofi5bQ1fzrCv8Z2n5dNzbA1r6VJa5OhszP2lZ8ZUx5ajN9wJ43HcNYwvJ3LiPSkSlrMZ5ACPubsZLHXDF954adJ@mi@AQ "Perl 6 – TIO Nexus") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 ( # generate a sequence 0, 4, 6, # seed the sequence { # lambda with placeholder parameters 「$a」 「$b」 [+] # reduce with 「&infix:<+>」 $^a # n-2 ^.. # Range that excludes the first value $^b # n-1 } ... # keep generating values until * # never stop )[ $_ ] # get the value that was asked for (0 based index) } ``` [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), ~~77~~ 73 bytes ``` param($n)$a=0,4;1..$n|%{$a+=(0..$a[-1]|?{$_-notin$a})-join'+'|iex};$a[$n] ``` [Try it online!](https://tio.run/nexus/powershell#@1@QWJSYq6GSp6mSaGugY2JtqKenklejWq2SqG2rYQDkJEbrGsbW2FerxOvm5Zdk5qkk1mrqZuVn5qlrq9dkplbUWgOVqOTF/v//3wAA "PowerShell – TIO Nexus") Implements the algorithm as defined, and is 0-indexed. Input of `6` is too much for TIO to handle. Sets `$a` to be an array `[0,4]`. Loops from `1` up to input `$n`. In the loop, we take the range of numbers from `0` up to the biggest number we have `$a[-1]`, and use a `Where-Object` clause `|?{...}` to pull out only those numbers that are not already present. That array of numbers is `-join`ed together with `+`s, and then fed to `iex` (short for `Invoke-Expression` and similar to `eval`). That value is then array-concatenated onto the end of `$a`. Finally, we exit our loop, and take the `$n`th number in our array. That number is left on the pipeline, and output is implicit. [Answer] # [Python 2](https://docs.python.org/2/), 85 bytes ``` def g(n): if n<2:return n*4 s=set(map(g,range(n)));return sum(set(range(max(s)))-s) ``` [Try it online!](https://tio.run/nexus/python2#Lc0xCsMwDEDRPafQKIV2CYGAkx7GENtosBIkG3p718WZ34ffzhAhoZCbgCPIsTgNpaqAzOsE9rFQMPsb00u9pNBLov1JrGb8@5Dsv2hd30YtXgoMLDBoI3crS@knpvYD "Python 2 – TIO Nexus") [Answer] ## Batch, 108 bytes ``` @if %1==0 echo 0&exit/b @set/ab=4,a=6 @for /l %%i in (2,1,%1)do @set/ac=(a+b+1)*(a-b)/2,b=a,a=c @echo %b% ``` Port of my JavaScript answer. [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 47 bytes ``` ?d1-scd/4*dd[d1+*2/r-dsn+dlnlc1-dsc0<x]sxlc0<xp ``` Works with integers as large as you want, up to the memory capacity of the computer. [Try it online!](https://tio.run/nexus/dc#@2@fYqhbnJyib6KVkhKdYqitZaRfpJtSnKedkpOXk2wIZCYb2FTEFlfkgOiC///NAA "dc – TIO Nexus") 0-based indexing, input on stdin, output on stdout. (There's also output on stderr, which is to be ignored.) Sample runs: ``` $ for ((j=0;j<12;j++)){ echo -n "$j ";dc -f sumseq.dc <<<"$j";echo;} 2>/dev/null 0 0 1 4 2 6 3 11 4 45 5 969 6 468930 7 109947436950 8 6044219445882138462810 9 18266294354989892462984673364511343859409730 10 166828754731567805766174036610844675771635260155825966927845486666328\ 837158267993261860 11 139159167026428037700805570917048711514125048327321592278500415852500\ 422178720517080334552793040951056255170819719745908378102737875659900\ 61575545777065220385544711322919415 ``` This uses the same algorithm as the following solution in bash, which is (a little) more readable: # Pure bash, 60 bytes ``` for((n=s=$1?4:0,k=1;k<$1;k++,s+=(n=n++*n/2-s))){ :;} echo $n ``` But the bash program only works for inputs up to 7, since it hits integer overflow beyond that. [Answer] # Pyth - 15 bytes ``` ePu+Gs-UeGGQ,Z4 ``` [Test Suite](http://pyth.herokuapp.com/?code=ePu%2BGs-UeGGQ%2CZ4&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5&debug=0). [Answer] # C# - 74 bytes ``` int A(int f){int e=4,i=1,s=0;for(;i++<f;)e=e*-~e/2-(s+=e);return f>0?e:0;} ``` Ungolfed: ``` int A(int f) { int e = 4, i = 1, s = 0; // e is the last element, s is the sum of all previous elements for (; i++ < f; ) // calculate for indexes 1 through max (don't need the index, just a correct number of loop cycles) e = e * -~e / 2 - (s += e); // -~e => (e + 1), higher precedence to remove parentheses return f > 0 ? e : 0; //handle input 0 as a special case, which is 0 } ``` There is probably a way to convert this to a lambda to save even more, or something using the .Aggregate Function. Although currently I have no imports, so maybe it evens out? [Answer] # [><>](https://esolangs.org/wiki/Fish), 43+3 = 46 bytes Makes use of the formula presented in [Adnan's](https://codegolf.stackexchange.com/a/110557/41020) and [Qwerp-Derp's](https://codegolf.stackexchange.com/a/110555/41020) answers. ``` :2(?^&46v }v?=&:&l<,2*{-$@:}+1+@:{:: *>n;>4 ``` Expects the input to be present on the stack, so +3 bytes for the `-v` flag. [Try it online!](https://tio.run/nexus/fish#@29lpGEfp2ZiVsZVW2Zvq2allmOjY6RVraviYFWrbajtYFVtZcWlZZdnbWfy//9/3TIFMwA "><> – TIO Nexus") [Answer] # [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ╟s╒π4╬╪♀○¢fΦå┼ ``` [Run and debug it](https://staxlang.xyz/#p=c773d5e334ced80c099b66e886c5&i=3) 0-indexed. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 14 bytes ``` 04"?(Dtɽ$F∑J)i ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIwNFwiPyhEdMm9JEbiiJFKKWkiLCIiLCIyIl0=) ]
[Question] [ Write a quine... from which every other character can be removed it still be a valid quine. You can specify whether to start removing characters at the first or second character. Scoring criteria (add bonuses/penatly percentages together for total percentage): * Answers must be at least 4 characters long * Program must contain at least one alphabetical character in its source, so for example, `12345!@#$%^&*()` is disqualified * +750% if the language used is not Turing-complete (I'm looking at you, HTML!) * -15% if the solution does not read its source from anywhere in any form * -20% if you can also keep only every 5th character and still form a quine The score is measured by the number of characters in the first program. Example (not real programs): If `123456789abcdef` and `13579bdf` are both quines, the score is 15. Additionally, if `159d` is also a quine, then the final score is 12. This is code-golf, so lowest score wins. [Answer] ## PHP, 4 chars − 15% − 20% = ~~2.72~~ 2.6 points ``` ABCD ``` Yes, PHP is a Turing-complete language. Nobody said I have to *use* any of its actual programming features. ;-) **Edit:** Changed the score based on the clarification that bonuses are additive, not multiplicative. [Answer] ## TI BASIC 4 - 35% = 2.6 *I might understand them wrong, but I think I am also eligible for the -15% and the -20% bonusses, meaning I have the lowest possible score.* I can write the program: ``` 123i ``` which will output `123i` where i is of course the imaginary unit. When you remove the 1st and the 3rd character all that remains is `2i` which outputs `2i` [Answer] # Python - 95 Great challenge. I thought this was pretty clever, and actually a legit solution! ``` 00;"#";print(open(__file__).read()) 0#;XpXrXiXnXtX(XoXpXeXnX(X_X_XfXiXlXeX_X_X)X.XrXeXaXdX(X)X) ``` [Answer] ## Golfscript, 5 points ``` {hai} ``` is a function that, when executed, will run the (non-existing) function `hai`. It's not executed, however, but rather printed when the program ends - including the outer brackets. Removing each other character yields: ``` {a} ``` Lame, I know :-) [Answer] ## HQ9+ - 4 \* 7.5 \* 0.8 = 24 points ``` Q+++ ``` Still a quine with every second character: ``` Q+ ``` ...and every fifth: ``` Q ``` Sorry, I couldn't resist. :) [Answer] # HTML/Markdown, 4\*7.5 = 30 ``` HHHH ``` I admit this is lame, but it doesn't really go against any rule in the question. Except that HTML/Markdown may not be considered a real programming language. [Answer] # !/bin/sh I liked [qwr's solution](https://codegolf.stackexchange.com/questions/23306/mandoline-quine#23311) so much, I shamelessly made a port for POSIX shell. Please don't save it into a filename containing spaces. ``` : '#';cat $0 #c a t $ 0 ``` Start removing at character number 1, and count newlines as characters. The second quine is of course: ``` #;a 0 cat $0 ``` *Please upvote qwr's answer instead of this one!* [Answer] # Bash, 23 Newline is a character! Some messy comment work, so that when every other character starting from the first is removed, the comment becomes code and the code becomes a comment: ``` #cRaRtR R$R0R R# cat $0 ``` After every other character (*including the new line*) is removed: ``` cat $0 #ct$ ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes -15% = 6.8 ``` ` I,` I, ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJgIEksYCBJLCIsIiIsIiJd) ## Every other char ``` `I`I ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJgSWBJIiwiIiwiIl0=) ## Explanation : ``` ` I,` # push ` I,` I # quote and prepend , # print `I` # push `I` I # quote and prepend # implicit output ``` [Answer] ## Brainf\*\*k, 37 - 15% = 31.45 Abusing the [Portable Brainfuck Interpreter](http://www.linusakesson.net/programming/brainfuck/pbi.c) ``` +A[B-C<D+E]F-GÿH<I<J<K<L<M<N<O[P.Q>R] ``` Start removing from the second character. [Answer] # [Python 3](https://docs.python.org/3/), ~~145~~ 94 bytes -15% : Score = 79.9 ``` s ="'psr=i%nrt;(p'rsi n=t%(rs;%e%xse)c;(xsc[s11:::2 2']; p)r'i%nst)(#s#%#s#)";exec(s[1:: 2] ) ``` [Try it online!](https://tio.run/##dY0xCsMwDEX3nEIoGFuFQONuMe5FgifX0CyukTykp3fdhkKXDgLp6z9eedb7I19afNySZ0RsAh51EfabylydKZplg@yrMixOJbVLoujMLnGVeV6WxQJYHRwUYt0hqWRGGVUfQpf2FI2svQc2ALWu6Mc0h2EovOVq3mZyx47@ijR8kCP@lnDCkz3TL7N2cfgDHr/2Ag "Python 3 – Try It Online") ## every other char: ``` s='s=%r;print(s%%s);xcs1:2 ';print(s%s);xcs1:2 ``` [Try it online!](https://tio.run/##K6gsycjPM/6fnJ@SalukpKT0v9hWvdhWtci6oCgzr0SjWFW1WNO6IrnY0MpIQR0uiBD7D9QTbWilaxjLxQWRBRmlCVWppKukZWSgyZVakZoMkfgPAA "Python 3 – Try It Online") ## How it works : The ugly string is the blending of : * `print('s =%r;exec(s[1::2 ] )'%s)####` for the normal quine * `'s=%r;print(s%%s);xcs1:2 ';print(s%s)` for the every-other-char quine `xcs1:2` is an annotation and doesn't throw any error as the part after the semicolumn can compile. Otherwise it would throw a `SyntaxError` and the program wouldn't run at all. # [Python 3](https://docs.python.org/3/), with reading code source: ~~70~~ 62 bytes ``` s ="p-r-i-n-t-(-*-o-p-e-n-(-_-_-f-i-l-e-_-_-)-)";exec(s[::2] ) ``` [Try it online!](https://tio.run/##jY7BCsIwEETP7leEPWWFBVtvKf2SUkTaLQZqEtII@vUxbU@CguxlZgfmTXilm3fnPPhR2oiIeVEtBo5s2XFizUf2HFiK03wpN5VkLn7VxISNPGXQS2dM3SvKpaKrDFc9wCiT8kGcnuws7noXMnCIkh7RKZsk6m6l9gQQonVJr46aXSPjsT4RbOXfgj/bt1mfiO31k7OnAPkN "Python 3 – Try It Online") ## every other char: ``` s=print(*open(__file__));xcs:2 ``` [Try it online!](https://tio.run/##JYxBCsMgEEXXnVOIKycQaNKdIScJQYqZUKEdZWIhPb2tdfcf//HSJz8i34qPG82itS7HnCRwNl1MxMa5PTzJOcTp9IcdVfk5y2D7YQXYaFd/qzp8fxFauAjlt7AKmcQsNbsiQEtWwqlt3etuvCLQSb4dUL4 "Python 3 – Try It Online") [Answer] # HQ9+T, - 4 \* 0.8 = 3.2 points ``` qqqq ``` It's a valid quine (ish) and a quine every second and fifth char. I couldn't resist . . . . ]
[Question] [ The goal of this challenge is the write the shortest function/program to take input text, encrypt it using the method below, and return the result. As an example, I will use the string `hello world`. **First**, get the input text. ``` hello world ``` **Second**, convert the string into ternary (base 3). Use this key: ``` a = 000 b = 001 c = 002 d = 010 e = 011 f = 012 g = 020 ... w = 211 x = 212 y = 220 z = 221 [space] = 222 ``` With this key, `hello world` becomes `021011102102112222211112122102010`, as seen below. ``` h e l l o w o r l d 021 011 102 102 112 222 211 112 122 102 010 ``` **Third**, move the first digit to the end. ``` 021011102102112222211112122102010 becomes 210111021021122222111121221020100 ``` **Fourth**, convert the number back into a string using the same key. ``` 210 111 021 021 122 222 111 121 221 020 100 v n h h r n q z g j ``` **Lastly**, return the encrypted text. ``` vnhhr nqzgj ``` Here are some sample text and their output: `the turtle ==> dvo fh ego` `python ==> uudwqn` `code golf ==> hpjoytqgp` As this is code golf, the shortest entry in *bytes* wins. Errors are allowed if some of the characters are not lowercase letters or space. This is my first challenge, so any suggestions would be more than helpful. Good luck! **Leaderboard:** ``` var QUESTION_ID=54643;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 getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/; ``` ``` 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, ~~23~~ 22 bytes ``` sXc.<sXz=+GdJ^UK3K1KJG ``` Try it online: [Regular Input](http://pyth.herokuapp.com/?code=sXc.%3CsXz%3D%2BGdJ%5EUK3K1KJG&input=programming+puzzles+and+code+golf&test_suite_input=hello+world%0Athe+turtle%0Apython%0Acode+golf&debug=0) / [Test Suite](http://pyth.herokuapp.com/?code=sXc.%3CsXz%3D%2BGdJ%5EUK3K1KJG&input=programming+puzzles+and+code+golf&test_suite=1&test_suite_input=hello+world%0Athe+turtle%0Apython%0Acode+golf&debug=0) Thanks to @isaacg for one byte. ### Explanation: ``` sXc.<sXz=+GdJ^UK3K1KJG =+Gd append a space the G (preinitialized with the alphabet) K3 assign 3 to K J^UK K assign all 3-digit ternary numbers [[0,0,0], [0,0,1],...,[2,2,2]] to J Xz G J translate input from G to J s sum (join all ternary numbers to one big list) .< 1 rotate by 1 c K split into lists of size 3 X JG translate from J to G s join chars to string and print ``` [Answer] # Pyth, 26 bytes ``` J+Gds@LJiR3c.<s.DR9xLJz1 2 ``` Try it online in the Pyth Compiler/Executor: [demo](https://pyth.herokuapp.com/?code=J%2BGds%40LJiR3c.%3Cs.DR9xLJz1+2&input=programming+puzzles+and+code+golf&test_suite_input=hello+world%0Athe+turtle%0Apython%0Acode+golf&debug=0) | [test cases](https://pyth.herokuapp.com/?code=J%2BGds%40LJiR3c.%3Cs.DR9xLJz1+2&input=programming+puzzles+and+code+golf&test_suite=1&test_suite_input=hello+world%0Athe+turtle%0Apython%0Acode+golf&debug=0) ### Idea Assume all input characters have already been mapped to the integers that step 2 specifies. For every 3-digit ternary number, we have that **xyz3 = 9x + 3y + z**, so modular division by **9** yields quotient **x** and residue **3y + z**. If the input is **abc3 def3 ghi3**, applying modular division to each yields **a, 3b + c, d, 3e + f, g, 3h + i**. After rotating the list from above one unit to the left, we can group the integers into pairs. This yields the list **(3b + c, d), (3e + f, g), (3h + i, a)**. Now, if we convert **(3y + z, w)** from base 3 to integer, we obtain **3(3y + z) + w = 9y + 3z + w = zyw3**. Thus, applying base conversion to the list of pairs gives us **bcd3 efg3 hia3**, which is precisely the result of rotating the concatenated ternary digits one unit to the left. All that's left to do is mapping the resulting integers back to characters. ### Code ``` J+Gd Concatenate "a...z" (G) with " " (d) and save in J. L z For each character in the input(z): x J Compute its index in J. R For each index I: .D 9 Compute (I / 9, I % 9). s Concatenate the resulting pairs. .< 1 Rotate the resulting list one unit to the left. c 2 Split it back into pairs. R For each pair: i 3 Perform conversion from base 3 to integer. L For each resulting integer: @ J Select the element of J at that index. s Concatenate the resulting characters. ``` [Answer] # Python 2, 96 ``` s=input() r=y='' for c in s+s[0]:x=(ord(c)-97)%91;r+=y and chr((y%9*3+x/9-26)%91+32);y=x print r ``` Converts a character `c` to a value `x` as `x=(ord(c)-97)%91`, with the modulo affecting only space to convert it to 26. The reverse conversion is `i` to `chr((i-26)%91+32)`, with the modulo only affecting `i=26` to make it become spaces. We loop through the characters, noting the current value `x` and the previous value `y`. We use the last two ternary digits of `y`, found as `y%9`, and the first ternary digit of `x`, found as `x/9`. The value of the concatenation is `y%9*3+x/9`. There's probably some optimizations combining this arithmetic with the shifting by `97` and fixing of space. We make this loop around, we return to the first character of the string at the end. We also do one preparation loop to write in a previous value `y`, suppressing the character for the first loop when `y` has not yet been initialized. [Answer] # CJam, ~~39~~ 29 bytes The cool thing about this one is that it doesn't even use base conversion. ``` q'{,97>S+:XZZm*:Yere_(+3/YXer ``` [Try it online](http://cjam.aditsu.net/#code=q'%7B%2C97%3ES%2B%3AXZZm*%3AYere_(%2B3%2FYXer&input=hello%20world). I just realized I had exactly the same idea as Jakube's Pyth answer. I actually ported this CJam code to Pyth before seeing his post, ending up with 25 bytes. Given it was my first Pyth golf I guess it's not too bad. # Explanation ``` e# Z = 3 q e# Push input string '{, e# Push ['\0' ... 'z'] 97> e# Keep ['a' ... 'z'] S+ e# Append space :X e# Assign "a...z " to X ZZm* e# Push 3rd cartesian power of [0 1 2] e# i.e. all 3-digit permutations of 0, 1, 2 e# (in lexicographical order) :Y e# Assign those permutations to Y er e# Translate input from X to Y e_ e# Flatten resulting 2D array (+ e# Rotate first element to the end 3/ e# Split back into 3-digit elements YXer e# Translate from Y to X ``` [Answer] # CJam, ~~30~~ ~~29~~ 27 bytes ``` q'{,97>S+:Af#9fmd(+2/3fbAf= ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q'%7B%2C97%3ES%2B%3AAf%239fmd(%2B2%2F3fbAf%3D&input=hello%20world). The approach is the same as in [my other answer](https://codegolf.stackexchange.com/a/54670), which is a port of this code to Pyth. ### How it works ``` q e# Read from STDIN. '{, e# Push ['\0' ... 'z']. 97> e# Remove the first 97 elements (['\0' - '`']). S+:A e# Append a space and save in A. f# e# Find the index of each input character in A. 9fmd e# Apply modular division by 9 to each index. (+ e# Shift out the first quotient and append it. 2/ e# Split into pairs. 3fb e# Convert each pair from base 3 to integer. Af= e# Select the corresponding elements from A. ``` [Answer] # Pyth, ~~30~~ 29 bytes ``` K+Gdsm@Kid3c.<sm.[Z3jxKd3z1 3 ``` Saved 1 byte thanks to @Jakube. [Live demo and test cases.](https://pyth.herokuapp.com/?code=K%2BGdsm%40Kid3c.%3Csm.%5BZ3jxKd3z1+3&input=python&test_suite=1&test_suite_input=hello+world%0Athe+turtle%0Apython%0Acode+golf&debug=1) [Answer] # Javascript (ES6), 175 bytes A one-liner! "Overuse of variable `v` award, anyone?" update: Now ***only*** uses variables called `v`, for total confusion! *Thanks @vihan for saving 6 bytes!* *Thanks @Neil for saving 27 bytes!!* ``` v=>(([...v].map(v=>(v<"V"?53:v.charCodeAt()-70).toString(3).slice(1)).join``)+v[0]).slice(1).match(/..?.?/g).map(v=>(v=String.fromCharCode(parseInt(v,3)+97))>"z"?" ":v).join`` ``` Defines an anonymous function. To use, add `v=` before the code to give the function a name, and call it like `alert(v("hello world"))` [Answer] # Julia, ~~149~~ 137 bytes My first golf! ``` s->(j=join;b=j([base(3,i==' '?26:i-'a',3)for i=s]);r=b[2:end]*b[1:1];j([i==26?" ":i+'a'for i=[parseint(r[i:i+2],3)for i=1:3:length(r)]])) ``` (partially) ungolfed: ``` f = s -> ( # join the ternary represenations: b = join([base(3, i == ' ' ? 26 : i - 'a',3) for i = s]); # rotate: r = b[2:end] * b[1:1]; # calculate the new numbers: n = [parseint(r[i:i+2],3) for i = 1:3:length(r)]; # convert back to characters: join([i == 26 ? " " : 'a' + i for i = n]) ) assert(f("hello world") == "vnhhr nqzgj") assert(f("the turtle") == "dvo fh ego") assert(f("python") == "uudwqn") assert(f("code golf") == "hpjoytqgp") ``` [Answer] # Javascript (ES6), ~~178~~, ~~172~~, 170 ``` p=>{p=p.replace(' ','{');c="";l=p.length;for(i=0;i<l;){c+=String.fromCharCode(((p.charCodeAt(i)-97)%9)*3+(((p.charCodeAt((++i)%l)-97)/9)|0)+97)}return c.replace('{',' ')} ``` Replaced Math.floor with a bitwise or. Created an anonymous function. If I'm understanding correctly, this should fix my noobishness somewhat (thanks Dennis!) and get me another 2 bytes down. [Answer] # Julia, ~~169~~ 166 bytes ``` s->(J=join;t=J(circshift(split(J([lpad(i<'a'?"222":base(3,int(i)-97),3,0)for i=s]),""),-1));J([c[j:j+2]=="222"?' ':char(parseint(c[j:j+2],3)+97)for j=1:3:length(t)])) ``` Ungolfed + explanation: ``` function f(s::String) # Convert the input into a string in base 3, with space mapping to 222 b = join([lpad(i < 'a' ? "222" : base(3, int(i) - 97), 3, 0) for i = s]) # Split that into a vector of single digits and shift once p = circshift(split(b, ""), -1) # Join the shifted array back into a string t = join(p) # Convert groups of 3 back into characters c = [t[j:j+2] == "222" ? ' ' : char(parseint(t[j:j+2], 3) + 97) for j = 1:3:length(t)] # Return the joined string join(c) end ``` [Answer] # Haskell, 160 bytes ``` a!k|Just v<-lookup k a=v x=['a'..'z']++" " y="012";z=mapM id[y,y,y] m(a:u:r:i:s)=[u,r,i]:m(a:s) m[e,a,t]=[[a,t,e]] main=interact$map(zip z x!).m.(>>=(zip x z!)) ``` Ugh, this feels way too lengthy, but at least I'm... beating Python somehow. And Ruby. [Answer] # Javascript (ES6), ~~141~~ ~~124~~ 120 bytes Believe it or not.... :-) ``` (t,i=0,c=w=>(t.charCodeAt(w)-123)%91+26)=>String.fromCharCode(...[...t].map(k=>(c(i)%9*3+c(++i%t.length)/9+65|0)%91+32)) ``` As with my other answer, this is an anonymous function, and needs to be assigned to a variable before it can be used. Try it here: ``` e=(t,i=0,c=w=>(t.charCodeAt(w)-123)%91+26)=>String.fromCharCode(...[...t].map(k=>(c(i)%9*3+c(++i%t.length)/9+65|0)%91+32)); input=document.getElementById("input"); p=document.getElementById("a"); input.addEventListener("keydown", function(){ setTimeout(function(){p.innerHTML = e(input.value);},10); }) ``` ``` <form>Type your text here: <input type="text" id="input" value="hello world"/><br> Only space and lowercase letters are allowed.</form> <h3>Output:</h3> <p id="a">vnhhr nqzgj</p> ``` I thought I might be able to shave a couple bytes off my previous answer by using a different technique, so I started out with one similar to Tekgno's and golfed my head off from there. I initialized some variables in the function's argument section, and again stuffed everything into a `.map` function. Then I realized the `String.fromCharCode` would be much more efficient outside the `.map`. After all was said and done, I had shaved off **more than ~~30~~ 45 bytes!** **Edit 1:** Saved 17 bytes by getting rid of the `.replace`s, using a technique similar to xnor's Python solution. OK, maybe it's time to move onto another challenge.... [Answer] # Python 2, ~~182~~ 180 Bytes This solution is not ideal, due to the replace being very costly.. Trying to figure out how to avoid that. ``` b=lambda k:k and b(k/3)*10+k%3 s=''.join('%03d'%b(ord(x)-6-91*(x>' '))for x in input()) print`[chr(int((s[1:]+s[0])[i:i+3],3)+97)for i in range(0,len(s),3)]`[2::5].replace('{',' ') ``` Input is like `"hello world"`. [Answer] # Mathematica, 162 bytes ``` r=Append[#->IntegerDigits[LetterNumber@#-1,3]~PadLeft~3&/@Alphabet[]," "->{2,2,2}];StringJoin[Partition[RotateLeft[Characters@#/.r//Flatten,1],3]/.(#2->#1&@@@r)]& ``` (Re)Using a `Rule` to convert the digit lists to characters and back. [Answer] # Javascript (ES6), 179 bytes ``` s=>[...s+s[0]].map(q=>`00${(q<'a'?26:q.charCodeAt(0)-97).toString(3)}`.slice(-3)).join``.slice(1,-2).match(/..?.?/g).map(q=>q>221?' ':String.fromCharCode(parseInt(q,3)+97)).join`` ``` Props to vihan for the `.match` regex. [Answer] # Ruby, 177 Needs at least Ruby 1.9 for the `each_char` method ``` l=[*('a'..'z'),' '];n=(0..26).map{|m|m=m.to_s(3).rjust 3,'0'};s='';gets.chomp.each_char{|x|s+=n[l.index x]};puts("#{s[1..-1]}#{s[0]}".scan(/.../).map{|i|i=l[n.index i]}.join '') ``` [Answer] ## Java, 458 449 bytes It made me a little sad to determine that I could shave off 10 bytes by not using Java 8 streams and the `map()` method. Here is the golfed version: ``` import org.apache.commons.lang.ArrayUtils;class A{public static void main(String[]a){int b=0;String[] c=new String[27];for(;b<27;++b)c[b]=String.format("%03d",Integer.valueOf(Integer.toString(b,3)));String d=a[0],e="abcdefghijklmnopqrstuvwxyz ",f="",g="";for(b=0;b<d.length();++b)f+=c[e.indexOf(d.substring(b,b+1))];f=f.substring(1)+f.charAt(0);for(b=0;b<f.length();b+=3)g+=e.charAt(ArrayUtils.indexOf(c,f.substring(b,b+3)));System.out.println(g);}} ``` Here is a much less golfed version. It is intended to be readable, but I make no guarantees. ``` import org.apache.commons.lang.ArrayUtils; class A { public static void main(String[] a) { int b=0; String[] c = new String[27]; for (; b < 27; ++b) c[b] = String.format("%03d", Integer.valueOf(Integer.toString(b, 3))); String d = a[0], e = "abcdefghijklmnopqrstuvwxyz ", f = "", g = ""; for (b = 0; b < d.length(); ++b) f += c[e.indexOf(d.substring(b, b + 1))]; f = f.substring(1) + f.charAt(0); for (b = 0; b < f.length(); b += 3) g += e.charAt(ArrayUtils.indexOf(c, f.substring(b, b + 3))); System.out.println(g); } } ``` This program takes the string to convert as a command-line argument. If you want to have spaces in your input, you have to surround it with double quotes. I wanted to provide an example of using this from the command line, but I was unable to get this code to work outside of Eclipse. I never learned to use Java from the command line ^\_^; You can probably get this running inside the IDE of your choice without too much trouble. [Answer] # Javascript (ES6), ~~181~~ 180 bytes ``` t=>((x=[...t].map(k=>`00${(k<'!'?26:k.charCodeAt(0)-97).toString(3)}`.slice(-3)).join``).slice(1)+x[0]).match(/.../g).map(j=>j>221?' ':String.fromCharCode(parseInt(j,3)+97)).join`` ``` This is an anonymous function, so it needs to be given a name before it can be used. (E.g. `encrypt=t=>...`) Try it out here: ``` e=t=>((x=[...t].map(k=>`00${(k<'!'?26:k.charCodeAt(0)-97).toString(3)}`.slice(-3)).join``).slice(1)+x[0]).match(/.../g).map(j=>j>221?' ':String.fromCharCode(parseInt(j,3)+97)).join``; input=document.getElementById("input"); p=document.getElementById("a"); input.addEventListener("keydown", function(){ setTimeout(function(){p.innerHTML = e(input.value);},10); }) ``` ``` <form>Type your text here: <input type="text" id="input" value="hello world"/><br> Only space and lowercase letters are allowed.</form> <h3>Output:</h3> <p id="a">vnhhr nqzgj</p> ``` I started out using multiple variables and `for` loops instead of `.map`. I then golfed it in every possible way without changing the algorithm, which put me somewhere around 217 bytes. After taking a look at UndefinedFunction's answer, I managed to get it down to 195, and some inspection of Dendrobium's answer resulted in another 14 golfed off. As far as I'm aware, I can't go any further or my result would be practically identical to Dendrobium's (except for being one character shorter!). Can anyone find the place where I saved one char? :-) As usual, suggestions are gladly welcome! [Answer] ## Matlab, 113 bytes ``` x=dec2base(strrep(input('','s'),' ','{')-97,3)';strrep(char(base2dec(reshape(x([2:end 1]),3,[])',3)+97)','{',' ') ``` Input is through stdin. Example: ``` >> x=dec2base(strrep(input('','s'),' ','{')-97,3)';strrep(char(base2dec(reshape(x([2:end 1]),3,[])',3)+97)','{',' ') hello world ans = vnhhr nqzgj ``` [Answer] # Julia - ~~92~~ ~~87~~ ~~61~~ 54 bytes ``` s->join(32+(3(i=[s...]%91+579)%27+i[[2:end,1]]÷9)%91) ``` Ungolfed: ``` function f(s) t=[s...]; # Convert the string into a char array # i=t%91+579 # Mod 91 drops the alpha characters to sit just # below space, then 579 is added as a trick, # equivalent to subtracting 6 and adding 9*65 v1=3i%27 # This shifts the bottom two ternary digits up # and removes the first ternary digit v2=i[[2:end,1]÷9 # This shifts the first ternary digit down and # removes the bottom two ternary digits. [2:end,1] # rotates the array to put the first value at the end N=(v1+v2)%91+32 # this combines the ternary digits, then returns # the values to the correct ASCII values j=join(N) # join the char array back to a string return j end ``` The trick may confuse you. Subtracting 6 moves 'a' down to zero after the mod. Adding 9\*65 is equivalent to adding 65 to v1+v2, which is part of the process of restoring the values to their ascii values. You could replace `i=t%91+579` with `i=t%91-6`, and then replace `N=(v1+v2)%91+32` with `N=(v1+v2+65)%91+32` to get the same result, but it requires one extra character. ]
[Question] [ Your challenge is to make a program or function that outputs the [GCD](https://en.wikipedia.org/wiki/Greatest_common_divisor) of its inputs in one language and the [LCM](https://en.wikipedia.org/wiki/Least_common_multiple) of its inputs in another. Builtins for GCD or LCM (I'm looking at you, Mathematica) are allowed but not encouraged. There will be 2 inputs, which will always be positive integers, never greater than 1000. ## Test Cases Each line is one test case in the format `x y => GCD(x,y) LCM(x,y)`: ``` 1 1 => 1 1 1 2 => 1 2 4 1 => 1 4 3 4 => 1 12 7 5 => 1 35 18 15 => 3 90 23 23 => 23 23 999 1000 => 1 999000 1000 999 => 1 999000 1000 1000 => 1000 1000 ``` [See this pastebin](https://pastebin.com/iGbuQkz3) for all possible inputs with `0 < x, y < 31`. Note that different versions of the same languages count as different languages. [Answer] # C / C++, ~~79~~ ~~78~~ 73 bytes *Thanks to @ETHproductions for saving a byte!* ``` int f(int a,int b){int c,d=a*b;for(;a;b=c)c=a,a=b%a;auto e=.5;c=e?d/b:b;} ``` C calculates the GCD: [Try it online!](https://tio.run/nexus/c-gcc#FY3BCoMwEETv@YogBLJlsUgrFJfFH@llNzHgobGIPYnfniZzeDMMDFPWfNjkGwUbFc5mASPLTSltuych5QCBBYXVCcnv2OzC/UiBlznedVK6Spt9ZM0ezGls1XevVfKdi@/sYof154H2CS0ML7TDCEDmKn8) C++ calculates the LCM: [Try it online!](https://tio.run/nexus/cpp-gcc#JY3NCsMgEITvPsWSUtAiLaENFFfbF@ll/QkIjUJiTiHPbiOdwzfDHGZqTAVG3kiy0YqtmZPe0MXimGeOhNY44QxJMvZMSGvJEMx1QGfC29@ssrjXU0zuu/oAOualzIGmF2tTE8XEBdsYHFqKV8rltYDWx@9dwkO02H1S96/6p4R@EMj2@gM) In C, `auto e=.5` declares an integer variable with the auto storage class (which is the default), which is then initialized to 0, whereas in C++11 it declares a double, which is initialized to 0.5. So the variable's value will be truthy in C++ and falsy in C. The function calculates the GCD with Euclid's algorithm, and the LCM by dividing the product of a and b by the GCD. Omitting the return statement works at least on GCC. The 78 byte solution below should work with any compiler: ``` int f(int a,int b){int c,d=a*b;for(;a;b=c)c=a,a=b%a;auto e=.5;return e?d/b:b;} ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly) / [Actually](https://github.com/Mego/Seriously), 2 bytes ``` 00000000: 1e 67 .g ``` This is a hexdump (xxd) of the submitted program. It cannot be tested online because TIO doesn't support the CP437 encoding. @Mego was kind enough to verify that this works on Cygwin, which implements CP437 as intended for Actually. ## Jelly: GCD Jelly uses the [Jelly code page](https://github.com/DennisMitchell/jelly/wiki/Code-page), so it sees the following characters. ``` œg ``` [Try it online!](https://tio.run/nexus/jelly#@390cvr///9N/huaAAA "Jelly – TIO Nexus") ### How it works `œ` is an incomplete token and thus ignored. `g` is the GCD built-in. ## Actually: LCM Actually uses [CP 437](https://en.wikipedia.org/wiki/Code_page_437#Character_set), so it sees the following characters. ``` ▲g ``` [Try it online!](https://tio.run/nexus/actually#@/9o2qb0///NuAxNAA "Actually – TIO Nexus") ### How it works `▲` is the LCM input. Since `g` (GCD) requires *two* integer inputs, it isn't executed. [Answer] # [Actually](https://github.com/Mego/Seriously) / [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` 00000000: 11 1c 67 ..g ``` This is a hexdump (xxd) of the submitted program. [Try it online!](https://tio.run/nexus/bash#jczRCoIwGAXg@z3FAQWvnK3CICSK6KZn6Ebm1GK6MSfNp1@lBdVFdC5@@A@czwfYG5FbAVsLaKMqkzcojWrGohau6BtNCXGuQGywQcULyRuqlRwICXBwgvdf8@vZ1thx2@dSDvetHmyt2gUSpW3y6pPOdIjLdw9ZliFkYXRqo3D@Uz@KiR7Jy@OZLj7BcOv97Jk1GAPjSFf4N5RWPvVseQM "Bash – TIO Nexus")1 ## Actually: GCD Actually uses [CP 437](https://en.wikipedia.org/wiki/Code_page_437#Character_set), so it sees the following characters. ``` ◄∟g ``` [Try it online!](https://tio.run/nexus/actually#@/9oesujjvnp//8bc5kAAA "Actually – TIO Nexus") ### How it works ``` (implicit) Read a and b from STDIN and push them on the stack. ◄ Unassigned. Does nothing. ∟ Unassigned. Does nothing. g Pop a and b and push gcd(a,b). (implicit) Write the result to STDOUT. ``` ## Jelly: LCM Jelly uses the [Jelly code page](https://github.com/DennisMitchell/jelly/wiki/Code-page), so it sees the following characters. ``` ×÷g ``` [Try it online!](https://tio.run/nexus/jelly#@394@uHt6f///zf@bwIA) ### How it works ``` ×÷g Main link. Left argument: a. Right argument: b × Multiply; yield ab. g GCD; yield gcd(a,b). ÷ Division; yield ab/gcd(a,b) = lcm(a,b). ``` **Note:** The formula **gcd(a,b)lcm(a,b) = ab** holds because **a** and **b** are positive. --- 1 TIO actually uses UTF-8 for Actually. Since both the ASCII characters and the CP437 characters **0x11** and **0x1c** are unassigned, the program works nevertheless. [Answer] ## [Alice](https://github.com/m-ender/alice) and [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes Alice computes the LCM: ``` //L oi@g ``` [Try it online!](https://tio.run/nexus/alice#@6@v78OVn@lQn/7/v6GRgqEFAA "Alice – TIO Nexus") What looks like a space is really `0x7F`, the `DEL` control character. Jelly computes the GCD. Since Jelly uses its own code page which is only compatible with printable ASCII, the linefeed and DEL character turn into `½` and linefeed, respectively: ``` //L½oi@ g ``` [Try it online!](https://tio.run/nexus/jelly#@6@v73Nob36mA1f6////DY3@G1oAAA "Jelly – TIO Nexus") ### Explanations Jelly is trivial: the first line defines a nonsensical helper link, the second line is the actual program and it simply contains the GCD built-in. Alice is a little bit trickier, but it also uses a built-in: ``` / Reflect to SE. Switch to Ordinal. While in Ordinal mode, the IP bounces diagonally up and down through the grid. i Read all input as a single string. L Compute the shortest common superstring of an empty string and the input. That is simply the input itself, so this does nothing. After two more bounces, the IP hits the top right corner and turns around, continuing to bounce up and down while moving west. L Still does nothing. i Try to read more input, but this simply pushes an empty string. / Reflect to W. Switch to Cardinal. The IP wraps to the last column. L Implicitly discard the empty string and convert the input to two integers. Compute their LCM. / Reflect to NW. Switch to Ordinal. The IP immediately reflects off the top boundary to move SW instead. o Implicitly convert the LCM to a string and print it. Reflect off the bottom left corner and move back NE. / Reflect to S. Switch to Cardinal. i Try to read a byte, but we're at EOF, so this pushes -1 instead. Irrelevant. The IP wraps back to the first line. / Reflect to NE. Switch to Ordinal. The IP immediately reflects off the top boundary to move SE instead. @ Terminate the program. ``` [Answer] # Octave / MATLAB, ~~66~~ 61 bytes ``` @(x,y)gcd(x,y)^(1-2*any(version==82))*(x*y)^any(version==82)) ``` Saved 5 bytes thanks to Foon. `(x*y)^any()` was of course shorter than `1+(x*y-1)*any()`. --- Well, at least it doesn't use the builtin for `lcm`. **Explanation:** This uses the builtin `gcd` to calculate the Greatest common divisor. In Octave, this is raised to the power of `1-2*any(version==82)`. `any(version==82)` is `0` in Octave, so this is simply `gcd(x,y)^1`. It's multiplied by `(x*y)^any(version==82)`, or `(x*y)^0 = 1`. For MATLAB, `gcd` is raised to the power of `1-2*any(version==82)`. `any(version==82)` is `1` in MATLAB, so this is `gcd(x,y)^-1`. It multiplied by `(x*y)^any(version==82)`, or `(x*y)^1 = x*y`. This gives the Least common multiple, since `lcm(x,y) == x*y/gcd(x,y)` for positive numbers. [Answer] # [Julia 0.4 / Julia 0.5](http://julialang.org/), 18 bytes ``` log.(1)==0?lcm:gcd ``` Evaluates to `gcd` in Julia 0.4 ([Try it online!](https://tio.run/nexus/julia#S1Ow/Z@Tn66nYahpa2tgn5Oca5WenPI/TcNCx9BEU6HGTqE4I7/8PwA "Julia 0.4 – TIO Nexus")) and to `lcm` in Julia 0.5 ([Try it online!](https://tio.run/nexus/julia5#S1Ow/Z@Tn66nYahpa2tgn5Oca5WenPI/TcNCx9BEU6HGTqE4I7/8PwA "Julia 0.5 – TIO Nexus")). ### How it works In Julia 0.4, `log.(1)` is a shorthand for `getfield(log,1)`, which returns the memory location of the `log` builtin, e.g., the pointer `Ptr{Void} @0x00007f2846cb6660`. The result is thus non-zero, the comparison is false, and the expression evaluates to `gcd`. In Julia 0.5, a new function vectorization syntax was introduced. `log.(1)` is now a shorthand for `broadcast(log,1)`, which – since `1` is not iterable – simply evaluates `log(1)`. The result is thus zero, the comparison is true, and the expression evaluates to `lcm`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly) and [MATL](https://github.com/lmendo/MATL), ~~6~~ 5 bytes ``` ZmD g ``` This is a full program in either of the two languages. It computes the GCD in Jelly ([Try it online!](https://tio.run/nexus/jelly#@x@V68KV/v//f0Oz/4ZGAA)) and the LCM in MATL ([Try it online!](https://tio.run/nexus/matl#@x@V68KV/v@/oRmXoREA)). The MATL program exits with an error (allowed by default) after producing the correct output. Only ASCII characters are used, so they correspond to the same encoded bytes in the two languages. ### Explanation of GCD in Jelly ``` ZmD Unused link g Main link (gets called automatically). Builtin GCD function (g) ``` ### Explanation of LCM in MATL ``` ZmD Compute LCM (builtin function Zm) and display immediately (D) g Tries to implicitly take input to do something with it (depending on the type of the input). Since there is no input, it errors out ``` [Answer] # Octave / MATLAB, ~~44~~ ~~42~~ 41 bytes ``` eval(['@' 'lcm'-[5 0 9]*all(version-82)]) ``` This defines an anonymous function for GCD (`@gcd`) in Octave, and for LCM (`@lcm`) in MATLAB. Example in Octave (or [Try it online!](https://tio.run/nexus/octave#@59alpijEa3uoK6gnpOcq64bbapgoGAZq5WYk6NRllpUnJmfp2thpBmr@T8xr1jD0EjH0EzzPwA)): ``` >> eval(['@' 'lcm'-[5 0 9]*all(version-82)]) warning: implicit conversion from numeric to char ans = @gcd >> ans(12,16) ans = 4 ``` Example in MATLAB: ``` >> eval(['@' 'lcm'-[5 0 9]*all(version-82)]) ans = @lcm >> ans(12,16) ans = 48 ``` [Answer] # JS (ES6), [CGL (CGL Golfing Language)](http://codepen.io/programmer5000/pen/zwYrVd), 31 bytes (non-competing) The LCM feature of CGL was added after this challenge. ```  g=(a,b)=>b?g(b,a%b):a //-LⓍ ``` What looks like a space is actually a non-breaking space, a comment for CGL. JS computes the GCD: ``` g=(a,b)=>b?g(b,a%b):a ``` And CGL computes the LCM: ``` // does nothing - decrements the current stack number, resulting in it pointing to input L computes the LCM of the first and second stack items and pushes it to the stack Ⓧ prints out the last stack item ``` Try it out: ``` Snippetify( g=(a,b)=>b?g(b,a%b):a //-LⓍ ); ``` ``` <script src="https://programmer5000.com/snippetify.min.js"></script> <input type = "number"> <input type = "number"> ``` [Answer] # [Whispers v1](https://github.com/cairdcoinheringaahing/Whispers/tree/v1)/[Whispers v2](https://github.com/cairdcoinheringaahing/Whispers/tree/v2), 51 bytes ``` > Input > Input >> R1 >> 1⊓2 >> 1⊔2 >> Output 4 ``` [Try it online! (Whispers v1)](https://tio.run/##K8/ILC5ILSr@/99OwTOvoLSEC07bKQQZgkjDR12TjaCMKWCGf2kJUIWCyf//hhZchqYA "Whispers v1 – Try It Online") [Try it online! (Whispers v2)](https://tio.run/##K8/ILC5ILSo2@v/fTsEzr6C0hAtO2ykEGYJIw0ddk42gjClghn9pCVCFgsn//4YWXIamAA "Whispers v2 – Try It Online") ## How it works The pivotal line is interestingly the only line that isn't executed by either language: ``` >> R1 ``` In Whispers (both versions), lines which don't match one of a certain set of regex are completely ignored. As a result, lines containing invalid commands are simply skipped over by the interpreter. `R` is a command that returns the magnitude and angle of a vector, which was added in version 2. In version 1 however, it's an invalid command, so that line is removed. In both versions, the execution pattern is the same: output the value on line **4**, which is either the GCD or LCM of the inputs, depending on the version. In version 1, we remove the 3rd line, so line **4** is ``` >> 1⊔2 ``` which simply runs the LCM command on the inputs. In version 2 however, the program is unchanged, meaning that line **4** is ``` >> 1⊓2 ``` which is the GCD builtin applied to the two inputs. Finally, in both versions, the value on line **4** is outputted and the program ends ]
[Question] [ [Chebyshev Polynomials](https://en.wikipedia.org/wiki/Chebyshev_polynomials) are a family of orthogonal polynomials that pop up in all kinds of places in math, and they have a lot of quite interesting properties. One characterization of them is that they are the unique polynomials that satisfy \$T\_n(\cos(x)) = \cos(nx)\$. ### Challenge Given an nonnegative integer \$n\$, you should output the \$n\$-th Chebyshev Polynomial. \$T\_n(x)\$. ### Definition The \$n\$-th Chebyshev Polynomial is given by following three term recursion: $$\begin{align} T\_0(x) & = 1 \\ T\_1(x) & = x \\ T\_{n+1}(x) & = 2xT\_n(x) - T\_{n-1}(x) \end{align}$$ ![](https://upload.wikimedia.org/wikipedia/commons/e/eb/Chebyshev_Polynomials_of_the_1st_Kind_%28n%3D0-5%2C_x%3D%28-1%2C1%29%29.svg) ### Details If your language has a native polynomial type, you can use that one as an output, otherwise you should output a list of coefficients in ascending- or descending order, or as a string representing a polynomial. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins ### Examples ``` T0(x) = 1 T1(x) = x T2(x) = 2x^2 - 1 T3(x) = 4x^3 - 3 x T4(x) = 8x^4 - 8x^2 + 1 T5(x) = 16x^5 - 20x^3 + 5x T10(x) = 512x^10 - 1280x^8 + 1120x^6 - 400x^4 + 50x^2 - 1 ``` In the descending degree list format we'd get `T3(x) = [4,0,-3,0]` and in the ascending degree format we'd get `T3(x) = [0,-3,0,4]` [Answer] # Mathematica, 15 bytes ``` #~ChebyshevT~x& ``` Of course, Mathematica has a builtin. If an alternative input form is allowed (10 bytes): ``` ChebyshevT ``` takes an integer `n` and a variable. [Answer] # [Octave](https://www.gnu.org/software/octave/), 39 bytes ``` @(n)round(2^n/2*poly(cos((.5:n)/n*pi))) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI0@zKL80L0XDKC5P30irID@nUiM5v1hDQ8/UKk9TP0@rIFNTU/N/SmZxgUaahoGmJheUaYhgGiGYpkgKgIr/AwA "Octave – Try It Online") ### Explanation `cos((.5:n)/n*pi)` builds a vector with the [roots of the polynomial](https://en.wikipedia.org/wiki/Chebyshev_polynomials), given by [![enter image description here](https://i.stack.imgur.com/Qtf0Y.png)](https://i.stack.imgur.com/Qtf0Y.png) `poly` gives the monic polynomial with those roots. Multiplying by `2^n/2` scales the coefficients as required. `round` makes sure that results are integer in spite of numerical precision. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 12 bytes Yes, a builtin. Shorter than Mathematica. ``` polchebyshev ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8L8gPyc5IzWpsjgjtex/Wn6RRh5Q1EBHwRCIC4oy80qAAkoKunZAIk0jT1NT8z8A "Pari/GP – Try It Online") --- Without builtin: # [Pari/GP](http://pari.math.u-bordeaux.fr/), 34 bytes ``` f(n)=if(n<2,x^n,2*x*f(n-1)-f(n-2)) ``` [Try it online!](https://tio.run/##K0gsytRNL/j/P00jT9M2E0jaGOlUxOXpGGlVaAF5uoaauiDKSFPzf1p@kUaegq2CgY6CIRAXFGXmlQAFlBR07YAEyACgIgA "Pari/GP – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 62 bytes ``` t n|n<2=1:[0|n>0]|x<-(*2)<$>t(n-1)++[0]=zipWith(-)x$0:0:t(n-2) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v0QhrybPxsjW0CraoCbPziC2psJGV0PLSNNGxa5EI0/XUFNbO9og1rYqsyA8syRDQ1ezQsXAysAKJGek@T83MTPPtqAoM69EQaNEwVTzPwA "Haskell – Try It Online") flawr saved a byte. [Answer] ## CJam (21 bytes) ``` 1a2,qi{0X$+2f*@.-}*;` ``` This is a full program: the equivalent as an anonymous block is the same length: ``` {1a2,@{0X$+2f*@.-}*;} ``` [Online demo](http://cjam.aditsu.net/#code=1a2%2C%7B0X%24%2B2f*%40.-%7Dqi*%3B%60&input=5) [Answer] # Python + [SymPy](http://docs.sympy.org/latest/index.html), 66 bytes ``` from sympy.abc import* T=lambda n:n<2and x**n or 2*x*T(n-1)-T(n-2) ``` [Try it online!](https://tio.run/##FcjBDoIwDADQs3xFj2sjRuaNyF/sB4qINGHdUnZgXz/19JKXa9mSPlpbLUU4asz1xvMLJOZkhbow7RznhUFHfXrWBU4ihWTg6aTgtB@w/@Oxrb8VEAVj/bzdcMexu2QTLU6uEJwgti8) ### With descending coefficients representation ``` from sympy import* x=symbols('x') T=lambda n:n<2and x**n or expand(2*x*T(n-1)-T(n-2)) ``` [Try it online!](https://tio.run/##FYpBDoMgEADP5RV7c5doUunN1F/wAYzabiILQQ7wekpPk8lMrPkb5NXamYKHu/pYgX0MKWtV1u5buG4cykDKrpfz2@5AFnkbJzsUrQVCgqPErmh00RZlmmn6wxC1s1cGFkhOPgfOT1rUIyaWjDyCRe7PDw) [Answer] # [MATL](https://github.com/lmendo/MATL), 17 bytes ``` lFTi:"0yhEbFFh-]x ``` Coefficients are output in increasing order of degree. [Try it online!](https://tio.run/##y00syfn/P8ctJNNKyaAywzXJzS1DN7bi/39DAwA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8D/HLSTTSsmgMsM1yc0tQze24r9LyH8DLkMuIy5jLhMuUy5DAwA). ## Explanation For input *n*, the code applies the recursive relation *n* times. The two most recent polynomials are always kept on the stack. When a new polynomial is computed, the oldest is removed. At the end, the second-last polynomial is displayed (the last polynomial is deleted), as we have done one too many iterations. ``` l % Push 1 FT % Push [0 1]. These are the first two polynomials i:" % Input n. Do the following n times 0 % Push 0 y % Duplicate most recent polynomial h % Concatenate: prepends 0 to that polynomial E % Multiply coefficients by 2 b % Bubble up. This moves second-most recent polynomial to top FF % Push [0 0] h % Concatenate: appends [0 0] to that polynomial - % Subtract coefficients ] % End x % Delete. Implicitly display ``` [Answer] ## SageMath, 25 bytes ``` lambda n:chebyshev_T(n,x) ``` [Try it online](http://sagecell.sagemath.org/?z=eJzLScxNSklUyLNKzkhNqizOSC2LD9HI06nQBAB5EgkB&lang=sage) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` Cr1µ’ßḤ0;_’’$ß$µỊ? ``` [Try it online!](https://tio.run/##y0rNyan8/9@5yPDQ1kcNMw/Pf7hjiYF1PJAJRCqH56sc2vpwd5f9////TQE) Returns a list of coefficients in ascending order. There is another solution for **17 bytes** with floating-point inaccuracies. ``` RḤ’÷Ḥ-*ḞÆṛæ«’µ1Ṡ? ``` [Try it online!](https://tio.run/##y0rNyan8/z/o4Y4ljxpmHt4OpHW1Hu6Yd7jt4c7Zh5cdWg0UPbTV8OHOBfb///83BQA) ## Explanation ``` Cr1µ’ßḤ0;_’’$ß$µỊ? Input: integer n Ị Insignificant - abs(n) <= 1 If true, n = 0 or n = 1 µ Monadic chain C Complement, 1-x r1 Range to 1 Else µ Monadic chain ’ Decrement ß Call itself recursively Ḥ Double 0; Prepend 0 _ Subtract with $ Monadic chain ’’ Decrement twice $ Monadic chain ß Call itself recursively ``` [Answer] # [J](http://jsoftware.com/), 33 bytes ``` (0>.<:)2&*1:p.@;9:o._1^+:%~1+2*i. ``` [Try it online!](https://tio.run/##y/r/P03B1kpBw8BOz8ZK00hNy9CqQM/B2tIqXy/eME7bSrXOUNtIK1OPiys1OSNfQcM6TVPNTsFAwVDBSMFYwUTBVMHQ4P9/AA) Assumes that floating-point inaccuracies are acceptable and creates the emoji `(0>.<:)` For **41 bytes**, there is another solution that avoids floats. ``` (0&,1:)`(-&2((-,&0 0)~2*0&,)&$:<:)@.(>&1) ``` [Try it online!](https://tio.run/##DcgxCoAwDAXQvaf4g4RErCRVl6jFowhiERdv4NWrb3x3rQWrg5U6c9k5UmKOHSlU3tT@LdT44rL1nMkkhPO4HvBchDIUhoQBIyaY1voB) [Answer] # Ruby + [polynomial](http://adrianomitre.github.io/Polynomial/website/index.html), ~~59~~ 58+13 = ~~72~~ 71 bytes Uses the `-rpolynomial` flag. ``` f=->n{x=Polynomial.new 0,1;n<2?[1,x][n]:2*x*f[n-1]-f[n-2]} ``` [Answer] # [Python 2](https://docs.python.org/2/), 79 bytes ``` f=lambda n:n>1and[2*a-b for a,b in zip([0]+f(n-1),f(n-2)+[0,0])]or range(1-n,2) ``` [Try it online!](https://tio.run/##LYtBCsMgEADP7Sv26DYrqMdA@xHxsJLaLrQbkVzSz9sIOQ0MM3Xf3quG3sv9w9@8MOisD8@6xHBjm6GsDZgyiMJPqokuTcWo9UgDAafoyCVMR9ZYX0/jrVLAPj4Z12k9ztdLbaIbCEExgv0P "Python 2 – Try It Online") [Answer] # Axiom, 40 bytes ``` f(n,x)==(n<2=>x^n;2*x*f(n-1,x)-f(n-2,x)) ``` results ``` (9) -> for i in [0,1,2,3,4,5,10] repeat output ["f(y)",i,"=", f(i,y)] ["f(y)",0,"=",1] ["f(y)",1,"=",y] 2 ["f(y)",2,"=",2y - 1] 3 ["f(y)",3,"=",4y - 3y] 4 2 ["f(y)",4,"=",8y - 8y + 1] 5 3 ["f(y)",5,"=",16y - 20y + 5y] 10 8 6 4 2 ["f(y)",10,"=",512y - 1280y + 1120y - 400y + 50y - 1] Type: Void ``` it is possible define one substitution law for formula in Axiom use above f() function for expansion of cos(n\*x) where n is one integer ``` (9) -> o:=rule cos(n*%y)==f(n,cos(%y)) (9) cos(%y n) == 'f(n,cos(%y)) Type: RewriteRule(Integer,Integer,Expression Integer) Time: 0 sec (10) -> b:=o cos(20*x) (10) 20 18 16 14 524288cos(x) - 2621440cos(x) + 5570560cos(x) - 6553600cos(x) + 12 10 8 6 4659200cos(x) - 2050048cos(x) + 549120cos(x) - 84480cos(x) + 4 2 6600cos(x) - 200cos(x) + 1 Type: Expression Integer Time: 0.48 (EV) + 0.02 (OT) + 0.10 (GC) = 0.60 sec ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 126 bytes ``` f=n=>n==0?new[]{1}:n==1?new[]{0,1}:new[]{0}.Concat(f(n-1)).Select((a,i)=>2*a-(i<n-1?f(n-2)[i]:0)).ToArray(); ``` Byte count also includes: ``` using System.Linq; ``` [Try it online!](https://tio.run/##bZBRT8IwEMff@ylOnlqFZUN9YWyEGHkREyMmPhAemnKTJqPDthMJ2Wef7UaQRf8PTe/u17v/VZiBKDTWpZHqAxYHY3EbzKX6jAlRfItmxwWe8uRIwEnk3BiYNvc242Ust1LAVyHX8Mylouxc@oW8ZqUSY6lsH9yxXKWQQQKqzPO4zhKVpCpJwonC/XJ1jKqRi6JTFPZ93F6r4KFQgluaUTWIGAsWmKOwlPK@ZEk6vOYDKseuNPHAkC3lahQ67K2Yas0PlMX1pSdjtV9fql1p447b/UbmCJQ2JWfUjTVFjsEr8rX7JqSMwVXrn3Uedpf2ylwTG7xwbbBt1/iZS2MpC2aFfuRiQ78hSc9D3rW06FI30IMeY/Gflh2wtdOFKvIf7s0/4eESbsGKVHVIIjIkt@SO3JMo/AE "C# (.NET Core) – Try It Online") The function returns polynomial as an array of coefficients in ascending order (from `x^0` to `x^n`) Explanation: ``` f = n => // Create a function taking one parameter (int) n == 0 ? new[] { 1 } : // If it's 0, return collection [1] n == 1 ? new[] { 0, 1 } : // If it's 1, return collection [0,1] (so x + 0) new[] { 0 } // Else create new collection, starting with 0 .Concat(f(n - 1)) // Concatenate with f(n-1), effectively multiplying polynomial by x .Select((a, i) => 2 * a - (i < n - 1 ? f(n - 2)[i] : 0)) // Multiply everything by 2 and if possible, subtract f(n-2) .ToArray(); // Change collection to array so we have a nice short [] operator // Actually omitting this and using .ElementAt(i) is the same length, but this is my personal preference ``` [Answer] ## JavaScript (ES6), 65 bytes ``` f=n=>n?n>1?[0,...f(n-1)].map((e,i)=>e+e-(f(n-2)[i]||0)):[0,1]:[1] ``` Inefficient for large `n`. Interesting but sadly also inefficient: ``` n=>[...Array(n+1)].map(g=(m=n,i)=>i<0|i>m?0:m<2?i^m^1:g(m-1,i-1)*2-g(m-2,i)) ``` Very efficient for 68 bytes: ``` f=(n,a=[1],b=[0,1])=>n?f(n-1,b,[0,...b].map((e,i)=>e+e-(a[i]||0))):a ``` Returns an array of coefficients in ascending order. [Answer] # [Stax](https://github.com/tomtheisen/stax), 19 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ╛5%Ö←Äⁿ¿æ╔Dë!é╔J╗yì ``` [Run and debug it](https://staxlang.xyz/#p=be3525991b8efca891c944892182c94abb798d&i=0%0A1%0A2%0A3%0A4%0A5%0A10&m=2) zipping takes a lot of bytes. ]
[Question] [ **Introduction** The rain finally subsided. Most of humanity drowned [due to a bug in @user12345's code](https://codegolf.stackexchange.com/q/23406/18487). Survivors are scattered across a worldwide archipelago. Radio communication is up, and humanity is poised to thrive once more. For no reason whatsoever, zombie pirates have gathered at the Prime Meridian, and are sweeping westward. The horde devours all. **Problem** Our doomsday scenario can be described by 5 integers on a single line which represent a set of cooperating island communities. They are ordered from west (leftmost integer) to east (rightmost integer). Beginning with the island farthest east, islanders flee in pairs to the next closest island. Curiously, for each pair that embarks, only one of them ever survives the trip. Islanders *only* travel in pairs. Odd populations elect a sole inhabitant to stay behind and provide the latest radio updates on the antics of the zombie pirate horde. Populations refuse to travel until all islands to the east of them have completed their migrations or died. When the population reaches the final, westernmost island, travel ceases. The operations manager at the end of the world needs a program that can output the final population counts of each village. **Example Input** `3 8 6 0 2` **Example Output** `8 1 0 1 0` **Assumptions** * Input may be provided via stdin, read from an arbitrarily named file, or accepted as an argument * For each island, 0 <= population <= 1024 * Populations never skip an island Shortest answer wins! [Answer] ### APL, 16 characters ``` {(1e9,4⍴2)⊤2⊥⍎⍵} ``` The input is provided as string to this block: ``` {(1e9,4⍴2)⊤2⊥⍵} "3 8 6 0 2" 8 1 0 1 0 ``` or one char less if the input is provided as argument to this block: ``` {(1e9,4⍴2)⊤2⊥⍵} 3 8 6 0 2 8 1 0 1 0 ``` It is based on the idea of Ilmari Karonen in [this comment](https://codegolf.stackexchange.com/questions/23631/the-floating-horde/23652#comment49428_23652). * `2⊥⍵` does a base 2 conversion of the input. * `(1e9,4⍴2)⊤` thus converts this number back into base 2 (for the four last digits) and base 1e9 for the first, which is enough for the input ranges given above. (`1e9,4⍴2` builds the list `1e9 2 2 2 2`.) Note that the fleeing west is done automatically by the base conversion during this process. [Answer] ### GolfScript, 23 22 characters ``` ~]{{.2/@+\2%}*]}4*' '* ``` An iterative approach. The array is iterated several times and each time a number of pairs is transferred from right to left. Try the example [online](http://golfscript.apphb.com/?c=OyczIDggNiAwIDInCgp%2BXXt7LjIvQCtcMiV9Kl19NConICcq&run=true). *Short explanation of the code:* ``` ~] # convert input to an integer { # loop 4 times (enough for a 5-elements input) { # inject this block into the array . # duplicate (l r r) 2/ # determine surviving people (l r r%2) @+\ # add to the left (l+r/2 r) 2% # determine remaining people (l+r/2 r%2) }* ] # make array again of the results }4* ' '* # format output ``` [Answer] ## GolfScript (25 chars) ``` ~]-1%{\.1&\2/@+}*]-1%' '* ``` [Online demo](http://golfscript.apphb.com/?c=OyczIDggNiAwIDInCgp%2BXS0xJXtcLjEmXDIvQCt9Kl0tMSUnICcq) Pretty straightforward solution: there's a more interesting approach which defines the output value for each island as a function of the input values, but I don't think it can be golfed nearly as far as actually following the redistribution algorithm described in the question. [Answer] ## Javascript/ES6 (69) Playing with bitwise operators : * `x&=1` keeps the lowest bit (1 if odd, 0 if even) * `x>>1` is division by 2 for integers ``` f=a=>{a=a.split(' ');for(i=5;--i;a[i]&=1)a[i-1]-=-(a[i]>>1);return a} ``` Version without ES6 : ``` function f(a){a=a.split(' ');for(i=5;--i;a[i]&=1)a[i-1]-=-(a[i]>>1);return a} ``` Examples : `f("3 8 6 0 2")` returns `[8, 1, 0, 1, 0]` `f("0 997 998 999 1000")` returns `[935, 0, 1, 1, 0]` [Answer] ## Python - 96 Characters First time golfing! Input from stdin. ``` n=map(int,raw_input().split()) x=4 while x:n[x-1]+=n[x]/2;n[x]%=2;x-=1 print' '.join(map(str,n)) ``` [Answer] # J (26 characters) Here is my solution in J: `((<.@-:@}.,0:)+{.,2|}.)^:_` ``` islands1 =: 3 8 6 0 2 islands2 =: 3 8 6 3 2 ((<.@-:@}.,0:)+{.,2|}.)^:_ islands1 8 1 0 1 0 ((<.@-:@}.,0:)+{.,2|}.)^:_ islands2 9 0 0 0 0 ``` This general solution should work with any number of islands. [Answer] # Ruby, ~~97~~ ~~90~~ ~~74~~ 72 [Online version](http://ideone.com/LvQLjI) Golfed it a bit further, not reversing the array anymore... ``` f=->i{i=i.split.map(&:to_i);(1..4).each{|n|i[-n-1]+=i[-n]/2;i[-n]%=2};i} ``` [Answer] # C - 121 characters Input is taken from stdin. ``` a[5];main(i){b(i=0,0);while(i++<5)printf("%i ",a[i-1]);}b(i,j){scanf("%i",&i);return j<5?i+= b(i,j+1)/2,a[j]=j?i&1:i,i:0;} ``` [Answer] # Python2 - 98 characters Input from stdin. ``` s=[0] for v in raw_input().split()[::-1]:s=[int(v)+s[0]/2,s[0]%2]+s[1:4] print' '.join(map(str,s)) ``` # Python3 - 79 characters Input from stdin. ``` s=[0] for v in input().split()[::-1]:s=[int(v)+s[0]//2,s[0]%2]+s[1:4] print(*s) ``` [Answer] Python 2, 85 80 bytes ``` b=1 for x in raw_input().split():b=2*b+int(x) print b/16-2,' '.join(bin(b)[-4:]) ``` X people starting on any island are equivalent to X\*2 people starting one island to the right. This code converts everyone in the starting configuration to their equivalent in far-right-islanders, then uses the binary representation of the result to determine how many people end up on each island. EDIT: Shortened the code by initializing `b` to 1 instead of 0, allowing the use of `bin` instead of a format string. [Answer] # Python (101) ``` l=map(int,raw_input().split()) for i in range(4):l[3-i]+=l[4-i]/2;l[4-i]%=2 print' '.join(map(str,l)) ``` We loop through the list from back to front and move the populations around according to the specification, then print the list. Here's a quick test: ``` >>> l=map(int,raw_input().split()) 3 8 6 0 2 >>> for i in range(4):l[3-i]+=l[4-i]/2;l[4-i]%=2 ... >>> print' '.join(map(str,l)) 8 1 0 1 0 ``` [Answer] # Mathematica 105 This should work with any number of islands. ``` f[w_,n_:1]:= If[n==Length@w,w, f[w~ReplacePart~{-n-> Mod[z=w[[-n]],2],-(n+1)->(w[[-(n+1)]]+ z~Quotient~2)},n+1]] ``` ## Examples 5 islands ``` f[{3, 8, 6, 0, 2}] ``` > > {8, 1, 0, 1, 0} > > > --- 25 islands ``` f[{145, 144, 144, 59, 35, 129, 109, 99, 200, 24, 219, 96, 12, 121, 75,20, 153, 124, 131, 178, 228, 120, 63, 207, 228}] ``` > > {270, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, > 1, 1, 0} > > > [Answer] # Java - ~~647~~ 533 but hoping for some brownie points for Java 8 Streams. ``` class I{int p;I e;I(int p,I e){this.p=p;this.e=e;}void x(){if(e!=null){int r=p&1;e.p+=(p-r)/2;p=r;}}public String toString(){return ""+p;}}Deque<I>B(String d){H<I>e=new H<>();return Arrays.stream(d.split(" ")).map(s->Integer.valueOf(s)).map(p->e.hold(new I(p,e.held()))).collect(Collectors.toCollection(LinkedList::new));}void x(Deque<I>is){is.descendingIterator().forEachRemaining((I i)->{i.x();});}void t(String s){Deque<I> a=B(s);x(a);System.out.println(a);}class H<T>{T h=null;H(){}T hold(T t){return (h=t);}T held(){return h;}} ``` The uncompressed form: ``` private static class Island { int population; final Island eastwardIsland; Island(int population, Island eastwardIsland) { this.population = population; this.eastwardIsland = eastwardIsland; } private void exodus() { if (eastwardIsland != null) { // How many remain. int remain = population & 1; // How many leave. int leave = population - remain; // Account for 50% death rate. int arrive = leave / 2; // Modify the eastward island population. eastwardIsland.population += arrive; // Change my population. population = remain; } } @Override public String toString() { return String.valueOf(population); } } private Deque<Island> buildIslands(String data) { // Holds the island to the east as we traverse. final Holder<Island> eastward = new Holder<>(); // Build my list of islands - assumes order is retained. return Arrays.stream(data.split(" ")) // Convert to int. .map(s -> Integer.valueOf(s)) // Build the island in a chain. .map(p -> eastward.hold(new Island(p, eastward.held()))) // Roll them into a linked list. .collect(Collectors.toCollection(LinkedList::new)); } private void exodus(Deque<Island> islands) { // Walk backwards. islands.descendingIterator() // Perform all exodus. .forEachRemaining((Island i) -> { i.exodus(); }); } private void test(String data) { Deque<Island> archipelago = buildIslands(data); // Initiate the exodus. exodus(archipelago); // Print them. System.out.println(archipelago); } ``` With an assist of: ``` // Mutable final. private static class Holder<T> { private T held = null; public Holder() { } public Holder(T it) { held = it; } public T hold(T it) { return (held = it); } public T held() { return held; } @Override public String toString() { return held == null ? "null" : held.toString(); } } ``` Slightly concerned that @DavidCarraher's test: ``` 145 144 144 59 35 129 109 99 200 24 219 96 12 121 7520 153 124 131 178 228 120 63 207 228 ``` generates ``` 270, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0 ``` [Answer] ## Java - ~~196~~ 195 I told myself I wouldn't post it if I couldn't get it under 200... I honestly don't think I can get rid of anything else, it's pretty slim for Java. ``` class H{public static void main(String[]a){int l=a.length,p[]=new int[l],i=l;for(;i-->0;){p[i]=Integer.valueOf(a[i]);if(l-i>1){p[i]+=p[i+1]/2;p[i+1]%=2;}}for(;++i<l;System.out.print(p[i]+" "));}} ``` Line breaks: ``` class H{ public static void main(String[]a){ int l=a.length,p[]=new int[l],i=l; for(;i-->0;){ p[i]=Integer.valueOf(a[i]); if(l-i>1){ p[i]+=p[i+1]/2; p[i+1]%=2; } } for(;++i<l;System.out.print(p[i]+" ")); } } ``` **Sample input output:** ``` $ java H 3 8 6 0 2 8 1 0 1 0 $ java H 0 1 2 3 4 5 6 7 8 9 10 1 1 1 1 1 1 1 0 1 0 0 $java H 235 897 158 693 809 1 0 1 ``` [Answer] ## Java - 179 characters **Compressed:** ``` class F{public static void main(String[] a){int l=0,x,s,i=a.length-1;String z="";for(;0<=i;i--){x=Integer.valueOf(a[i])+l;s=i>0?x%2:x;l=(x-x%2)/2;z=s+" "+z;}System.out.print(z);}} ``` **Normal:** ``` public class FloatingHorde { public static void main(String[] a) { int leave = 0; String outputStr = ""; for (int i = a.length - 1; 0 <= i ; i--) { int x = Integer.valueOf(a[i]) + leave; int stays = i > 0 ? x % 2 : x; leave = (x - x % 2) / 2; outputStr = stays + " " + outputStr; } System.out.print(outputStr); } } ``` **Sample output:** ``` $ java F 3 8 6 0 2 8 1 0 1 0 $ java F 7 6 5 4 3 11 1 1 1 1 ``` [Answer] ## Emacs Lisp 144 chars Not tiny, but it works ``` (lambda (d) (setq x d)(while(cdr x) (setcar(cdr x)(+(/(-(car x)(%(car x)2))2)(cadr x))) (setcar x (-(car x)(*(/(car x)2)2))) (pop x)) (reverse d)) ``` [Answer] # awk - 44 Characters ``` {for(i=NF;i>1;){n=int($i/2);$i%=2;$--i+=n}}1 ``` [Answer] # Java - 116 Characters For example `int[] i = {2, 33, 16, 5};` (I guess those don't add to the count, since each number can vary) would output `23 0 0 1` ``` for(int j = i.length-1; j > 0; j--) { while(i[j] > 1) { i[j] -= 2; i[j-1]++; } } for(int j = 0; j < i.length; j++) { System.out.print(i[j] + " "); } ``` ]
[Question] [ ## Problem definition Print out the powerset of a given set. For example: ``` [1, 2, 3] => [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]] ``` Each element is to be printed on a separate line, so the above example would be printed as: ``` [] [1] [2] ... [1, 2, 3] ``` ## Example code (in D, python example [here](https://stackoverflow.com/questions/1482308/whats-a-good-way-to-combinate-through-a-set)): ``` import std.stdio; string[][] powerset(string[] set) { if (set.length == 1) { return [set, []]; } string[][] ret; foreach (item; powerset(set[1 .. $])) { ret ~= set[0]~item; ret ~= item; } return ret; } void main(string[] argv) { foreach (set; powerset(argv[1 .. $])) writeln(set); } ``` ## Input Elements will be passed as arguments. For example, the example provided above would be passed to a program called `powerset` as: ``` powerset 1 2 3 ``` Arguments will be alphanumeric. ## Rules 1. No libraries besides io 2. Output does not have to be ordered 3. Powerset does not have to be stored, only printed 4. Elements in the set must be delimited (e.g. `1,2,3`, `[1,2,3]` and `['1','2','3']` are acceptable, but `123` is not * Trailing delimiters are fine (e.g. `1,2,3, == 1,2,3`) 5. *Best* is determined based on number of bytes The best solution will be decided no less than 10 days after the first submission. [Answer] # Mathematica 16 **Code** `Subsets` is native to Mathematica. ``` Column@Subsets@s ``` The code (without column) can be [verified on WolframAlpha](http://www.wolframalpha.com/input/?i=Subsets%5B%7B1,2,3%7D%5D). (I had to use brackets instead of `@`; they mean the same thing. **Usage** ``` s={1,2,3} Column@Subsets@s ``` ![output](https://i.stack.imgur.com/zez7U.png) --- This method (55 chars) uses the approach suggested by @w0lf. ``` s #&/@Tuples[{0,1},Length@s]/.{0:>Sequence[]}//Column ``` **Breakdown** Generate the tuples, composed of `0` and `1`'s of length `Length[s]` ``` Tuples[{0, 1}, Length@s] ``` > > {{0, 0, 0}, {0, 0, 1}, {0, 1, 0}, {0, 1, 1}, {1, 0, 0}, {1, 0, 1}, {1, > 1, 0}, {1, 1, 1}} > > > Multiply the original list (vector) by each tuple: ``` s # & /@ Tuples[{0, 1}, Length@s] ``` > > {{0, 0, 0}, {0, 0, 3}, {0, 2, 0}, {0, 2, 3}, {1, 0, 0}, {1, 0, 3}, {1, > 2, 0}, {1, 2, 3}} > > > Delete the `0`'s. `%` is shorthand for "the preceding output". %/. {0 :> Sequence[]} > > {{}, {3}, {2}, {2, 3}, {1}, {1, 3}, {1, 2}, {1, 2, 3}} > > > Display in column: ![Mathematica graphics](https://i.stack.imgur.com/MKYu1.png) [Answer] ## C, 118 115 Whilst can save approx 20 chars with simpler formatting, still not going to win in code golf terms either way. ``` x,i,f; main(int a,char**s){ for(;x<1<<a;x+=2,puts("[]"+f)) for(i=f=0;++i<a;)x&1<<i?f=!!printf("%c%s","[,"[f],s[i]):0; } ``` Testing: ``` /a.out 1 2 3 [] [1] [2] [1,2] [3] [1,3] [2,3] [1,2,3] ``` [Answer] ### GolfScript, 22 18 characters ``` ~[[]]{{+}+1$%+}@/` ``` Another attempt in GolfScript with a completely different algorithm. Input format is the same as with w0lf's answer. ([online test](http://golfscript.apphb.com/?c=OydbMSAyIDNdJwoKfltbXV17eyt9KzEkJSt9QC9g&run=true)) [Answer] ## GolfScript (43 chars) This may seem quite long, but it's the first solution to follow the spec: input is from command-line arguments, and output is newline-delimited. ``` "#{ARGV.join(' ')}"n/[[]]\1/{`{1$+.p}+%}%p; ``` E.g. ``` $ golfscript.rb powset.gs 1 2 3 ["1"] ["2"] ["2" "1"] ["3"] ["3" "2"] ["3" "1"] ["3" "2" "1"] [] ``` [Answer] ## awk (82) ``` {for(;i<2^NF;i++){for(j=0;j<NF;j++)if(and(i,(2^j)))printf "%s ",$(j+1);print ""}} ``` assume saved in file powerset.awk, usage ``` $ echo 1 2 3 | awk -f powerset.awk 1 2 1 2 3 1 3 2 3 1 2 3 ``` **ps** if your awk doesn't have and() function, replace it with `int(i/(2^j))%2` but adds two to the count. [Answer] ## JavaScript, 98 Sadly, a good chunk is spent on output formatting. ``` for(n in a=eval(prompt(i=p=[[]]))) for(j=i+1;j;) p[++i]=p[--j].concat(a[n]); alert('[]'+p.join('\n')) ``` ### Input Takes a JavaScript array. (e.g. [1,2,3]) ### Output ``` [] 1 1,2 2 2,3 1,2,3 1,3 3 ``` [Answer] ## J, 19 chars ``` (<@#~#:@i.@(2&^)@#) (<@#~#:@i.@(2&^)@#) 1 2 3 ┌┬─┬─┬───┬─┬───┬───┬─────┐ ││3│2│2 3│1│1 3│1 2│1 2 3│ └┴─┴─┴───┴─┴───┴───┴─────┘ ``` The ascii boxing in the output is called `boxing` and provides heterogen collection (for different length of arrays here). [Answer] ## Python ~~70~~ 67 bytes ``` def p(a,*v): i=0;print v for n in a:i+=1;p(a[i:],n,*v) p(input()) ``` Input is taken in the same manner as for [ugoren's solution](https://codegolf.stackexchange.com/questions/9045/shortest-power-set-implementation/9060#9060). Sample I/O: ``` $ echo [1,2,3] | powerset.py () (1,) (2, 1) (3, 2, 1) (3, 1) (2,) (3, 2) (3,) ``` [Try it online!](https://tio.run/##FcoxDoAgEATAnldsCUoh2GF4iaEgUeI1x8Wgia9HnXrkaUdl3/u2F4jOdrhNUKA4LXISN9wKpZ5gECMHGqNbvrZSSJb/rEQTy9W0Mb2vzsJbzOkF "Python 2 – Try It Online") [Answer] ## Golfscript 48 ``` ~:x,:§2\?,{[2base.,§\-[0]*\+x\]zip{~{}{;}if}%p}% ``` This program uses the binary representations of numbers from 0 to length(input) to generate powerset items. ### Input The input format is the Golfscript array format (example: `[1 2 3]`) ### Output The output is a collection of arrays separated by newlines, representing the power set. Example: ``` [] [3] [2] [2 3] [1] [1 3] [1 2] [1 2 3] ``` ### Online Test The program can be tested online [here](http://golfscript.apphb.com/?c=OydbMSAyIDNdJwoKfjp4LDrCpzJcPyx7WzJiYXNlLizCp1wtWzBdKlwreFxdemlwe357fXs7fWlmfSVwfSU%3D&run=true). [Answer] # Python (74 70 chars) ``` def p(a,v): if a:i,*a=a;p(a,v);p(a,v+[i]) else:print v p(input(),[]) ``` for input as `1,2,3` or `[1,2,3]`, output is: ``` [] [3] [2] [2, 3] [1] [1, 3] [1, 2] [1, 2, 3] ``` [Answer] ## Haskell (96) ``` import Control.Monad import System.Environment main=getArgs>>=mapM print.filterM(\_->[False ..]) ``` If importing `Control.Monad` isn't allowed, this becomes **100** characters: ``` import System.Environment main=getArgs>>=mapM print.p p z=case z of{[]->[[]];x:y->p y++map(x:)(p y)} ``` [Answer] ## Ruby, 39 ``` $*.map{p *$*.combination($.) $.+=1} p$* ``` [Answer] **Mathematica 53** ``` Column@Fold[#~Join~Table[x~Join~{#2},{x,#}]&,{{}},#]& ``` ![enter image description here](https://i.stack.imgur.com/nb8Lu.png) [Answer] ## APL (26) Reads input from keyboard because there's no `argv` equivalent. ``` ↑⍕¨(/∘T)¨↓⍉(M/2)⊤⍳2*M←⍴T←⎕ ``` Usage: ``` ↑⍕¨(/∘T)¨↓⍉(M/2)⊤⍳2*M←⍴T←⎕ ⎕: 1 2 3 3 2 2 3 1 1 3 1 2 1 2 3 ``` Explanation: * `T←⎕`: read input, store in `T` * `M←⍴T`: store length of `T` in `M` * `(M/2)⊤⍳2*M`: generate the bit patterns for `1` upto `2^M` using `M` bits. * `↓⍉`: split the matrix so that each bit pattern is separate * `(/∘T)¨`: for each bit pattern, select those sub-items from `T`. * `↑⍕¨`: for output, get the string representation of each element (so that it will fill using blanks and not zeroes), and format as a matrix (so that each element is on its own line). [Answer] **Scala, 81** ``` def p[A](x:Seq[A]){x.foldLeft(Seq(Seq[A]()))((a,b)=>a++a.map(b+:_)).map(println)} ``` [Answer] # JavaScript (*ES6*) 76 Partially copied from this one: <https://codegolf.stackexchange.com/a/51502/21348> Using a bitmap, so it's limited to no more than 32 elements. Run the snippet in Firefox to test. ``` f=l=>{ for(i=0;i<1<<l.length;i++) console.log(l.filter(v=>[i&m,m+=m][0],m=1)) } // TEST // Redefine console to have output inside the page console = { log: (...p) => O.innerHTML += p.join(' ') + '\n' } test=()=>{ var set = I.value.match(/[^ ,]+/g) O.innerHTML=''; f(set); } test() ``` ``` #I,#O { border: 1px solid #aaa; width: 400px; padding:2px} ``` ``` Insert values, space or comma separated:<br> <input id=I value='1 2 3'> <button onclick="test()">-></button> <pre id=O></pre> ``` [Answer] # C# 164 Man this is hard in C#! ``` void P<T>(T[]c){foreach(var d in c.Aggregate<T,IEnumerable<IEnumerable<T>>>(new[]{new T[0]},(a,b)=>a.Concat(a.Select(x=>x.Concat(new[]{b})))))Console.WriteLine(d);} ``` [Answer] # K, 14 bytes ``` {x@&:'!(#x)#2} ``` Generate all 0/1 vectors as long as the input, gather the indices of 1s and use those to select elements from the input vector. In practice: ``` {x@&:'!(#x)#2} 1 2 3 (!0 ,3 ,2 2 3 ,1 1 3 1 2 1 2 3) ``` This is a bit liberal with the output requirements, but I think it's legal. The most questionable part is that the empty set will be represented in a type dependent form; `!0` is how K denotes an empty numeric vector: ``` 0#1 2 3 / integers !0 0#`a `b `c / symbols 0#` 0#"foobar" / characters "" ``` ## Explanation The `(#x)#2` builds a vector of `2` as long as the input: ``` {(#x)#2}1 2 3 2 2 2 {(#x)#2}`k `d `b `"+" 2 2 2 2 ``` When monadic `!` is applied to a vector, it is "odometer": ``` !2 2 2 (0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1) ``` Then we use "where" (`&`) on each (`'`) vector to gather its indices. The colon is necessary to disambiguate between the monadic and dyadic form of `&`: ``` &0 0 1 0 1 1 2 4 5 {&:'!(#x)#2} 1 2 3 (!0 ,2 ,1 1 2 ,0 0 2 0 1 0 1 2) ``` If we just wanted combination vectors, we'd be done, but we need to use these as indices into the original set. Fortunately, K's indexing operator `@` can accept a complex structure of indices and will produce a result with the same shape: ``` {x@&:'!(#x)#2} `a `c `e (0#` ,`e ,`c `c `e ,`a `a `e `a `c `a `c `e) ``` Elegant, no? [Answer] ## Python 2, 64 bytes Using comma-separated input: ``` P=[[]] for i in input():P+=[s+[i]for s in P] for s in P:print s ``` ## Pyth, 4 bytes (using builtin) or 14 bytes (without) As noted by @Jakube in the comments, Pyth is too recent for this question. Still here's a solution using Pyth's builtin powerset operator: ``` jbyQ ``` And here's one without it: ``` jbu+Gm+d]HGQ]Y ``` You can try both solutions [here](https://pyth.herokuapp.com/?code=jbyQ&input=1,+2,+3&debug=0) and [here](https://pyth.herokuapp.com/?code=jbu%2BGm%2Bd%5DHGQ%5DY&input=1,+2,+3&debug=0). Here's an explanation of the second solution: ``` jb # "\n".join( u # reduce( +G # lambda G,H: G+ m # map( +d]H # lambda d: d+[H], G # G), Q # input() ]Y # [[]])) ``` [Answer] ## brainfuck, 94 bytes ``` +[[<+>>+<-]++[>-<------]>-[>]<<[>>+>]>,]++++++++++[[[<]<]+[-[>[.>]]<[<]>+[>]>]<< .[<<[<]>-]++>] ``` Formatted: ``` + [ [<+> >+<-] ++[>-<------]>-[>] <<[>>+>] >, ] ++++++++++ [ [[<]<] + print [ -[>[.>]] <[<] >+[>] > ] <<. increment [ <<[<] >- ] ++> ] ``` Expects input of the form `9,10,11` without a trailing newline, and outputs subsets in the same format, sometimes with a trailing comma. The first line printed will always be empty, signifying the empty set. [Try it online.](http://brainfuck.tryitonline.net/#code=K1tbPCs-Pis8LV0rK1s-LTwtLS0tLS1dPi1bPl08PFs-Pis-XT4sXSsrKysrKysrKytbW1s8XTxdK1stWz5bLj5dXTxbPF0-K1s-XT5dPDwuWzw8WzxdPi1dKys-XQ&input=MSwyMyw0LDU) The basic idea is to place a bit next to each element, then repeatedly increment the binary number while printing the corresponding subset before each increment. (A bit indicates whether an element is in the subset.) A sentinel bit to the left of the array is used to terminate the program. This version actually creates an exponential number of sentinels to save some bytes; a more efficient 99-byte solution that only uses one sentinel can be found in the revision history. Each bit is encoded as one plus its value; i.e., it can be either `1` or `2`. The tape is laid out with the bit before each element and a single zero cell between adjacent elements. The comma is included on the tape for non-final elements, so we can conveniently just print elements without doing any extra work to handle delimiters. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 13 bytes ``` ⍪,⊃∘.,/⎕,¨⊂⊂⍬ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQZcjzra0/4/6l2l86ir@VHHDD0dfaCczqEVj7qaQKh3zX@giv9pXIYKRgrGAA "APL (Dyalog Classic) – Try It Online") Output: ``` 1 2 3 1 2 1 3 1 2 3 2 3 ``` There's a blank line at the end to represent the empty set. Explanation: `⎕` evaluated input `⎕,¨⊂⊂⍬` append an empty numeric list after each element `∘.,` Cartesian product `/` reduction (foldr) `⊃` disclose (necessary after reduction in APL) At this point the result is an n-dimensional 2-by-...-by-2 array, where n is the length of the input. `,` flatten into a vector `⍪` turn the vector into an upright 2n-by-1 matrix, so each subset is on a separate line [Answer] # [Haskell](https://www.haskell.org/), ~~80~~ 78 bytes ``` import System.Environment main=getArgs>>=mapM(print.concat).mapM(\a->[[a],[]]) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRCG4srgkNVfPNa8ssyg/Lzc1r4QrNzEzzzY9tcSxKL3Yzs42N7HAV6OgKDOvRC85Py85sURTDywUk6hrFx2dGKsTHRur@f//f5P/xv@N/hsCAA "Haskell – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ŒPŒṘ€Y ``` [Try it online!](https://tio.run/nexus/jelly#@390UsDRSQ93znjUtCby////hjpGOsYA "Jelly – TIO Nexus") `ŒṘ€Y` are string formatting. [Answer] # [Python 2](https://docs.python.org/2/), 63 bytes ``` def f(s,p=[[]]): for e in s: for u in p:p=p+[u+[e]] print p ``` [Try it online!](https://tio.run/##HccrDsAgDABQv1NUQsCMORJO0tSNZhho@Iidvvs89@SeV6tB9cwMbIaXhEhk4wbcOmQoFcabf@ubREnicDnMRBtIL3WCKBvcffAHWX0A "Python 2 – Try It Online") [Answer] # JavaScript (ES6), 68 bytes ``` a=>alert(a.reduce((a,x)=>[...a,...a.map(y=>[...y,x])],[[]]).join` `) ``` ### Demo ``` let f = a=>alert(a.reduce((a,x)=>[...a,...a.map(y=>[...y,x])],[[]]).join` `) f([1,2,3]) ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes ``` ⊇ᵘẉᵐ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FX@8OtMx7u6ny4dcL//9GGOkY6xrEA "Brachylog – Try It Online") ``` ẉ Write on its own line ᵘ ᵐ every unique ⊇ subset of the input. ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 1 byte ``` y ``` Since Pyth has implicit `Q` (input variable) at the end of programs, this is basically just power set of the input. I don't think this violates any rules (although 'No libraries besides io' is a bit vague) [Try it online!](https://tio.run/##K6gsyfj/v/L//2hDHQUjHQXjWAA "Pyth – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) `-R`, ~~5~~ 1 [byte](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ~~Sadly, Japt's built-in for getting the powerset of an array doesn't include the empty array or this would be 1 byte.~~ It does now! ``` à ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=4A&input=WzEsIDIsIDNd) (the empty line at the end is the empty set or you can [run it with the `-Q` flag](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVE&code=4A&input=WzEsIDIsIDNd) instead to visualise the sub-arrays) [Answer] # [Zsh](https://www.zsh.org/), 31 bytes Accidentally cut my previous byte-count in half answering another prompt... ``` for i;a=({$i,}\ $^a) <<<${(F)a} ``` [Try it online!](https://tio.run/##qyrO@J@moanxPy2/SCHTOtFWo1olU6c2RkElLlGTy8bGRqVaw00zsfZ/QVFmXomCuq2trbomF1eagqGCEYRUMFYwAbISFZIUkv8DAA "Zsh – Try It Online") Delimiter is one or more spaces, we abuse trailing delimiters extensively here. [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 3 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` ʠ¶j ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDQSVBMCVDMiVCNmomZm9vdGVyPSZpbnB1dD0xJTJDJTIwMiUyQyUyMDMmZmxhZ3M9) #### Explanation ``` ʠ¶j # Implicit input ʠ # Take the powerset ¶j # Join on newlines # Implicit output ``` ]
[Question] [ [Legendre's Conjecture](https://en.wikipedia.org/wiki/Legendre%27s_conjecture) is an unproven statement regarding the distribution of prime numbers; it asserts there is at least one prime number in the interval \$(n^2,(n+1)^2)\$ for all natural \$n\$. # The Challenge Make a program which only halts if Legendre's conjecture is false. Equivalently, the program will halt if there exists \$n\$ which disproves the conjecture. # Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest program in bytes wins. * No input shall be taken by the program. * The program only needs to halt or not halt in theory; memory and time constraints shall be ignored. * One may use methods other than checking every \$n\$ if they can prove their program will still only halt if Legendre's conjecture is false. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~49~~ 47 bytes A full program that stops only if there's some \$n\ge2\$ such that all \$x\in[(n-1)^2..n^2]\$ are composite. ``` for(x=n=2n;x-n*n;d?0:x=n*n++)for(d=x++;x%d--;); ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/Lb9Io8I2z9Yoz7pCN08rzzrF3sAKKKCVp62tCZJMsa3Q1rauUE3R1bXWtP7/HwA "JavaScript (Node.js) – Try It Online") ### Commented ``` for( // outer loop: x = n = 2n; // start with x = n = 2 x - n * n; // stop if x = n² d ? 0 : x = n * n++ // if d = 0, set x = n² and increment n ) // for( // inner loop: d = x++; // start with d = x and increment x x % d--; // stop if d divides x; decrement d ); // if we end up with d = 0, then x is prime ``` [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 34 bytes ``` 1...{is-prime none $_²..($_+1)²} ``` [Try it online!](https://tio.run/##K0gtyjH7/99QT0@vOrNYt6AoMzdVIS8/L1VBJf7QJj09DZV4bUPNQ5tq//8HAA "Perl 6 – Try It Online") Counts upwards until it finds a number where none of the given range are prime. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ 11 bytes ``` ∞.∆DnÅNs>n@ ``` [Try it online!](https://tio.run/##ASYA2f9vc2FiaWX//@KIni7iiIZEbnM@bkTDhVDOuC7DgcW4w6XiiaD//w "05AB1E – Try It Online") *-6 bytes thanks to @ovs* ## Explained ``` ∞.∆DnÅNs>n@ ∞ Push an infinite list .∆ Find the first item in that list that: D s>n (n+1)^2 is @ larger or equal than nÅN the next prime from n^2 ``` [Answer] # [R](https://www.r-project.org/), ~~60~~ ~~55~~ 54 bytes *Edit: -1 byte thanks to Robin Ryder* ``` while(sd(sapply(lapply(T^2:(T=T+1)^2,`%%`,2:T),all)))T ``` [Try it online!](https://tio.run/##K/r/vzwjMydVozhFozixoCCnUiMHQoXEGVlphNiGaBtqxhnpJKiqJugYWYVo6iTm5Ghqaob8/w8A "R – Try It Online"), or, since it's rather boring to run a program that (probably) never halts and produces no output, [try](https://tio.run/##K/r/vzwjMydVQyPPtrg0V6M4saAgp1IjB0KFxBlZaYTYhmgbasYZ6SSoqiboGFmFaOok5uRoAkF1QVFmXolGskaITp6mZu3//wA "R – Try It Online") a slightly longer version (exchanging `n=sum(` for `any(`) that prints n and the number of primes in the interval (n-1)^2..n^2 for each n>2. Commented original version: ``` while( # keep looping as long as... any( # there is at least one true result among... sapply(T^2:(T=T+1)^2, # the loop from T^2 up to (T+1)^2 # (& use this opportunity to increment T)... function(x)all(x%%(2:T)) # tested for primality by checking that all # modulo divisions from 2..T have a non-zero result ) ) ){} ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ‘ɼ²ÆCµƬ ``` A niladic Link which, if the conjecture is False, will yield a list of counts of primes between \$2\$ and \$k^2\$ where \$k\$ is the zero-based index of the element (although the zero-indexed element will be `None` rather than `0`). The final value in the list will be the count of primes between \$2\$ and \$n^2\$ (the next term would be the count between \$2\$ and \$(n+1)^2\$, and would be equal to that). Note: Since this uses one of Jelly's prime related built-ins, this is subject to the underlying implementation's ([sympy](https://docs.sympy.org/latest/index.html)'s) primality check, and `help(sympy.ntheory.isprime)` states *...[If] the number is larger than 2^64, a strong BPSW test is performed. While this is a probable prime test and we believe counterexamples exist, there are no known counterexamples)*. **[Try it online!](https://tio.run/##ARcA6P9qZWxsef//4oCYybzCssOGQ8K1xqz//w "Jelly – Try It Online")** ### How? Collects the counts of primes between \$2\$ and \$(k+1)^2\$ starting with \$k=0\$ until repetition would be present by appending the result. This implies there are no new primes between \$(k+1)^2\$ and \$(k+2)^2\$ (i.e. \$n^2\$ and \$(n+1)^2\$). The final result, if any, will have a leading `None` - the initial input to the function that performs the counting. ``` ‘ɼ²ÆCµƬ - Link: no arguments Ƭ - collect up (the initial input (None) and each result) until repetition: µ - apply the monadic chain - i.e. f(x=previousResult): ɼ - recall (k) from the register (initially 0), apply, store back, and yield: ‘ - increment -> k+1 ² - square -> (k+1)² ÆC - count primes from 2 to (k+1)² inclusive ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ²+æR$Ṇµ2# ``` [Try it online!](https://tio.run/##y0rNyan8///QJu3Dy4JUHu5sO7TVSPn/fwA "Jelly – Try It Online") -1 byte thanks to caird coinheringaahing -1 byte thanks to Jonathan Allan [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~67~~ 62 bytes ``` _¶¶_ {`(_+)¶_*(¶_+) _$1$2$2$1$1_ ¶(_+)¶(?!_*(?!(__+)\2+$)\1) ``` [Don't try it online!](https://tio.run/##K0otycxL/P@fK/7QtkPb4rmqEzTitTWBLC0NIKGtyRWvYqhiBISGKobxXIe2QWQ17BWBCuwVNeKB3BgjbRXNGENNrv//AQ "Retina 0.8.2 – Try It Online") Instead, [try](https://tio.run/##K0otycxLNPz/3zsh/tC2Q9viuZRUtJWqEzTitTWBPC0NIKGtyRWvYqhiBISGKobxXIe2QWQ17BWBCuwVNeKB3BgjbRXNGENNrv//DQ0A "Retina – Try It Online") a [Retina 1](https://github.com/m-ender/retina/wiki/The-Language) version which takes as input the number of iterations. Explanation: ``` _¶¶_ ``` The working area contains `n+1`, `n²` and `(n+1)²`, where `n` starts at `0` but is immediately incremented (saving 5 bytes over my previous answer which started with `n=1`). ``` {` ``` Repeat until Legendre's conjecture is false. ``` (_+)¶_*(¶_+) _$1$2$2$1$1_ ``` Increment `n`; the old `(n+1)²` becomes the new `n²` and the new `(n+1)²` is calculated. ``` ¶(_+)¶(?!_*(?!(__+)\2+$)\1) ``` If none of the numbers between `n²` and `(n+1)²` are prime, then delete `n²` and `(n+1)²`, which causes the loop to terminate, as neither stage can now match. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~194~~ ~~180~~ 169 bytes ``` #include<gmp.h> main(){mpz_t n,l,h;for(mpz_init_set_ui(n,1),mpz_init(l),mpz_init(h);mpz_mul(l,n,n),mpz_add_ui(n,n,1),mpz_mul(h,n,n),mpz_nextprime(l,l),mpz_cmp(l,h)<1;);} ``` [Try it online!](https://tio.run/##TY7NCsMgEITvfYpCLwqmkLOhryKyGhXWrSQKJaWvXqukf7eZ2fmGhcEB1HoKBFiMnVxMZ385RB2I8XtMm8pHEii8nK8L6z5QyGq1WZXASIxcfEKGf9pz2XUsyFCQoP2kjdmxL9gL/lcge8tpCdE26j0HMTXj@TRKLh@1PmFG7dY6YPv1BQ "C (gcc) – Try It Online") -14 bytes thanks to ceilingcat! -11 bytes again thanks to ceilingcat! To test, here's one that outputs the prime in each range: # [C (gcc)](https://gcc.gnu.org/), 352 bytes ``` #include<stdio.h> #include<gmp.h> #define m(X) mpz_##X main(){m(t) n,l,h;m(init_set_ui)(n,1);m(init)(l);m(init)(h);for(;;){m(mul)(l,n,n);m(add_ui)(n,n,1);m(mul)(h,n,n); printf("In ("); m(out_str)(stdout,10,l); printf(", "); m(out_str)(stdout,10,h); printf("): "); m(nextprime)(l,l);if(m(cmp)(l,h)>0)return; m(out_str)(stdout,10,l); puts(""); }} ``` [Try it online!](https://tio.run/##fZBBasQwDEX3OYVJNhJ4ysy2KbPvDWYXgmPHBksJjg2lZa5e105DO5t2J/3/viSkTrNSOYvOsfJp0i9bnNzyZK/NjzLTuveTNo61ILihoPV96LpbQ6NjwA@CiIKll7YncOzisOk4JIfA8oKHhuB/S4u9WQL0fQ1T8sWULLkC4zQd0SO82/bbbsQaHEcD7SsLaKtAsKSyMAaEcnyp5eUs/SMqxd@gfQTxeScJWL/FIpKud5VZzgCBorW2Fq9nDDqmwP9vT3GDts6733P@VMaP85ZPvvzzCw "C (gcc) – Try It Online") Note: This is probably very optimizable. When certain users inevitably improve the solution, I'll update. ;) [Answer] # [Python 2](https://docs.python.org/2/), 45 bytes ``` i=k=P=1 while~i*~i-k:P*=k;k+=1;i+=i*i<k>0<P%k ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9M22zbA1pCrPCMzJ7UuU6suUzfbKkDLNts6W9vW0DpT2zZTK9Mm287AJkA1@/9/AA "Python 2 – Try It Online") [Here's a demonstration](https://tio.run/##BcFLCoAwDAXAvafIRmirgj8EP/EMvYIL0UckihTEjVevM9cb9lPrGMHCnqvk2XGsH9yHQgbvWEbJuBqRMRwmmcvJ@FTIkRHSMxCU7kW31TRd3vbW2njd0ECSI/4 "Python 2 – Try It Online") of the code halting if we modify it to claim that all of `range(36,49)` is non-prime. We use the [Wilson's Theorem](https://codegolf.stackexchange.com/a/27022/20260) prime generator. We count up potential primes `k`, and the condition `P%k>0` is met exactly for primes. Except, we use `P*=k` instead of `P*=k*k` which makes `k=4` also be called prime, but that doesn't matter here. Here's how we halt if there's not prime between two consecutive squares. The value `i` tries to track the smallest number so that the square `i*i` is at least the current potential prime `k`. Every time we hit a prime `k`, we update `i` by checking if `i*i<k`, and if so, increment `i`. This makes it so that `k<=i*i` afterwards. But, if there is no prime between `i**2` and `(i+1)**2`, then `i` won't update in that interval, and `k` will reach all the way to `(i+1)**2`. The `while` loop conditions checks for this (writing `~i*~i` for `(i+1)**2`) and terminates the loop if it happens. --- **73 bytes** ``` n=2 while any(all(k%i for i in range(2,k))for k in range(n*n,~n*~n)):n+=1 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8/WiKs8IzMnVSExr1IjMSdHI1s1UyEtv0ghUyEzT6EoMS89VcNIJ1tTEySWjRDL08rTqcvTqsvT1LTK07Y1/P8fAA "Python 2 – Try It Online") A more direct approach of checking that each interval between squares contains a prime, based [on the solution of Manish Kundu](https://codegolf.stackexchange.com/a/208909/20260) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes First attempt: ``` [N>nÅMNn‹#] ``` Fixed (after @ovs notes): ``` [NÌnÅMN>n‹# ``` ## Explanation: ``` [NÌnÅMN>n‹# [ Infinite Loop N Current loop index (starts from 0 to Infinity) Ì add 2 ( we want to start from N=1 instead of N=0) n Squaring - (N+1)**2 ÅM Find the previous prime. Highest prime less than (N+1)**2 N> Push Current loop index + 1 n Squaring - N**2 ‹ Does Highest prime less than (N+1)**2 < N**2 ? # If true, break the loop ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/2u9wT97hVl8/u7xHDTuV//8HAA) [Answer] # [Io](http://iolanguage.org/), 124 bytes ``` method(x :=1;loop(s :=0;for(i,x*x,x*(x+2)+1,if(Range 1 to(i)asList select(o,i%o<1)size<3,s :=1;break));if(s<1,break);x=x+1)) ``` [Try it online!](https://tio.run/##JYwxDkIhEAWvQmOyKxSinfBvYGVtgwq6EdkfloJ4eSRaTPKmeEM8kjou6jLesT35Dn2adZl5BZlz5xJXINO3fQJd71FbQwnOoTyisqoxEAY5kTQlMcdbAza0YW9R6BP9wciveK0xvBDdvIq35q@uL11bxJEA1VqptFzGFw "Io – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~11~~ 10 bytes ``` `@U_Yq@QU< ``` [Try it online!](https://tio.run/##y00syfn/P8EhND6y0CEw1Ob/fwA "MATL – Try It Online") -1 byte thanks to Luis Mendo. Otherwise, pretty straightforward. ``` ` % Start a loop @ % Push loop index (n) U % square _Yq % Get next prime @QU % Loop index plus one, squared < % Continue loop if the prime is smaller than this. ``` [Answer] # [><>](http://esolangs.org/wiki/Fish), 51 bytes ``` /;?)*:&+1}::&< \~:*>2:}}:}=?^:}}:}$%?2~1+l3+1.15a&4 ``` [Try it online!](https://tio.run/##S8sszvj/X9/aXlPLSk3bsNbKSs2GK6bOSsvOyKq21qrW1j4OTKuo2hvVGWrnGGsb6hmaJqqZ/P8PAA) [Try it online! (2)](https://tio.run/##S8sszvj/X9/aXlPLSk3bsNbKSs2GK6bOSsvOyKq21qrW1j4OTKuo2hvVGWrnGGsb6hmapqqZ/P8PAA) shows the program terminating if starting above last prime in first range. **Explanation** ``` /;?)*:&+1}::&< \~:* ``` Prime branch, checks if first found prime is below \$(n+1)^2\$ and then increments \$n\$ and jumps up to the next range, otherwise terminates ``` >2:}}:}=?^ ``` Ends trial division if we have found a prime ``` :}}:}$%?2~1+l3+1. ``` Branch-free trial division ``` / \ .15a&4 ``` Initial values, starts at 10 trying to find primes below \$4^2\$ [Answer] # [Python 3](https://docs.python.org/3/), ~~107~~ ~~99~~ ~~88~~ ~~86~~ ~~90~~ ~~86~~ 79 bytes ``` n=2 while n:n+=0<sum(min(i%j for j in range(2,i))for i in range(n*n,~n*~n))or-n ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P8/WiKs8IzMnVSHPKk/b1sCmuDRXIzczTyNTNUshLb9IIUshM0@hKDEvPVXDSCdTUxMklokQy9PK06nL06rL09TML9LN@/8fAA "Python 3 – Try It Online") Initially, n=2. Then it checks if any of the 2n numbers between n^2 and (n+1)^2 are prime or not. If yes, then n is incremented, otherwise n is set to 0 and the loop terminates. *-7 bytes thanks to Jo King* [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 30 bytes ``` For[n=1,NextPrime[n++^2]<n^2,] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/98tvyg6z9ZQxy@1oiSgKDM3NTpPWzvOKNYmL85IJ/b///8A "Wolfram Language (Mathematica) – Try It Online") Special thankks to @att for saving 9 bytes [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~88~~ 84 bytes Saved 4 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` q;h;i;j;f(n){for(h=n=1;h;++n)for(h=0,i=n*n;q=j=++i<~n*~n;h|=q)for(;++j<i;)q=q&&i%j;} ``` [Try it online!](https://tio.run/##JYrNCoMwEAbveQovStZYaM@f@zASiNlAt2zpzZ9Xj6HObYaJjzXGWg0ZgoLklbb0@frMyq8WQ1C6/TkJ66gwLhyCzKeOpyLvbP@hnWUWkLENg/QFRxX9de9F1JPbXNdInuCOegE "C (gcc) – Try It Online") Will run forever on an infinite machine (with new infinity-bit `int` types!) so long as there's always a prime number in the interval \$(n^2,(n+1)^2)\$. Here's the same code modified to print the primes as they are found: # [C (gcc)](https://gcc.gnu.org/), 161 bytes ``` q;h;i;j;f(n){for(h=n=1;h;++n)for(h=0,i=n*n;q=j=++i<~n*~n;h|=q){for(;++j<i;)q=q&&i%j;if(q)printf("Found prime %d in the interval (%d, %d)\n",j,n*n,(n+1)*(n+1));}} ``` [Try it online!](https://tio.run/##JU0xDoMwENt5RYQEuiOpVOYja1/RBQEpF5WjQbQLha@nUfFgy5Ytd5dH18UYaCQmTw4ENzcvMFqxdQq1Fjz91bCVSihYb7Xm5pDqEBq/NpyLVPUNEwYbypILT@wg4GthWR3kt/ktvUpuGlTRKxa1jkOSdVg@7VNB0ZuU411y4026MSC6xurPSPseU1VNLQtgtmUqwQFStscf "C (gcc) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~12~~ 11 bytes [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` _²ôZÑ dj}f1 ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=X7L0WtEgZGp9ZjE) (May cause your browser to explode!) ``` _ :Function taking an integer Z as argument ² : Z squared ZÑ : Z times 2 ô : Range [Z²,Z²+Z*2] d : Any j : Prime } :End function f1 :Return the first Z≥1 that returns false ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 12 bytes ``` +₁;?≜^₂ᵐ⟧₂ṗⁿ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/X/tRU6O1/aPOOXGPmpoebp3waP5yEGPn9EeN@///BwA "Brachylog – Try It Online") ### How it works Brachylog will try to find a value `N` that fulfills the following program: ``` +₁;?≜^₂ᵐ⟧₂ṗⁿ +₁ N+1 ;? [N+1, N] ≜ Try possible numbers, e.g. [5, 4] ^₂ᵐ Map square [25, 16] ⟧₂ Range from min to max ṗⁿ Succeeds if there is no prime in this range ``` [Answer] # Scala, ~~98~~ ~~93~~ ~~91~~ 87 bytes *-7 bytes thanks to Dominic Van Essen* ``` Stream.iterate(2:BigInt)(_+1)find(n=>n*n to n*n+2*n forall(x=>n to(2,-1)exists(x%_<1))) ``` Without `BigInt`, it could be made a few bytes shorter, but then it would overflow. It first creates an infinite list starting at 2, then tries to find an `n` in that list such that every number `x` in the range `n^2` to `(n+1)^2` is composite. [Try it in Scastie](https://scastie.scala-lang.org/x3HjWbAxRYeVxcYX28gqzA) ]
[Question] [ # Background The game of [Morra](http://en.wikipedia.org/wiki/Morra_(game)) is a simple game. In the "original" version, several players simultaneously throw out a number 0-5 with their hands while guessing the total sum of everyone's hands. The version I'll use here has been modified to increase the potential for non-trivial strategy, and it is described below: * There are two players. * Like in rock-paper-scissors, the players move simultaneously. * Each turn, each player chooses a number 0-5 and also *guesses* their opponents choice of 0-5. This means that two numbers are output each turn. To clarify, both numbers output should be in the range 0-5, inclusive. * If you guess your opponent's choice correctly but your opponent did not guess correctly, you win a certain number of points equal to the sum of the two numbers played. For example, if the numbers played were 3 and 5, a correct guess would be worth 8 points. * If both or neither players guess correctly, no points are awarded. * The person with the most points after 1000 rounds wins that game. --- # The Tournament The tournament will be done in a round-robin style and will be run by creating each possible pairing of contestant. For each victory, the contestant gains 2 victory points. Each tie results in 1 victory point. No victory points are gained for a loss. Intuitively, the winner of the tournament shall be the contestant with the most victory points against others. --- # How to Enter There will be two methods of submitting bots to compete. The first, and much preferred method, is to implement a Java interface supplied by the controller. The second method is to write an independent program. Let's cover the Java method first. The interface you will need to implement is `Player` and it defines two methods: `public String getName()` identifies your bot, and `public int[] getMove(String[] args)` takes `args` as an array of six strings, `mychoices myguesses myscore opponentchoices opponentguesses opponentscore`. An example is the following: ``` 042 045 0 324 432 6 ``` This means that I chose 0 on the first round and guessed that my opponent was going to throw a 0. My opponent threw a 3 and guessed I would throw a 4. In the third round, my opponent made the correct guess that I would throw a 2, meaning that he gains 2+4=6 points. Your method will return an array of two integers, which are your choice and guess, respectively. An example is `{4,2}`for a choice of 4 and a guess of 2. Here is an example of a complete Java bot written as a method. If you want, your submission only has to include what's going in the `getMove` method. ``` import java.util.Random; /** * A simple example Morra bot to get you started. */ public class ExampleBot implements Player { public String getName() { return "ExampleBot"; } public int[] getMove(String [] args) { //easiest way I know to break down to create a move history //(just contains their throw history) char[] theirThrowsC = args[3].toCharArray(); int[] theirThrows = new int[theirThrowsC.length]; for(int i = 0; i < theirThrowsC.length; i++) { theirThrows[i] = Integer.parseInt(Character.toString(theirThrowsC[i])); } //get my score int myScore = Integer.parseInt(args[2]); Random r = new Random(); int guess = r.nextInt(6); if(theirThrows.length > 0) { guess = theirThrows[theirThrows.length-1]; } //throws a random number, guesses what they threw last return new int[] {r.nextInt(6),guess}; } public static int otherMethod(int example) //you can write additional static methods { return 0; } } ``` ## As an Independent Program I am currently limited in my support of additional languages. Besides Java, I can accept programs written in Python 3.4, Perl 5, or Ruby 2.1.5. If there is a language that several people seem to want, I'll do my best to add it. The input to your program will be arguments on the command line. It could look like this: ``` perl awesomebot.plx 042 045 0 324 432 6 ``` The output of your program should be your choice followed by your guess, each followed by whitespace. Please include in your answer the exact command needed to run it. Keep in mind that I'm running Windows 8.1. --- # Extra Rules ## Saving State and Timeouts Your program will be allowed to create one text file in the local directory, where you can store information. This information will kept throughout the tournament but deleted afterwards. Give the file a name I can identify. There is a time limit of 500 milliseconds for your code to respond. Failure to respond in the time limit (or giving an invalid move) will result in forfeiture of that particular match. Java submissions currently have a passive timeout (which I may upgrade to active), whereas non-Java submissions have an active timeout where their process is terminated after 500 milliseconds. ## More submission rules * You are allowed multiple submissions, as long as they abide by the rules and don't tag-team. * Each entry must be unique. You can't make an exact copy of another bot's logic in a different language. * The bots cannot interact with each other (to form a team of any sort). * You can't use the logic of the other bots inside of your bot to, say, identify your competitor and predict its actions. You can, of course, try to determine the strategy of your opponent. * Don't attempt to mess with the controller, other contestants, or my computer. Don't connect to external information sources. # The Controller The current version of the controller is [found here](https://github.com/PhiNotPi/Morra). It is written in Java 8. The "Tournament" file is the main controller, which also contains the list of competitors (if you want to host your own competitions). --- # Leaderboard I haven't really been able to update the leaderboard very often. I am rather busy this weekend. By "rather busy" I mean no access to a computer from 6:30 AM to 9:30 PM. Here are the scores after 5 runs. The "Echo" bot kept forfeiting for some reason (might be my fault, I haven't investigated yet). ``` 170 - Quinn and Valor 158 - Historian 142 - DeltaMax 140 - MorraCowbell 132 - Extrapolator 115 - Rainbolt 102 - Popularity 100 - Interpolator 83 - CounterBot 80 - Basilisk 76 - Erratica 65 - Trendy 63 - Scholar 62 - RandomGuesser 60 - KingFisher 59 - NullifierBot 55 - EvolvedBot 48 - Confused ``` --- # Credit Many thanks to Rainbolt and Peter Taylor for their help with the controller. [Answer] ## Morra Cowbell For anyone looking for significance in the name of this bot, the name *Morra* makes me think of [Space Italian](http://darthsanddroids.net/episodes/0758.html), so I reckoned I needed a name which played on that. Other candidates included *Morra fool you* and *Morra for me*. This is a full class implementing the `Player` interface. Explanation below. ``` import java.util.Random; public class MorraCowbell implements Player { private final Random rnd = new Random(); public String getName() { return "MorraCowbell"; } public int[] getMove(String[] args) { int[] prior = new int[36]; for (int i = 0; i < 36; i++) prior[i] = 1; // args: myChoices myGuesses myScore opponentChoices opponentGuesses opponentScore if (args.length == 6 && args[3].length() == args[4].length()) { for (int i = 0; i < args[3].length(); i++) prior[6*(args[3].charAt(i) - '0') + (args[4].charAt(i) - '0')]++; } int[] weights = new int[6]; for (int r = 0; r < 6; r++) { for (int s = 0; s < 6; s++) { for (int t = 0; t < 6; t++) { weights[r] += (r + s) * ((r + s == 5 ? 1 : 0) + (r == t ? -1 : 0)) * prior[s * 6 + t]; } } } // Find the best window. int[][] magic = new int[][] { { 7776, 6480, 5400, 4500, 3750, 3125 }, { 3125, 2500, 2000, 1600, 1280, 1024 }, { 1875, 1500, 1200, 960, 768, 640 }, { 1125, 900, 720, 576, 480, 400 }, { 1620, 1296, 1080, 900, 750, 625 }, { 1296, 1080, 900, 750, 625, 500 }, { 750, 625, 500, 400, 320, 256 }, { 675, 540, 432, 360, 300, 250 }, { 648, 540, 450, 375, 300, 250 }, { 375, 300, 250, 200, 160, 128 }, { 375, 300, 240, 200, 160, 128 }, { 450, 375, 300, 240, 192, 160, 128 }, { 324, 270, 225, 180, 150, 125 }, { 270, 225, 180, 144, 120, 100, 80 }, { 225, 180, 150, 120, 96, 80 }, { 225, 180, 144, 120, 96, 80 }, { 324, 270, 216, 180, 150, 125, 100, 80, 64 }, { 135, 108, 90, 72, 60, 50 }, { 135, 108, 90, 75, 60, 50, 40, 32 }, { 108, 90, 75, 60, 48, 40, 32 }, { 54, 45, 36, 30, 25, 20, 16 }, { 54, 45, 36, 30, 24, 20, 16 } }; long bestN = 0; int bestD = 1, bestIdx = -1, bestA[] = null; for (int[] A : magic) { for (int i = 0; i < A.length - 5; i++) { long n = 0; int d = 0; for (int j = 0; j < 6; j++) { n += weights[j] * A[i + j]; d += A[i + j]; } if (n * bestD > bestN * d) { bestN = n; bestD = d; bestIdx = i; bestA = A; } } } int r = rnd.nextInt(bestD); for (int i = 0; i < 6; i++) { r -= bestA[bestIdx + i]; if (r < 0) return new int[] { i, 5 - i }; } // Just a precaution: this should be unreachable. return new int[] { 0, 5 }; } } ``` ### Explanation I started by analysing games with fewer fingers. The simplest non-trivial one allows calls of `0` or `1` and has the following payoff table (values are payoff for the row player): ``` (0,0) (0,1) (1,0) (1,1) +----------------------- (0,0) | 0 0 -1 0 (0,1) | 0 0 0 1 (1,0) | 1 0 0 -1 (1,1) | 0 -1 1 0 ``` The `(0,0)` strategy is dominated by `(0,1)`, so we can reduce the table to ``` (0,1) (1,0) (1,1) +----------------- (0,1) | 0 0 1 (1,0) | 0 0 -1 (1,1) | -1 1 0 ``` Now the `(1,0)` strategy is dominated by `(0,1)`, so we can further reduce the table to ``` (0,1) (1,1) +----------- (0,1) | 0 1 (1,1) | -1 0 ``` And now `(1,1)` is dominated by `(0,1)`, so we end up with ``` (0,1) +----- (0,1) | 0 ``` Therefore always playing `(0,1)` is a Nash equilibrium. But the curious thing is that it's not the only one. This is a symmetric zero-sum game, so the expected payoff is 0, and any mixed strategy combining `(0,1)` and `(1,0)` where `(0,1)` is picked at least 50% of the time achieves that payoff. So we have a one-dimensional space of Nash equilibria. It seems to be the case, although I haven't proven it, that `n`-finger Morra has an `n`-dimensional polytope of Nash equilibria which are mixed strategies between the `n+1` `(pick, guess)` pairs for which `pick + guess = n`. The magic numbers in the code above encode the 32 vertices of the 5-dimensional polytope of Nash equilibria. I found them by setting up a linear programming instance which represented the polytope and then using random objective functions. The reason for encoding all 32 rather than picking one is simple: the expected payoff is 0, so I need to do better than expected to get a win. I essentially assume that the other player is using a mixed strategy and estimate the distribution based on their pick history. Then I select the polytope vertex which maximises my expected gain against that estimated distribution. QuinnAndValor demonstrates the vulnerability of the assumption that the other player is using a mixed strategy. By detecting a player which uses the strategies from the Nash equilibria it is able to switch into a random walk mode where, playing a non-equilibrium strategy, it is liable on average to lose, but it only needs to gain a lead once and then it can revert to playing pairs for which `pick + guess = n`. So the Nash equilibria for a single game don't generalise trivially to Nash equilibria for the repeated game, which allows more complex strategies. [Answer] # Quinn and Valor (Updated) Quinn and Valor are an elite ranger team. With crossbow and claw, they rip apart every opponent dares to challenge them. ``` import java.util.ArrayList; import java.util.List; interface Champion extends Player { } /* * Quinn and Valor are an elite ranger team. With crossbow and claw, they ... */ public class QuinnAndValor implements Champion { private final Champion quinn = new Quinn(); private final Champion valor = new Valor(); private int checker; private int myScore, opScore; private boolean ulted; private boolean teemoDetected; private boolean quinnNeverLose, valorNeverLose; private int quinnScore, valorScore; private int quinnRound, valorRound; public QuinnAndValor() { checker = check() ? 0 : 1; } // Check if is a fine use private static boolean check() { return Thread.currentThread().getStackTrace()[3].getClassName().equals( "Tournament"); } @Override public String getName() { return quinn + " and " + valor; } @Override public int[] getMove(String[] args) { // Punish for bad usage switch (checker) { case 1: checker++; return new int[] { -1, -1 }; case 2: checker++; return null; case 3: throw new Error("Mua he he heh!"); default: if (checker > 0) throw new Error("Mua he he heh!"); break; } int round = args[0].length(); if (round == 0) { // Buy starting items myScore = opScore = 0; teemoDetected = false; quinnNeverLose = valorNeverLose = true; quinnScore = valorScore = quinnRound = valorRound = 0; ((Valor) valor).reset(); } if (ulted = useUltimate(args)) { valorRound++; return valor.getMove(args); } else { quinnRound++; return quinn.getMove(args); } } /* * Quinn's ultimate has a lengthy cool-down, especially at lower ranks, so * we have to use it only when needed. */ private boolean useUltimate(String[] args) { int round = args[0].length(); int lastMyScore = myScore; int lastOpScore = opScore; myScore = Integer.parseInt(args[2]); opScore = Integer.parseInt(args[5]); int score = (myScore - opScore) - (lastMyScore - lastOpScore); if (ulted) { valorScore += score; valorNeverLose &= score >= 0; } else { quinnScore += score; quinnNeverLose &= score >= 0; } if (round < 100) { // Haven't hit level 6 yet return false; } if (myScore > opScore) { // We're already winning. Press on with strategy impossible to lose if (quinnNeverLose && quinnRound >= 50) return false; if (valorNeverLose && valorRound >= 50) return true; } else if (myScore < opScore) { // Although Quinn can blind others to counter them, she can be // counter be Teemo who also has blind! Don't fall for this! if (!teemoDetected) { teemoDetected = true; for (int i = round - 20; i < round; i++) if (args[3].charAt(i) + args[4].charAt(i) != 'e') teemoDetected = false; } if (teemoDetected) return true; } if (valorRound < 100) { // If we never use our ultimate, how can we know how strong it is? return true; } if (quinnScore < 0 && valorScore < 0) return valorRound < quinnRound; else return quinnScore * valorRound < valorScore * quinnRound; } @Override public String toString() { return getName(); } /* * Quinn is a female Demacian elite ranger. * * @see Valor */ public static class Quinn implements Champion { @Override public String getName() { return "Quinn"; } /* * Magic! */ @Override public int[] getMove(String[] args) { int t = (int) ((Math.sqrt(Math.random() * 168 + 1) - 1) / 2); return new int[] { 5 - t, t }; } @Override public String toString() { return getName(); } } /* * Valor is Quinn's Demacian eagle. * * @see Quinn */ public static class Valor implements Champion { @Override public String getName() { return "Valor"; } private int lastRound; private double[][] c; public void reset() { lastRound = 0; c = new double[6][6]; } /* * Magic! */ @Override public int[] getMove(String[] args) { int round = args[0].length(); int[] b = new int[6]; for (int i = round - 12; i < round; i++) b[args[0].charAt(i) - '0']++; { double deWeight = Math.pow(0.95, round - lastRound); for (int i = 0; i < 6; i++) for (int j = 0; j < 6; j++) c[i][j] *= deWeight; double weight = 1; for (int i = round - 1; i >= lastRound; i--) { c[args[3].charAt(i) - '0'][args[4].charAt(i) - '0'] += weight; weight *= 0.95; } } lastRound = round; List<int[]> pq = new ArrayList<>(1); double e = Integer.MIN_VALUE; for (int i = 0; i < 6; i++) for (int j = 0; j < 6; j++) { double f = 0; for (int k = 0; k < 6; k++) f += (i + j) * c[j][k]; for (int k = 0; k < 6; k++) f -= (i + k) * c[k][i]; // recently played moves are dangerous f -= b[i] * b[i] * ((round + 11) / 12); if (f >= e) { if (f > e) { pq.clear(); e = f; } pq.add(new int[] { i, j }); } } return pq.get((int) (Math.random() * pq.size())); } @Override public String toString() { return getName(); } } } ``` They almost always win against all Java solution on my machine. ## Edit: I admit Quinn and Valor failed to duel Historian, but I still have good faith in them to win the tournament. My principle is, for any solution with `choice + guess == 5`, also playing with `choice + guess == 5` grantees keeping your advantage. ## Update: Well... everything just got complicated. [Answer] # Scholar Scholar tries to learn from the moves of its opponent, choosing the one his opponene less guessed and guessing the one his opponent most used. But theory isn't everything, so Scholar doesn't do very well... ``` import java.util.HashMap; public class Scholar implements Player { public static int[] pm = new int[6]; public static int[] pg = new int[6]; public static HashMap<Integer, Integer> lm = new HashMap<>(); public static HashMap<Integer, Integer> lg = new HashMap<>(); public String getName() { return "Scholar"; } public int[] getMove(String[] a) { int r = a[0].length(); for (int i = 0; i < 6; i++) { pm[i]=0; pg[i]=0; } for (int i = 0; i < a[3].length(); i++) { int m = Integer.parseInt(String.valueOf(a[4].charAt(i))); int g = Integer.parseInt(String.valueOf(a[3].charAt(i))); pm[m]++; pg[g]++; } for (int i = 0; i < pm.length; i++) { lm.put(i, pm[i]); lg.put(i, pg[i]); } if (r < 1) { return new int[] { 3, 3 }; } else { int mm = lm.entrySet().stream().min((x, y) -> x.getValue() > y.getValue() ? 1 : -1).get().getKey(); int mg = lg.entrySet().stream().max((x, y) -> x.getValue() > y.getValue() ? 1 : -1).get().getKey(); return new int[] { mm, mg }; } } } ``` [Answer] # DeltaMax *(Updated to not use files and added a new section. Also modified to no longer get stuck tying in the first section.)* Consists of a couple of strategies which start simple then get more complex — if you clear one, it moves you to the next section. * **Section 1:** Guess `{0, 5}` consistently * **Section 2:** Check if your last 4 guesses form a constant, linear or quadratic pattern and keep guessing the pattern until it breaks * **Section 3:** Check if you guess an abnormally low amount of some number (less than 1/13) and choose that number * **Section 4:** Analyse bigrams in your choices and look at what's more likely to come out next * **Section 5:** Look at the past 100 rounds and pick the `(choice, guess)` pair which would have the best expectation, weighted so that recent rounds are more important * **Section final:** Guess randomly, with higher likelihood of having low choices and high guesses. If you get here, then DeltaMax has given up and would like to say, "good game". To find out which strat was used in the end, uncomment the ``` if (myChoices.length == 999) { System.out.println(strat); } ``` line. Apologies for the horrid Java, I spent my afternoon piecing bits together and relearning the language :) ``` import java.io.*; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class DeltaMax implements Player { private int strat = 100; public String getName() { return "DeltaMax"; } public int[] toInts(String s) { char [] chars = s.toCharArray(); int[] ints = new int[chars.length]; for (int i = 0; i < chars.length; i++){ ints[i] = Integer.parseInt(Character.toString(chars[i])); } return ints; } public int mod6(int n) { n = n % 6; if (n < 0) { n += 6; } return n; } public int[] getMove(String [] args) { int[] myChoices = toInts(args[0]); int[] myGuesses = toInts(args[1]); int myScore = Integer.parseInt(args[2]); int[] opponentChoices = toInts(args[3]); int[] opponentGuesses = toInts(args[4]); int opponentScore = Integer.parseInt(args[5]); int rounds = myChoices.length; if (rounds == 0) { strat = 100; } Random r = new Random(); // if (myChoices.length == 999) { System.out.println(strat); } if (strat == 100) { // Section 1 - {0, 5} if (opponentScore - myScore > 21 || (opponentScore >= myScore && rounds > 100)) { strat = 200; } else { return new int[] {0, 5}; } } if (strat == 200) { // Section 2 - Mini interpolator int w = opponentChoices[opponentChoices.length - 4]; int x = opponentChoices[opponentChoices.length - 3]; int y = opponentChoices[opponentChoices.length - 2]; int z = opponentChoices[opponentChoices.length - 1]; if (w == x && x == y && y == z) { // Constant return new int[] { r.nextInt(4) + 2, w }; } if (mod6(x-w) == mod6(y-x) && mod6(y-x) == mod6(z-y)) { // Linear return new int[] { r.nextInt(4) + 2, mod6(z + (z-y)) }; } if (mod6((y-x) - (x-w)) == mod6((z-y) - (y-x))) { // Quadratic return new int[] { r.nextInt(4) + 2, mod6((z-y) + mod6((y-x) - (x-w))) }; } strat = 300; } if (strat == 300) { // Section 3 - exploit least guessed int [] counts = new int[6]; for (int i = 0; i < rounds; i++) { counts[opponentGuesses[i]] += 1; } int minCount = rounds; for (int i = 0; i < 6; i++) { if ((counts[i] <= 1 || counts[i] * 13 < rounds) && counts[i] < minCount) { minCount = counts[i]; } } if (minCount == rounds) { strat = 400; } else { ArrayList<Integer> choices = new ArrayList<Integer>(); for (int i = 0; i < 6; i++) { if (counts[i] == minCount) { choices.add((Integer) i); } } int choice = choices.get(r.nextInt(choices.size())); // {0, 0} is about the worst thing you can do, so DeltaMax tries to avoid that if (choice == 0) { return new int[] { 0, r.nextInt(4) + 2 }; } else { return new int[] { choice, r.nextInt(6) }; } } } if (strat == 400) { // Section 4 - bigrams if (opponentScore - myScore > 42 || (opponentScore >= myScore && rounds > 300)){ strat = 500; } else { int[] opponentScores = new int[6]; int opponentLast = opponentChoices[opponentChoices.length - 1]; int[] myScores = new int[6]; int myLast = myChoices[myChoices.length - 1]; for (int i = 0; i < opponentChoices.length - 1; i++) { if (opponentChoices[i] == opponentLast) { opponentScores[opponentChoices[i+1]] += 1; } if (myChoices[i] == myLast) { myScores[myChoices[i+1]] += 1; } } int maxIndex = -1; int maxScore = 0; int minIndex = -1; int minScore = rounds; for (int i = 0; i < 6; i++) { if (opponentScores[i] >= maxScore) { maxScore = opponentScores[i]; maxIndex = i; } if (myScores[i] <= minScore) { minScore = myScores[i]; minIndex = i; } } if (minIndex == 0 && maxIndex == 0) { return new int[] { 0, r.nextInt(4) + 2 }; } else { return new int[] { minIndex, maxIndex }; } } } if (strat == 500) { // Section 5 - best expectation if (opponentScore - myScore > 84 || (opponentScore >= myScore && rounds > 800)){ strat = 573; } else { int minLen = Math.min(rounds, 100); double bestScore = 0; int bestGuess = 0; int bestChoice = 5; for (int guess = 0; guess < 6; guess++) { for (int choice = 0; choice < 6; choice++) { double score = 0; int start = rounds - minLen; for (int i = start; i < rounds; i++) { if (opponentGuesses[i] == choice && opponentChoices[i] != guess) { score -= (choice + opponentChoices[i]) * ((double) i - start) / minLen; } else if (opponentGuesses[i] != choice && opponentChoices[i] == guess) { score += (choice + opponentChoices[i]) * ((double) i - start) / minLen; } } if (score > bestScore) { bestScore = score; bestGuess = guess; bestChoice = choice; } } } if (bestChoice == 0 && bestGuess == 0) { return new int[] { r.nextInt(4) + 2, bestGuess }; } else { return new int[] {bestChoice, bestGuess}; } } } // Section final - hope for the best int num = (int) Math.floor(Math.sqrt(r.nextInt(35))); return new int[] {5 - num, num}; } } ``` [Answer] # Historian *(Updated: same logic, shorter code and **100 times faster** but you can use only one Historian bot at a tournament.)* Uses weighted random to choose a throw-guess pair based on the effectiveness of using only that pair against opponents previous history. The weights are the squares ot the achievable scores. ``` public class Historian implements Player { private static java.util.Random r = new java.util.Random(); private static int[] sc=new int[36]; //reseted between games, use only one Historian bot public String getName() {return "Historian";} public int[] getMove(String [] a) { if (a[3].length()==0) {sc=new int[36]; for(int i=0;i<6;i++) sc[i*6+(5-i)]=5-i;} else {int t=a[3].charAt(a[3].length()-1)-'0'; int g=a[4].charAt(a[3].length()-1)-'0'; for(int i=0; i<6; i++) {sc[i*6+t]+=i+t; sc[g*6+i]-=t+g;}} int sum=0; for(int i=0; i<36; i++) {sum+=(sc[i]<1)?1:sc[i]*sc[i];} int seed=r.nextInt(sum);int mt=-1; while (seed>=0) {seed-=(sc[++mt]<1)?1:sc[mt]*sc[mt];} return new int[] {(int)(mt/6),mt%6};} } ``` Beats `Quinn and Valor` *(not anymore)* and loses to `Morra Cowbell`. In the tournament with most of the bots `Historian` comes second to `Quinn and Valor`. [Answer] # Extrapolator (v1.1) Extreme extrapolation from one of the Nash-equilibriums of a simpler game. I support the terse answer format! (In python-style.) ``` public class Extrapolator implements Player { private static java.util.Random r = new java.util.Random(); public String getName() { return "Extrapolator"; } public int[] getMove(String [] args) { int t=-1; for(int c=15,s=r.nextInt(60);s>=0;s-=c,c-=2,t++); return new int[] {t,5-t}; } } ``` Seems to tie with the Magic Cow (Morra Cowbell) and beats other entries I checked. [Answer] # Trendy Trendy takes a look at the opponent's past moves, weighting them by recency. Guesses the weightiest, and picks one shifted up slightly from that. Here it is, in all its glory: ``` public class Trendy implements Player{public String getName(){return "Trendy";}public int[]getMove(String[]a){float h=0,c[]=new float[6];int i=0,l=a[3].length(),p=0;for(;i<l;)c[a[3].charAt(i++)-48]+=(float)i/l;for(i=0;i<6;i++)if(c[i]>h)h=c[p=i];return new int[]{(p+2)%6,p};}} ``` The only thing I can compare it with now is Cowbell. It loses by a small margin the majority of the time, but comes out on top often enough for my liking. We'll see how it does with more competitors. [Answer] ## Random Guesser This is really straight-forward. It effectively rolls a d6, and adds another roll to the previous roll for its guess. It won't win, but it'll provide a nice benchmark. ``` import java.util.Random; public class RandomGuesser implements Player { private final Random rnd = new Random(); public String getName() { return "RandomGuesser"; } public int[] getMove(String[] args) { return new int[] { rnd.nextInt(6), rnd.nextInt(6) }; } } ``` [Answer] # Confused, Python 3 An unnecessarily complicated entry. Even I don't know what it does. ``` import sys from random import * if len(sys.argv) == 7: mn,mg,ms,on,og,os = [list(map(int, v)) for v in sys.argv[1:]] s,t = sum(mn+on)%5, sum(mg+og)%5 n = [0]*3+list(range(6))*5+[5,0,5] m = [1,0,5,4]+n[:-2:s//9+1] numoptions = [n.extend(n[i+s::5+t]+[i]*i*(6+t)) for i in n[:]] and n guessoptions = [m.extend(m[i+t//2::8]+[i]*i*(5+s)) for i in m[:]] and m num = choice(numoptions) guess = choice(guessoptions) else: num, guess = randint(0, 5), randint(0, 5) sys.stdout.write('%u %u\n' % (num, guess)) ``` Although this advanced algorithm seems to perform worse than random in this tournament, and uses significant memory and run-time, it has stunning results for certain values of 5 ;-) [Answer] # Rainbolt Takes the difference between the last two numbers our opponent guessed, adds that to our opponent's latest guess, finds the modulus, and avoids choosing that number at all costs. For example, if you guess {5,4,3} (decreasing by one) then we would avoid choosing 2 at all costs. Takes the difference between the last two numbers our opponent chose, adds that to our opponent's latest choice, and guesses that number. For example, if you guess {1,4,5,2} (increasing by threes) then we would guess 5. Avoids pointless or very close to pointless rolls. ``` public class Rainbolt implements Player { public String getName() { return "Rainbolt"; } public int[] getMove(String[] args) { int[] yourChoices = toIntArray(args[3]); int[] yourGuesses = toIntArray(args[4]); int myChoice; if (yourGuesses.length > 1) { int latest = yourGuesses[yourGuesses.length - 1]; int secondLatest = yourGuesses[yourGuesses.length - 2]; int numberToAvoid = (2 * latest - secondLatest + 6) % 6; do { myChoice = rollRandom(); } while (myChoice == numberToAvoid); } else { myChoice = rollRandom(); } int myGuess; if (yourChoices.length > 1) { int latest = yourChoices[yourChoices.length - 1]; int secondLatest = yourChoices[yourChoices.length - 2]; myGuess = (2 * latest - secondLatest + 6) % 6; } else { myGuess = rollRandom(); } if ((myChoice + myGuess) < 3) { do { myGuess = rollRandom(); } while ((myChoice + myGuess) < 3); } return new int[] { myChoice, myGuess }; } private static int[] toIntArray(String arg) { int[] result = new int[arg.length()]; for (int i = 0; i < arg.length(); i++) result[i] = Character.getNumericValue(arg.charAt(i)); return result; } private static int rollRandom() { return (int) (Math.random() * 6); } } ``` [Answer] # Evolved Bot I evolved this bot to be the best random based bot. ``` import java.util.Arrays; public class EvolvedBot implements Player { private static final double MUTATION_RATE = .2; private static final double CROSS_OVER_RATE = .5; private final double[] pickProbabilities; private final double pickSum; private final double[] guessProbabilities; private final double guessSum; public EvolvedBot(){ this(new double[]{1.0069058661897903, 0.8949716031797937, 0.5249198534098369, 0.437811964976626, 0.2630925750209125, 0.4862172884617061}, new double[]{0.6336558074769376, 0.13700756148363913, 0.9586621925124863, 0.11223159366330251, 0.8931390659502754, 0.662974949440039}); } public EvolvedBot(double[] pickProbabilities, double[] guessProbabilities) { this.pickProbabilities = pickProbabilities; this.guessProbabilities = guessProbabilities; pickSum = Arrays.stream(pickProbabilities).sum(); guessSum = Arrays.stream(guessProbabilities).sum(); } @Override public String getName() { return "EvolvedBot"/* + ": " + Arrays.toString(pickProbabilities) + Arrays.toString(guessProbabilities)*/; } @Override public int[] getMove(String[] args) { int[] move = new int[]{5, 5}; double pick = Math.random() * pickSum; double guess = Math.random() * guessSum; for (int i = 0; i < 6; i++){ if (pick >= 0) { pick -= pickProbabilities[i]; if (pick < 0) { move[0] = i; } } if (guess >= 0){ guess -= guessProbabilities[i]; if (guess < 0){ move[1] = i; } } } return move; } public EvolvedBot mutate(double mutationRate){ double[] pickProbabilities = Arrays.copyOf(this.pickProbabilities, 6); double[] guessProbabilities = Arrays.copyOf(this.guessProbabilities, 6); for (int i = 0; i < 6; i++){ pickProbabilities[i] = Math.max(pickProbabilities[i] + (Math.random() * 2 - 1) * mutationRate, 0); } for (int i = 0; i < 6; i++){ guessProbabilities[i] = Math.max(guessProbabilities[i] + (Math.random() * 2 - 1) * mutationRate, 0); } return new EvolvedBot(pickProbabilities, guessProbabilities); } } ``` [Answer] # Popularity, Python 3 Compute guess based on popular numbers used in the past by the opponent. The numbers used recently have more weight. The number choice is often the same as the guess. ``` import sys from random import * if len(sys.argv) == 7: mn,mg,ms,on,og,os = [list(map(int, v)) for v in sys.argv[1:]] n = list(range(6)) guess = choice(n + on[-100:] + on[-20:]*8) num = choice(n + [guess]*6) else: num, guess = randint(0, 5), randint(0, 5) sys.stdout.write('%u %u\n' % (num, guess)) ``` [Answer] # Interpolator *(Switched to Java since Python was causing problems)* Uses polynomial interpolation on the last 10 opponent choices to work out the opponent's next number, then does the same to its own choices and *avoids* choosing that number. Also, Interpolator has a slight bias against choosing 0 or 5, and its choice is sometimes affected by its guess: * If it guesses 0 it will never choose 0 * If it guesses 5 it will always choose 0 or 1 ``` import java.util.ArrayList; import java.util.Collections; import java.util.Random; public class Interpolator implements Player { private final int TAIL_LENGTH = 10; public String getName() { return "Interpolator"; } public int[] toInts(String s) { char [] chars = s.toCharArray(); int[] ints = new int[chars.length]; for (int i = 0; i < chars.length; i++){ ints[i] = Integer.parseInt(Character.toString(chars[i])); } return ints; } public int mod6(int n) { n = n % 6; if (n < 0) { n += 6; } return n; } public int interpolate(int[] nums){ boolean allEqual = true; for (int i = 0; i < nums.length; i++){ if (nums[i] != nums[0]){ allEqual = false; } } if (allEqual) { return nums[0]; } else { int [] newNums = new int[nums.length - 1]; for (int i = 0; i < nums.length - 1; i++){ newNums[i] = nums[i+1] - nums[i]; } return nums[nums.length - 1] + interpolate(newNums); } } public int[] tail(int[] nums) { int minLength = Math.min(TAIL_LENGTH, nums.length); int[] tailArray = new int[minLength]; for (int i = 0; i < minLength; i++){ tailArray[i] = nums[nums.length - minLength + i]; } return tailArray; } public int[] getMove(String [] args) { Random r = new Random(); if (args[0].length() == 0){ return new int[] {r.nextInt(5), r.nextInt(5)}; } int[] myChoices = toInts(args[0]); int[] opponentChoices = toInts(args[3]); int[] opponentGuesses = toInts(args[4]); int guess = mod6(interpolate(tail(opponentChoices))); int avoid = mod6(interpolate(tail(myChoices))); if (guess == 5){ return new int[] {r.nextInt(2), 5}; } int[] choiceArray = {0, 1, 1, 2, 2, 3, 3, 4, 4, 5}; ArrayList<Integer> choices = new ArrayList<Integer>(); for (int i = 0; i < choiceArray.length; i++) { choices.add(choiceArray[i]); } choices.removeAll(Collections.singleton((Integer) avoid)); if (guess <= 0) { choices.removeAll(Collections.singleton((Integer) 0)); } int choice = choices.get(r.nextInt(choices.size())); return new int[] {choice, guess}; } } ``` [Answer] # CounterBot Does not *counter* anyone but rather counts through 0-5 in a circle (`0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4 ...`) ``` import java.util.Random; public class Counter implements Player { int lastChoice = new Random().nextInt(6); //Chooses a random starting number public String getName() { return "CounterBot"; } public int[] getMove(String[] args) { int[] oChoices = new int[6]; //Array to store the amount of individual choices of the opponent for (int i = 0; i < args[3].length(); i++) { int index = Integer.parseInt(String.valueOf(args[3].charAt(i))); //get that choice oChoices[index]++; //Increment the number corresponding the choice } int guess = 0, last = 0; for (int i = 0; i < oChoices.length; i++) { //Increment over the choices' array if (oChoices[i] > last) { //If the number has been chosen more often than the one before last = oChoices[i]; //Set the new maximum value (later the last maximum value) guess = i; //Set it as the next guess } } lastChoice++; //Increment our choice lastChoice %= 6; //Make sure it's within the bounds of 0-5 ie. modulo 6 (6 modulo 6 = 0) return new int[]{lastChoice, guess}; //return our choice and guess } } ``` [Answer] # Basilisk, Python According to legend, The Basilisk is the king of the serpents. ([source](http://en.wikipedia.org/wiki/Basilisk)) I figured that's an appropriate name for a bot that plays "The Noble Game Of Kings" and is written in python. =D This bot strikes fear into the heart of the other bots, and causes death with a single glance. ``` import sys import random args = sys.argv argc = len(args) if argc < 6: sys.exit() myChoices = args[1] myGuesses = args[2] myScore = args[3] opponentChoices = args[4] opponentGuesses = args[5] opponentScore = args[6] if len(myChoices) == 0: print (random.randint(0, 5)) print (random.randint(0, 5)) sys.exit() guesses = [0, 0, 0, 0, 0, 0] for char in opponentGuesses: i = int(char) guesses[i] += 1 #Will default towards smaller guesses to minimize opponent winnings #For example, if the guess list is #[5, 3, 7, 3, 4, 8] #This will return 1. (index of the first 3) myNextMove = guesses.index(min(guesses)) list = [ [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]] i = 0 while i < len(myGuesses) - 1: myGuess = int(myGuesses[i]) opponentResponse = int(opponentChoices[i+1]) list[myGuess][opponentResponse] += 1 i += 1 myPreviousGuess = int(myGuesses[-1]) relevantList = list[myPreviousGuess] #Defaults towards higher moves. #For example, if the list is #[3, 8, 6, 8, 0, 7] #This will return 3 (index of the last 8) highestValue = -1 highestIndex = -1 for i in range(len(relevantList)): if relevantList[i] >= highestValue: highestValue = relevantList[i] highestIndex = i myNextGuess = highestIndex print (myNextMove) print (myNextGuess) ``` This runs on a pretty simple strategy. I'm not expecting it to win, but it was fun to write. This is also my first KoTH challenge, so I'm excited to see how well it performs. ### How it picks its next move. The Basilisk always makes the move that his opponent has guessed the least number of times. In case of a tie, he will pick the smaller number. (to minimize the opponents number of points.) ### How it picks its next guess. The Basilisk will pick the most likely response to its previous guess. For example, If last time, it guessed a 3, it will go back through all of the previous times that it has guessed a 3, and then return the most common opponent move that comes after a guess of 3. In case of a tie, it will pick the larger number (to maximize the number of points it could make.) On a technical note, will this run correctly? Is print() sufficient, or should I use something like sys.stdout.write() like the other Pythonistas have done? [Answer] ## Ditto This turns into the opponent, but behind by one guess/choice. ``` import java.util.Random; public class Ditto implements Player { private final Random rnd = new Random(); public String getName() { return "Ditto"; } // myChoices myGuesses myScore oppChoices oppGuesses oppScore public int[] getMove(String[] args) { if(args[0] == null || args[0].isEmpty()) { return new int[] { rnd.nextInt(6), rnd.nextInt(6) }; } int[] myChoices = toIntArray(args[0]); int[] myGuesses = toIntArray(args[1]); //int myScore = Integer.parseInt(args[2]); int[] oppChoices = toIntArray(args[3]); int[] oppGuesses = toIntArray(args[4]); //int oppScore = Integer.parseInt(args[5]); return new int[] { oppChoices[oppChoices.length-1], oppGuesses[oppGuesses.length-1] }; } private static int[] toIntArray(String arg) { int[] result = new int[arg.length()]; for (int i = 0; i < arg.length(); i++) result[i] = Character.getNumericValue(arg.charAt(i)); return result; } } ``` [Answer] ## NullifierBot, Java Always throws 0 to minimize any opponent winnings. If the opponent ever guesses my number, they only earn what they threw. Always guesses 5 to maximize my winnings. Since I can't get any points from my throw, I want to get as many from the opponent. I could randomly guess, but where's the fun in that? ``` public class NullifierBot implements Player { public String getName() { return "NullifierBot"; } public int[] getMove(String [] args) { // always throws 0 to minimize opponents score // always guesses 5 to maximize my score return new int[] {0, 5}; } } ``` [Answer] # Erratica, Java Not great, but it was originally designed to be mostly random, until the value of the trade-off popped out at me. Manages to lose consistently vs. Counter Bot >\_< ``` import java.util.Random; class Erratica implements Player { private final Random rnd = new Random(); public String getName() { return "Erratica"; } public int[] getMove(String[] args) { if(args[0] == null || args[0].isEmpty()) { return new int[]{rnd.nextInt(4)/3+4,rnd.nextInt(4)/3}; } int[] myChoices = toIntArray(args[0]); int[] myGuesses = toIntArray(args[1]); int myScore = Integer.parseInt(args[2]); int[] opponentChoices = toIntArray(args[3]); int[] opponentGuesses = toIntArray(args[4]); int opponentScore = Integer.parseInt(args[5]); int round = opponentChoices.length + 1; int choice=0; int guess=0; if(round<7) { if(rnd.nextFloat()<(0.1f*(float)round-0.1f)) { choice=(opponentChoices[round-2]+opponentGuesses[round-2])%6; }else { choice=rnd.nextInt(6); } if(rnd.nextFloat()<(0.1f*(float)round-0.1f)) { guess=opponentChoices[round-2]; }else { guess=rnd.nextInt(6); } return new int[]{choice, rnd.nextInt(6)/5*(5-choice-guess)+guess}; }else { int lastError=Math.abs(opponentGuesses[round-2]-myChoices[round-2]); for(int i=round-2; i>round-8;i--) { if(lastError<rnd.nextInt(6)) { lastError++; }else { lastError--; } if(lastError<0) lastError+=6; } lastError = lastError%6; //shouldn't change switch(rnd.nextInt(4)) { case 0: choice=(myChoices[round-2-lastError-round/10])%6; break; case 1: choice=(myChoices[lastError+round/10])%6; break; default: choice = rnd.nextInt(6); break; } lastError=Math.abs(myGuesses[round-2]-opponentChoices[round-2]); for(int i=round-2; i>round-8;i--) { if(lastError<rnd.nextInt(6)) { lastError++; }else { lastError--; } if(lastError<0) lastError+=6; } lastError = lastError%6; //shouldn't change switch(rnd.nextInt(4)) { case 0: guess=(opponentChoices[round-2-lastError-round/10])%6; break; case 1: guess=(opponentChoices[lastError+round/10])%6; break; default: guess = rnd.nextInt(4); break; } } if(myScore>opponentScore) switch(rnd.nextInt(2)){ case 0: choice=5-guess; break; case 1: guess=5-choice; break; default: break; } return new int[]{choice, guess}; } private static int[] toIntArray(String arg) { int[] result = new int[arg.length()]; for (int i = 0; i < arg.length(); i++) result[i] = Character.getNumericValue(arg.charAt(i)); return result; } } ``` [Answer] # Echo, Ruby ``` mychoices, myguesses, myscore, opponentchoices, opponentguesses, opponentscore = $* unless mychoices puts "0 5" exit end if mychoices.size > 990 && myscore == '0' nextchoice = rand(1..5) else nextchoice = opponentchoices[-1].to_i end recentchoices = opponentchoices[/.{0,100}$/] nextguess = (0..5).max_by do |choice| (recentchoices.count(choice.to_s)+1) * (nextchoice + choice) end puts "%s %s"%[nextchoice,nextguess] ``` Plays the last play the opponent made, on the theory that anybody can make a bot that they cannot predict. Guesses based on expectation value using a hundred-move sample. [Answer] # KING FISHER ``` import java.util.Random; public class KingFisher { private Random rnd = new Random(); private int wins = 0; private int loses = 0; private int median = 0; private int medianMoved = 0; private int[] weightedLow = {40,65,80,90,95}; private int[] weightedHigh = {5,15,30,55,95}; private boolean highWeightMethod = true; public String getName() { return "KingFisher"; } public int[] getMove(String [] args) { char[] mc = args[0].toCharArray(); char[] mg = args[1].toCharArray(); char[] oc = args[3].toCharArray(); char[] og = args[4].toCharArray(); int len = mc.length; int currentGuess = 0; int currentChoice = 0; if(len < 10) return new int[] {rnd.nextInt(6),rnd.nextInt(6)}; int[] guessWeight = {0,0,0,0,0,0}; int[] guessWeightTotal = {0,0,0,0,0,0}; for(int a = 0; a< len;a++) guessWeight[oc[a]-48]++; if(!highWeightMethod){ int[] whiteList = {1,1,1,1,1,1}; for(int b = 0;b<3;b++){ int min = 0; int max = 0; int minIndex = 0; int maxIndex = 0; for(int a = 0;a<6;a++){ if(whiteList[a] == 1){ min = guessWeight[a]; max = guessWeight[a]; minIndex = a; maxIndex = a; break; } } for(int a = 0; a<6;a++){ if(whiteList[a] == 1){ if(guessWeight[a]<min){ min = guessWeight[a]; minIndex = a; } if(guessWeight[a]>max){ max = guessWeight[a]; maxIndex = a; } } } guessWeight[maxIndex] = min; guessWeight[minIndex] = max; whiteList[maxIndex] = 0; whiteList[minIndex] = 0; } } for(int a = 0; a< 6;a++) for(int b = 0; b<=a;b++) guessWeightTotal[a]+=guessWeight[b]; int randInt = rnd.nextInt(guessWeightTotal[5]); for(int a = 0; a<6;a++){ if(randInt < guessWeightTotal[a]){ currentGuess = a; break; } } if(mg[len-1] == oc[len-1]){ wins++; median++; } if(og[len-1] == mc[len-1]){ loses++; median--; } if(median > 2){ medianMoved++; median = 0; } if(median < -2){ medianMoved--; median = 0; } randInt = rnd.nextInt(95); if((wins-medianMoved)>(loses+medianMoved)){ for(int a = 0; a<6;a++){ if(randInt < weightedLow[a]){ currentChoice = a; break; } } } else{ for(int a = 0; a<6;a++){ if(randInt < weightedHigh[a]){ currentChoice = a; break; } } } if(medianMoved < -5){ highWeightMethod = !highWeightMethod; medianMoved = 0; } return new int[] {currentChoice,currentGuess}; } } ``` This guy consist out of bad guessing alghorithms that use weighted arrays mostly. [Answer] Uh uh. I know what you're thinking. "Is he gonna pick five or something else?" Well to tell you the truth in all this excitement I'm kinda not sure myself, but being this is a .44 Method, the most powerful method in the world and would overload your stack right away, you've gotta ask yourself one question: "Do I feel lucky?" Well, do ya, punk? ``` public class DirtyHarry implements Player { @Override public String getName() { return "DirtyHarry"; } @Override public int[] getMove(String[] args) { return new int[]{5, 5}; } } ``` ]
[Question] [ ## Challenge Given a size s, print a cube net of that size made of hash symbols (`#`) and spaces (). Examples: ``` 1: # # # # # # 2: # # # # # # # # # # # # # # # # # # # # # # # # 3: # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` The net can actually be any valid cube net that can fold into a cube, for example these: ``` # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` ## Rules * The resulting net must be geometrically valid (foldable into a cube) * Standard loopholes forbidden * Read the rules carefully * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer wins, but will not be selected [Answer] ## Python 2, 47 bytes ``` n=input() for c in 1,4,1:exec"print'# '*c*n;"*n ``` [Try it online!](https://tio.run/nexus/python2#@59nm5lXUFqiocmVll@kkKyQmadgqGOiY2iVWpGarFRQlJlXoq6soK6VrJVnraSV9/@/MQA) Prints this net, chosen for being left-justified: ``` # # # # # # # # # # # # # # # # # # # # # # # # ``` The lines have `n` or `4*n` copies of `'# '`. For each of `1,4,1`, we print `n` times that many copies, done `n` times for `n` lines. Having an `exec` loop inside a `for` loop seems wasteful, but I didn't see better. Alternatives I tested: ``` lambda n:('# '*n*3+'\n')*n+(' '*n+'# '*n+'\n')*3*n lambda n:('# '*n*3+'\n')*n+(' '*4*n+'# '*n*3+'\n')*n def f(n): for c in[3]*n+[1]*3*n:print('# '*c*n).center(6*n) def f(n): for c in[4]*n+[0]*n:print' '*c*n+'# '*n*3 def f(n): for c in[1]*n+[4]*n+[1]*n:print'# '*c*n def f(n): c=1;exec("print'# '*c*n;"*n+"c^=5;"*n)*3 def f(n): for i in range(3*n):print'# '*[1,4,1][i/n]*n def f(n): for c in 1,4,1:print('# '*c*n+'\n')*n, def f(n): for c in 1,4,1:exec"print'# '*c*n;"*n ``` (The `def` functions can all be one shorter as a program.) [Answer] # Octave, ~~58~~ ~~44~~ ~~42~~ 32 bytes ``` @(n)[z=repmat('# ',n);z,z,z,z;z] ``` partly inspired by @xnor 's python answer. ``` z=repmat('# ',n); ``` creates a squre pattern of '# ' for input 2 results the following pattern: ``` # # # # y=[z,z,z,z]; ``` four `z` s are concatenated horizontally: ``` # # # # # # # # # # # # # # # # [z;y;z] ``` `z` and `y` and `z` are concatenated vertically [Try It Online!](https://tio.run/#RbANN) ``` # # # # # # # # # # # # # # # # # # # # # # # # ``` Previous answer: ``` @(n){h(1:n,1:2:n*6)=1;h(1:n*4,n*2+1:2:4*n)=1;' #'(h+1)}{3} ``` [Try It Online!](https://tio.run/#imwsv) Generates a T shaped one ``` # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` [Answer] # Mathematica, ~~77~~ ~~60~~ 52 bytes *Thanks to Martin Ender for golfing 8 bytes away!* ``` {±s_:=s~Table~#;b=±{a=±"# "," "},±{a,a,a,a," "}}<>b& ``` Unnamed function taking a positive integer argument `#` and returning a string with newlines (including a trailing newline); each line has a trailing space as well. First we define `±` to be a function that repeats its input `#` times; then `a` is defined as `±"# "` (this `#` is a character, not the input!), and from that `b` is defined to be the set of `#` short lines, while `±{a,a,a,a}<>n` is the set of `#` long lines. (In both cases, there is a literal linefeed between matching quotes.) The final `<>b` concatenates the resulting list of strings with second copy of the set of short lines. Example output when `#=2` ([xnor's answer](https://codegolf.stackexchange.com/a/106824/56178) taught me that this orientation is golfier): ``` # # # # # # # # # # # # # # # # # # # # # # # # ``` Previous version of this implementation: ``` ""<>(±s_:=s&~Array~#;{b=±{a=±"# ",n="\n"},±{a,a,a,a}<>n,b})& ``` Original submission: ``` ""<>If[(m=n~Mod~t)==0,"\n",If[n<t#||#<m<=2#,"# "," "]]~Table~{n,4(t=3#+1)#}& ``` Builds a string out of `4*(3#+1)` pieces, each of which is either `"# "`, `" "`, or `"\n"`; simply calculates which pieces to use based on the index `n`. Example output when `#=2`: ``` # # # # # # # # # # # # # # # # # # # # # # # # ``` [Answer] ## JavaScript (ES6), 59 bytes ``` f= n=>`141`.replace(/./g,m=>`${`# `.repeat(n*m)}\n`.repeat(n)) ``` ``` <input type=number oninput=o.textContent=f(this.value)><pre id=o> ``` Output includes a trailing space at the end of each line and a trailing newline. [Answer] # Ruby, 36 bytes ``` f=->n{puts (t=[s="# "*n]*n)+[s*4]*n+t} ``` Usage: ``` f=->n{puts (t=[s="# "*n]*n)+[s*4]*n+t} f[3] # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` # Ruby, 38 bytes This shape is longer in Ruby but I expect there are some languages where it is shorter. ``` ->n{puts [s="# "*n*3]*n+[" "*n*4+s]*n} ``` Usage: ``` g=->n{puts [s="# "*n*3]*n+[" "*n*4+s]*n} g[3] # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` Both answers can be shorter if it is permitted to return (preferably) an array of strings or (less preferably) a single string instead of printing. [Answer] # Scala, 56 bytes ``` (n:Int)=>Seq(1,4,1)map("# "*_*n+"\n")map(_*n)mkString "" ``` [Answer] # JavaScript (ES6), 71 ``` n=>((z='# '[R='repeat'](n))[R](3)+` `)[R](n)+(' '[R](n)+z+` `)[R](n*3) ``` **Test** ``` f= n=>((z='# '[R='repeat'](n))[R](3)+` `)[R](n)+(' '[R](n)+z+` `)[R](n*3) function update() { O.textContent=f(I.value) } update() ``` ``` <input id=I type=number value=3 oninput='update()'><pre id=O></pre> ``` [Answer] # Java 8, 99 bytes ``` l->{for(int i=-1,j;++i<3*l;)for(j=-1,k=(i/l==2)?4*l:l;++j<k;)System.out.print("# "+j>k-2?"\n":"");} ``` [Answer] # [V](https://github.com/DJMcMayhem/V), ~~24~~ ~~23~~ ~~20~~ ~~18~~ 20 bytes ``` Ài# ddÀpLyGïp3PGïp ``` With all the hidden characters shown ``` Ài# ^[ddÀp^VLyGïp3PGoïp ``` `^[` is `0x1b` (escape character literal) and `^V` is `0x16` (`C-v`) [Try it online!](https://tio.run/nexus/v#@3@4IVNZQTol5XBDgZhPpfvh9QXGASDy////RgA) I had to increase bytecount because the `Ä` command was being buggy in this new V pull Outputs in this format: ``` # # # # # # ``` with a leading newline Hexdump: ``` 00000000: c069 2320 1b64 64c0 7016 4c79 47ef 7033 .i# .dd.p.LyG.p3 00000010: 5047 ef70 PG.p ``` ## Explanation ``` Ài# ^[ " Argument times insert "# " ddÀp " Argument times duplicate line ``` Now that one face of the net has been completed, we have to create the net ``` ^VLy " Copy the face Gïp " Paste it at the end of buffer 3P " Paste 3 times (these form the line) Gïp " Paste at end of buffer again ``` --- Alternate solution if we don't output the spaces: ### ~~21~~ ~~20~~ ~~18~~ ~~16~~ 18 bytes ``` Àé#ddÀpLyGïp3pGïp ``` (for the same reason as the top solution, this TIO link is modified) [Try it online!](https://tio.run/nexus/v#@3@44fBK5ZSUww0FYj6V7ofXFxgHgMj///8bAgA) [Answer] # [V](https://github.com/DJMcMayhem/V), 14 bytes (non-competing) ``` Ài# 5Ù4JjòÀÄk ``` [Try it online!](https://tio.run/nexus/v#@3@4IVNZQdr08EwTr6zDmw43HG7J/v//vwkA "V – TIO Nexus") ``` 00000000: c069 2320 1b35 d934 4a6a f2c0 c46b .i# .5.4Jj...k ``` For whatever reason, this challenge uncovered numerous bugs. Now that they're all fixed, this version is unfortunately non-competing, but it's nice to see what a V answer to this challenge should look like when it doesn't have to add tons of bytes to keep up with my sloppy coding. Explanation: ``` À " Arg 1 times: i# <esc> " Insert the string "# " 5Ù " Make 5 copies of this line, and put the cursor on the second copy 4J " Join four of these lines together j " Move down to the last line ò " Recursively: ÀÄ " Make Arg 1 copies of this line k " And move up a line ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ 19 bytes ``` ”#xẋ³Wẋ³K€Y 141DÇ€Y ``` [Try it online!](https://tio.run/nexus/jelly#@/@oYa5yxcNd3Yc2h4NJ70dNayK5DE0MXQ63g5j///83NAAA "Jelly – TIO Nexus") *-1 thanks to 44874 (steenbergh).* I CAN'T OUTGOLF MUDDYFISH HELP! Is this golfable??? ~~20~~ 19 bytes just seems like **too much**, seeing Link 1. Explanation: ``` ”#xẋ³Wẋ³K€Y Helper link. Arguments: z ”# Character #. y (implicit) x Repeat each element of y x times. ³ 1st command-line argument. ẋ Repeat x y times. W Wrap z. ³ 1st command-line argument. ẋ Repeat x y times. K Join z on spaces. € Map this link on x. Y Join z on newlines. 141DÇ€Y Main link. Arguments: 0 141 Integer 141. D Convert z to base 10. Ç The above link as a monad. € Map this link on x. Y Join z on newlines. ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` NλG↑λ←×⁶λ↓λ# DM×⁴λ← ``` The code ends with a space. [Try it online!](https://tio.run/nexus/charcoal#@/9@z7pzu9/vWf6obeK53Y/aJhye/qhxG4g1@dxuZYX3e5a837MWJLYFLKvw/78xAA "Charcoal – TIO Nexus") ### Explanation Charcoal is a language specializing in ASCII art. It is also incomplete, buggy, and under-documented. Suffice it to say, this took a fair amount of trial and error before it did what it was supposed to. * `Nλ` inputs a number into `λ`. * `G` is the polygon command, which we'll use here to draw a rectangle. `↑λ←×⁶λ↓λ` specifies the border of the polygon: upward `λ` steps, leftward 6 times `λ` steps, and downward `λ` steps. (That's three `λ` by `λ` blocks side-by-side.) The bottom edge of the rectangle is inferred. The polygon is then filled with the string `#` . * `D` dumps the current canvas to stdout, resulting in something like this: ``` # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` * After the `G` command, the cursor is at the bottom left corner of the canvas. `M×⁴λ←` moves it leftward by 4 times `λ` steps (equivalent to two `λ` by `λ` blocks). * outputs a space there, extending the canvas leftward by the correct amount. * At the end of the program, the canvas is (again) sent to stdout: ``` # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` Put 'em together and you've got a cube net. [Answer] # [Bash](https://www.gnu.org/software/bash/) / Unix utilities, ~~72~~ ~~69~~ ~~68~~ 66 bytes ``` b()(yes `dc<<<2o4d$n^$1^3/p`|tr 01 ' #'|head -$n);n=$1;b 1;b 4;b 1 ``` [Try it online!](https://tio.run/nexus/bash#@5@koalRmVqskJCSbGNjY5RvkqKSF6diGGesX5BQU1KkYGCooK6grF6TkZqYoqCrkqdpnWerYmidpADCJiD6////xgA "Bash – TIO Nexus") This works by using the fact that [4^k / 3], when written in base 2, is 10101010...01, with k 1's. (The square brackets here denote the floor function.) [Answer] # Pyke, 16 bytes ``` uAD,sXF**"# ``` [Try it here!](http://pyke.catbus.co.uk/?code=u%03%01%04%01AD%2CsXF%2a%2a%22%23+&input=2&warnings=0) Equivalent to ``` 1 4 1]3AD,sXF**"# ``` Because of unprintables This uses a couple of tricks to lower the byte-count: * It uses some unprintables to represent the list `[1, 4, 1]` * `XF` automatically dumps the output to the stack * The string `"#` at the end gets swapped with the last `*`, meaning that the closing `"` is not required. This happens implicitly when the last token is a string. ``` u - [1, 4, 1] AD - apply(*, ^, input) , - zip(^) s - sum(^) F**"# - for i in ^: * - ^ * input * - ^ * v "# - "# " X - splat(^) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~68~~ ~~71~~ 65 bytes -6 with thanks to @sagiksp ``` def f(i,c=1): print(' '*i*4,'')[c>i]+'# '*i*3 if i*2>c:f(i,c+1) ``` [Try it online!](https://tio.run/nexus/python2#@5@SmqaQppGpk2xrqGnFpVBQlJlXoqGuoK6VqWWio66uGZ1slxmrra4MFjHmUshMU8jUMrJLtgJr0jbU/J@mYar5HwA "Python 2 – TIO Nexus") In the absence of finding a way to beat @xnor I'll post my recursive function simply as an alternative approach. For f(5) prints ``` # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` This pattern was chosen simply because it can be split into two parts unlike all of the others. [Answer] ## PHP, 64 62 bytes Saved 2 bytes thanks to [Christoph](https://codegolf.stackexchange.com/users/29637/christoph). ``` while($a="282"[$i++/$s=$argv[1]]*$s)echo str_pad(" ",$a,"# "); ``` Prints a net like this: ``` # # # # # # # # # # # # # # # # # # # # # # # # ``` (with a leading newline) [Answer] ## Batch, 111 bytes ``` @set s= @set i=@for /l %%i in (1,1,%1)do @ %i%call set s=%%s%% # %i%echo%s% %i%echo%s%%s%%s%%s% %i%echo%s% ``` [Answer] # [Pushy](https://github.com/FTcode/Pushy), ~~32~~ ~~29~~ 28 bytes Prints the cube net left-justified. This was hard to golf... ``` &V:`# `;{:";N^:4:";T'.;TD^:" ``` [**Try it online!**](https://tio.run/nexus/pushy#@68WZpWgrJBgXW2lZO0XZ2UCpELU9axDXOKslP7//28CAA) [Answer] # [Retina](https://github.com/m-ender/retina), 39 37 bytes This is my first time using Retina, I'm still trying to understand how to do things. ``` .+ $*# # # \`# $_¶ G`. )*%`^ $_$_$_ ``` (with two trailing spaces after the 4th and 5th lines) Thanks to Martin Ender for golfing 2 bytes! [Try it online!](https://tio.run/nexus/retina#@6@nzaWipcwFhApcMQlAQiX@0DYu9wQ9Lk0t1YQ4IBcE//83AgA) [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~52~~ ~~67~~ 40 bytes Complete re-write: ``` :[a*3|G=G+@#`][a*2|G=G+@ `][a|?G][a|?_fG ``` This now uses this pattern: ``` ###-- --### ``` Where the `-`are filled with spaces. ``` : Read 'a' from the command line > Assume 3 [a*3| Create 3 segments times 'a' filling > 3*3 = 9 G=G+@#`] Define A$ to be '#' and add this to G > G = "#########" [a*2| Create 2 segments times 'a' spacer G=G+@ `] Define B$ to be ' ' and add this to G > G = "######### " [a| FOR d == 1; d <= a; d++ ?G] Display G$: "######### " "######### " "######### " [a| FOR e == 1; e <= a; e++ ?_fG Display G$ in reverse (_f...|): " #########" " #########" " #########" (For loop and function call to Flip impicitly closed by QBIC) ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~28~~ ~~17~~ 16 bytes 15 bytes of code, +1 for `-n` flag. ``` "# "Xa*_RLaM141 ``` Takes the size as a command-line argument. [Try it online!](https://tio.run/nexus/pip#@6@krKAUkagVH@ST6GtoYvj//3/dvP/GAA "Pip – TIO Nexus") ### Explanation ``` a is 1st cmdline arg _ Build a lambda function a* (a) times argument "# "X Repeat string "# " that many times RLa Wrap in a list and repeat list (a) times M141 Map that function to the characters of 141 Autoprint (-n flag separating list items with newlines) ``` The following isn't exactly how the data gets modified, but it gives the basic idea (for `a=2`): ``` 141 [1;4;1] [2;8;2] ["# # ";"# # # # # # # # ";"# # "] [["# # ";"# # "];["# # # # # # # # ";"# # # # # # # # "];["# # ";"# # "]] # # # # # # # # # # # # # # # # # # # # # # # # ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes ``` D141S×S*„# ×» ``` [Try it online!](https://tio.run/nexus/05ab1e#@@9iaGIYfHh6sNajhnnKCoenH9r9/78xAA "05AB1E – TIO Nexus") **Explanation** Example input `n=2` ``` D # duplicate input # STACK: 2, 2 141S # push the list [1,4,1] # STACK: 2, 2, [1,4,1] × # repeat each item in the list input_no times # STACK: 2, [11, 44, 11] S # split into list of digits # STACK: 2, [1, 1, 4, 4, 1, 1] * # multiply each digit with input # STACK: [2, 2, 8, 8, 2, 2] „# × # repeat the string "# " for each item in the list # STACK: ['# # ','# # ','# # # # # # # # ','# # # # # # # # ','# # ','# # '] » # join by newlines # OUTPUT: # # # # # # # # # # # # # # # # # # # # # # # # ``` [Answer] ## C#, 152 bytes ``` n=>{var m="";foreach(int c in new[]{1,4,1})for(int i=0,j;i++<n;){for(j=0;j++<c;)m+=new System.Text.StringBuilder().Insert(0,"# ",n);m+="\n";}return m;}; ``` [Answer] # SmileBASIC, ~~57~~ 50 bytes ``` INPUT S E$=("#"*S*3+CHR$(10))*S?E$SCROLL-S*2,-1?E$ ``` Explained: ``` INPUT SIZE PART$=("#"*SIZE*3+CHR$(10))*S 'generate half of the pattern PRINT PART$ 'print half the pattern SCROLL SIZE*-2,-1 'scroll the text 2 squares right (and 1 character down) PRINT PART$ 'print half the pattern again ``` After the first PRINT (size=2, @ is the cursor position): ``` ###### ###### @ ``` After the SCROLL: ``` ###### ###### @ ``` After the second PRINT: ``` ###### ###### ###### ###### @ ``` [Answer] # Common Lisp, ~~83~~ ~~81~~ 79 bytes ``` (lambda(x)(format t"~v@{~v@{# ~}~:*~%~}~v@{~vt~0@*~v{# ~}~%~}"x(* x 3)(* x 2))) ``` Usage: `(funcall #'(lambda(x)(format t"~v@{~v@{# ~}~:*~%~}~v@{~vt~0@*~v{# ~}~%~}"x(* x 3)(* x 2)))2)` Output: ``` # # # # # # # # # # # # # # # # # # # # # # # # ``` ### How does it work? ``` in format there is control string (inside "") and arguments after it certain commands in string can use arguments (for example ~a displays argument) ~v{~} - takes argument and does commends inside {~} number of times (number is given by argument) we can write text in loop body - it'll get displayed. Even if in loop body there are none commends to use arguments loop itself will consume one argument (it doesn't matter what it'll be - it doesn't seem to affect output) ~% - newline ~n* - jump n arguments forward (relative) ~n:* - jump n arguments backwards (relative) ~n@* - jump to argument n (global, counting from 0) ~v@{~v{# ~}~%~1@*~} <--- we make x rowns, 3x columns of string "# ". ~1@* is used during looping, it also means we end on argument 1. (second argument: (* x 3)) ~v@{~vt~0@*~v{# ~}~%~} <--- we now make 3x rows, x columns of "(spaces)# " ~vt - is used to move to accurate column. Here it takes argument (* x 2) - this is minimal number of columns to display. It uses space as default character for missing characters (when string inside <~> is shorter than min number of columns). I use it to make (* x 2) spaces, by giving it no text. ~0@* <--- after making spaces we have no new arguments, we go back to argument number zero - it is used to determine number of columns in our block ``` Ideas for improvement are welcomed. ]
[Question] [ An old test for programmers, taken from [here](https://www.facebook.com/notes/dario-dariol/il-pifferaio-magico/10157974434244334/) (Note: in italian). Along a road (denoted by '`_`'), there is a Magical Piper (denoted by '`P`') and several mice (represented by the two characters 'o' and '`~`', that denote respectively the head and the tail of the small rodents). Write a program that prints how many mice are going towards the Piper and how many mice are going away from him. The input is a string, the output are two numbers, the first the number of mice that go towards the Piper, the second the number of mice that go away from the Piper. The input can be also a list or vector of characters, and the output a vector or list of two numbers. You can assume that the input is always correct. Both programs as well as functions are allowed. Examples: input: `__o~P_o~~o` output: `1 2` input: `__P~oo~o~_o~~o__` output: `3 2` input: `~oPo~` output: `2 0` input: `o~P~o` output: `0 2` --- This is code golf, so the shortest program in any language wins. **Note:** In the question, I've removed the requirement of an error message, given the majority prefer it this way. Sorry for people that already coded the error test! [Answer] # [Ruby](https://www.ruby-lang.org/), ~~128 .. 51~~ 49 bytes ``` ->w{%w(o ~).map{|c|w.scan(/_*._*(.)/).count [c]}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1668WrVcI1@hTlMvN7Gguia5plyvODkxT0M/XksvXktDT1NfUy85vzSvRCE6Oba29n@BQlq0Unx8fl0AENflK8VyQUUC6vLz6/LrwKLx8Uqx/wE "Ruby – Try It Online") No error checking. ### How: * Ignore all underscores * All mice going towards the piper have the head in an odd-numbered (0-based) position. * All mice heading away from the piper have the tail in an odd-numbered position. * Take every 2nd character (skipping underscores), count heads and tails. # [Ruby](https://www.ruby-lang.org/) (with error checking), ~~109 99~~ 97 bytes ``` ->w{w.chars+w.scan(/[o~]./)-%w(o ~ _ ~o o~)==[?P]?%w(o ~).map{|c|w.scan(/_*._*(.)/).count [c]}:q} ``` [Try it online!](https://tio.run/##lY7NCoJAFIX3PcVFCJzCcS@Y25azH4aLDUqbvDYqg6j31U3KQNpUi7P5zg/HdZd@LtM5OvnBS3vNXXP0srF5Fcaa2MhYRHsfEjAgMAGxSFOdKZO9qJC3vB5GO75LeJB4CKWIhbTUVS1oa6bkPs01lDpAJFaLmAKzW4liIiZ@UsSFt66H1Tt/eOCKxnYF1F3bQFI4R24b306pH@L41zp@PzM/AA "Ruby – Try It Online") Thanks Value Ink for -2 bytes on both. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ ~~11~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` '_KāÈÏaTS¢ ``` Port of [*@GB*'s Ruby answer](https://codegolf.stackexchange.com/a/199033/52210), so make sure to upvote him!! -1 byte thanks to *@Grimmy* by taking the input as character-list. [Try it online](https://tio.run/##yy9OTMpM/f9fPd77SOPhjsP9iSHBhxb9/x@tFK@kA8YBQFwHxPlQXIdExyOxYeIQfbEA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn1l8H/1eO8jjYc7DvcnhgQfWvRf5398fH5dABDX5XPFxwfU5efX5deBufHxXHX5Afl1XED5unwA). **Explanation:** ``` '_K '# Remove all "_" from the (implicit) input-list ā # Push a list in the range [1, length] (without popping the list) È # Check for each whether it's even Ï # Only keep the characters at these even 1-based indices a # Check for each remaining character whether it's a letter or not # (1 if 'o'; 0 if '~') TS # Push 10 as digit-list: [1,0] ¢ # And count each in the list of 0s and 1s # (after which this pair of counts is output implicitly as result) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~80 66 65 58~~ 57 bytes Returns `[towards, away]`. ``` s=>Buffer(s).map(c=>c%3?i^=~c:a[c&1]+=++i&1,a=[i=0,0])&&a ``` [Try it online!](https://tio.run/##bYxBDoIwEEX33sPSpkgg7kwGE0/QPcFmUltTAwyh6nKuXglbWfzN@y/vhV9Mbonz@zTRw@cAOUF7@4TgF5lUNeIsHbTueL7GO7C7YOdE02vQOoqmROgi1GXdKyEwO5oSDb4a6CmDLKwlNuuYCqUOf6dhIibeBGt3FCZDvMPX6pbMPw "JavaScript (Node.js) – Try It Online") ### How? An efficient way to determine whether the character is a mouse body part is to take the ASCII code modulo \$3\$. Quite conveniently, we can also distinguish between `P` and `_` or between `o` and `~` by simply testing the parity of the corresponding ASCII codes. ``` character | 'P' | '_' | 'o' | '~' ------------+-----+-----+-----+----- ASCII code | 80 | 95 | 111 | 126 modulo 3 | 2 | 2 | 0 | 0 modulo 2 | 0 | 1 | 1 | 0 ``` ### Commented ``` s => // s = input string Buffer(s) // turn s into a buffer .map(c => // for each ASCII code c: c % 3 ? // if c modulo 3 is not equal to 0: i ^= ~c // invert the least significant bit of i if c is even // (must be 80, for 'P') : // else: a[c & 1] += ++i & 1, // update a[0] if c is even (126 -> '~') // or a[1] if c is odd (111 -> 'o') // increment i and add its parity a = [i = 0, 0] // start with a = [0, 0] and i = 0 ) && a // end of map(); return a[] ``` --- # [JavaScript (Node.js)](https://nodejs.org), ~~112~~ 102 bytes A version with error checking, as per the original rules of the challenge. ``` s=>Buffer(s).some(c=>n?n-=c:c-111&&c-126?c-95?c-80|p++:0:!++a[n=c^17,p^c&1],a=[n=0,p=0])|p-1?'error':a ``` [Try it online!](https://tio.run/##dczLCsIwEAXQvX/hpk1pUxrBVyAt@AXdSxtCTESpmZCoq5Jfr/GxUxczA3Mu9yzuwkt3slds4KAmzSbP6t1Na@WQz0oPF4Ukq01jMJNUYkJIksSzWDUSb5dxbarR5jmt6DzPxd4w2ZN1YXuZkK4QLD6qwrKqy0aLSZMq58ClVEwSjIdBlQMckUYp5xDaOAHSLJt9YRsAAoRXgPOfkY/@sXd3@1t5LH3S9AA "JavaScript (Node.js) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 47 bytes Port of [G B's Ruby answer](https://codegolf.stackexchange.com/a/199033/64121). ``` lambda s:map(s.replace('_','')[::2].count,'~o') ``` [Try it online!](https://tio.run/##HcgxDoQgEEDR3lNMN5AQC0sS72CvZoKuRBNlCGBhM1dn3S1@8V98ys6hq76f6umu5eMg28tFldu0xdOtm0JCg6hHa7u5XfkOxaAw6uo5QYYjABKxDG8vm98NwiwsfyFC2wDEdIQCXmVdvw "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~252~~ \$\cdots\$ ~~71~~ 72 bytes Saved 29 bytes thanks to [JoKing](https://codegolf.stackexchange.com/users/76162/jo-king)!!! Saved 2 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!! Saved a byte thanks to [ReinstateMonica](https://codegolf.stackexchange.com/users/85755/reinstate-monica)!!! Saved 21 bytes thanks to [KevinCruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!!! Added a byte to fix a bug kindly pointed out by [JoKing](https://codegolf.stackexchange.com/users/76162/jo-king). ``` def f(s): r=[0,0];i=0 for c in s: if'_'!=c:r[c>'o']+=i;i^=1 return r ``` [Try it online!](https://tio.run/##HY6xDsMgDETn8hVuFhI1A@1IRL@BPUoZaFBZcARk6OJfp6aWrJNP93Q@vvWD6dHaew8QxjJpAdmsalbbEo0SEDCDh5igaHGJQTp5NV7n1T8lyu1m4hJf5s7QXs@cILcOlA4MziFZXsJh5sMSIiH9DefYIrRIrJziCBfzHDmmOvZHpvYD "Python 2 – Try It Online") Inputs a string and outputs a list. [Answer] # [J](http://jsoftware.com/), ~~27~~ 19 bytes ``` [:+/_2=&'~'\'_'-.~] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o6209eONbNXU69Rj1OPVdfXqYv9rcnGlJmfkKxgqGCnoWimkKajHx@fXBQBxXb46RMoYSSqgLj@/Lr8OLB0fD1VgBLIDrKAuPyC/DipqANcGNA9o2H8A "J – Try It Online") This took inspiration from both [Kevin's answer](https://codegolf.stackexchange.com/a/199044/15469) and [GB's answer](https://codegolf.stackexchange.com/a/199033/15469). ## how We'll work through an example: `__o~P_o~~o` * `'_'-.~]` Remove the underscores: ``` o~Po~~o ``` * `_2=&'~'\` For every two characters, create a boolean mask where 1 indicates that the character in that position is `~`: ``` 0 1 o~ 0 0 Po 1 1 ~~ 0 0 o ``` * `[:+/` Sum the colums: ``` 1 2 ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 31 bytes ``` +`o~(?!o) 1 T`1~`~1`.*P *\C`1 ~ ``` [Try it online!](https://tio.run/##K0otycxLNPz/Xzshv07DXjFfk8uQKyTBsC6hzjBBTyuASyvGOcGQq@7///j4gLr8/Lr8uvj8urr8@HgA "Retina – Try It Online") ### Explanation ``` +`o~(?!o) 1 ``` Recursively replace all mice walking to the left with a `1`. Mice walking to right stay as they are. ``` T`1~`~1`.*P ``` Swap `1` and `~` at all positions up to the `P`. ``` *\C`1 ``` Every `1` stands for a mouse walking towards the Magical Piper. Count the `1`'s and output the result without changing the current string. ``` ~ ``` Count `~`'s (implicit output). every `~` stands for a mouse walking away from the Magical Piper. --- # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~23~~ 18 bytes port of [G B's Ruby answer](https://codegolf.stackexchange.com/a/199033/64121). 5 bytes shorter thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil). ``` _ (.). $1 *\C`~ o ``` [Try it online!](https://tio.run/##K0otycxLNPz/P56LS0NPU49LxZBLK8Y5oY4rHygWH1CXn1@XXxefX1eXHx8PAA "Retina – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org/en/), ~~57~~ 54 bytes ``` s=>Buffer(s).map(c=>a[~c&1]+=c%19&&i++%2,a=[i=0,0])&&a ``` Alternative JavaScript answer for [the existing JavaScript answer](https://codegolf.stackexchange.com/a/199034/52210) ~~(of equal byte-count at time of writing)~~, which I figured was worth posting as separated answer. Loosely based on [my Java 8 answer](https://codegolf.stackexchange.com/a/199049/52210) and inspired by [*@GB*'s Ruby answer](https://codegolf.stackexchange.com/a/199033/52210). -3 bytes thanks to *@Arnauld*. [Try it online.](https://tio.run/##bYwxDoMwEAT7/ANjywRBuhRHkRe4R8g6OXbkiHAIB8r7uoNoQ7HN7GjeuGFyS5y/14mePgfICbrHGoJfZFL1B2fpoMOenWgHDa5o70JErYtbhdBHaKpmUEJgdjQlGn090ksGWVpLbPYxlUpd/k7DREx8CNaeKEyG@ITv1SOZfw) **Explanation:** ``` s=> // Method with string as parameter and integer-array as result Buffer(s).map(c=> // Loop over the characters in the String as codepoint integers: a[~c&1]+= // Increase the count at index (c+1)%2 by: c%19&& // If c modulo-19 is NOT 0: i++%2, // Add i%2 to the count, and increase i by 1 afterwards a=[i=0,0] // Start the counts at [0,0] and i at 0 )&&a // After the loop, return this resulting pair of counts ``` The codepoints of the four used characters are `'P'=80, '_'=95, 'o'=111, '~'=126`, which I'm using to my advantage: * The `~c&1` will result in index `0` for the character `'o'` and index `1` for character `'~'`. (It will also result in index `1` for character `'P'` and index `0` for character `'_'`, but this won't cause any issues.) * The modulo-19 is to ignore `'_'` characters. Using the modulo-19 on the four codepoints results in `4,0,16,12` for `P_o~` respectively, for which the `'_'` is falsey and the other three are truthy. The `i++%2` will only add `1` to the count for odd-indexed characters. All even-indexed characters won't affect the counts. Since the `'P'` is guaranteed to be at an even-indexed position (when ignoring the `'_'` with `c%19&&`), the count for character `'P'` will always increase by `0`, and thus stay the same. [Answer] # JavaScript (ES6) Port of [G B's Ruby answer](https://codegolf.stackexchange.com/a/199033/64121). ``` a=>a.filter(v=>v!='_').map((v,i)=>i%2||v=='P'?0:a[+(v=='o')]++,a=[0,0])&&a ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~ 87 ~~ 85 bytes *Saved 2 bytes thanks to [@xibu](https://codegolf.stackexchange.com/users/90181/xibu)* Prints the results as `towards away`. ``` a,b,p;f(char*s){for(a=b=p=0;*s;s++)*s%3?p|=~*s:p+*s++&1?b++:a++;printf("%d %d",a,b);} ``` [Try it online!](https://tio.run/##bYxNCoMwFIT3niIELPlRaOnOELyCNwgxohVaXzC2XVjf0ZsGoTsXA8PMx@fKwbkYbdEWXvXM3ewsAl97mJnVrfb6rERQQUouQn6t/UejCJWXIk2nS91KWVkplZ/HaekZzTuSd7RIOq62@IKxIw87ToyTNSMkAcYANikIlCvin0tgNLX/2SAAAu6AMQcIQgN4sCfrrsy2@HX93Q4hlu8f "C (gcc) – Try It Online") ### Commented ``` a, // a = 'towards' counter b, // b = 'away' counter p; // p = piper flag f(char *s) { // f is function taking a pointer to a string s for( // main loop: a = b = p = 0; // start with a = b = p = 0 *s; // go on while the end of the string is not reached s++ // advance the pointer after each iteration ) // *s % 3 ? // if the current character is not a mouse body part: p |= ~*s // set the piper flag if the ASCII code is even (80 -> 'P') : // else: p + *s++ & 1 ? // test the parity of (p + current ASCII code) and advance // the string pointer to skip the next body part // if odd: b++ // increment b : // else: a++; // increment a printf("%d %d", a, b); // print the results } // ``` --- # [C (gcc)](https://gcc.gnu.org/), ~~ 72 ~~ 70 bytes *Saved 2 bytes thanks to [@mypronounismonicareinstate](https://codegolf.stackexchange.com/users/36445/my-pronoun-is-monicareinstate)* This version saves the results in an array passed as a 2nd argument. I don't know for sure if it's acceptable. ``` p;f(char*s,int*r){for(*r=r[1]=p=0;*s;s++)*s%3?p|=~*s&1:r[p^*s++&1]++;} ``` [Try it online!](https://tio.run/##lU7RCoJAEHz3K45A8U4FrbcO6Rd8t0vkRBPKPfaiHsz79K6zKHq0hV3YnZmdkUknpbWKt6E81sh03A8XhnRsAUOGOZaZyFWecqa5jiLKtL/ZqXtumA6yLZbqwNw5yEQU8cleoW/Iue6HkJLRI8T9IliuBffc0oarqgJTuDawism7kHKi0BEd7DfEb/aDw7BMxTwzQflHWhgAA@Ylr6qZtFBqoADzNfzL1cX9ybpUOtmHbE91p21yewI "C (gcc) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes ``` 'P¡`RJ'_K2ô„~o‚¢ ``` [Try it online!](https://tio.run/##ATMAzP9vc2FiaWX//ydQwqFgUkonX0syw7TigJ5@b8OC4oCawqL//19fUH5vb35vfl9vfn5vX18 "05AB1E – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 25 bytes ``` 80&Yb"@g'o~'&mXz2eq!Xs]P+ ``` [Try it online!](https://tio.run/##y00syfn/38JALTJJySFdPb9OXS03osootVAxojg2QPv/f/X4@IC6/Py6/Lr4/Lq6/Ph4dQA "MATL – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 14 bytes ``` /J%2-z\_\~/J\o ``` [Try it online!](https://tio.run/##K6gsyfj/X99L1Ui3KiY@pk7fKyb////4@IC6/Py6/Lr4/Lq6/Ph4AA "Pyth – Try It Online") A port of [@GB's wonderful Ruby answer](https://codegolf.stackexchange.com/a/199033/64121), go give him your upvotes! Terrible explanation: ``` / \~ // Count the occurrences of "~" in: J // J= %2 // Every second character of -z\_ // every character of the input not in "_" // Implicit print /J\o // Count the occurrences of "o" in J // Implicit print ``` [Answer] # Python 3.8, 62 bytes ``` lambda s:((v:=s.replace("_","")[::2]).count("o"),v.count("~")) ``` You can [try it online](https://tio.run/##K6gsycjPM7YoKPqfpmCrEPM/JzE3KSVRodhKQ6PMyrZYryi1ICcxOVVDKV5JR0lJM9rKyihWUy85vzSvREMpX0lTpwzGqVPS1PxfUJQJZKcBlcfX5dflB@SDRQE). Link has two extra bytes to give a name to the function. Port of [this](https://codegolf.stackexchange.com/a/199033/75323) Ruby answer, so be sure to upvote it as well! [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 11 bytes ``` '_;;\[2enf: ``` [Try it online!](https://tio.run/##SyotykktLixN/f9fPd7aOibaKDUvzer///j8urr8gPi6/Pw6AA "Burlesque – Try It Online") Using the algorithm of [G B's answer](https://codegolf.stackexchange.com/a/199033/91386) # Burlesque, 24 bytes ``` 'P;;^p<-_+'_;;m{2co}FLf: ``` [Try it online!](https://tio.run/##SyotykktLixN/f9fPcDaOq7ARjdeWz3e2jq32ig5v9bNJ83q///4/Lq6/ID4uvz8OgA "Burlesque – Try It Online") Without error checking. ``` 'P;; # Split at P ^p<- # Reverse those following the piper _+ # Rejoin '_;; # Remove all road m{2co} # Split each into pairs (i.e. mice) FL # Flatten array f: # Count mice ``` # Burlesque, 44 bytes ``` 'P;;sa2!=qpPif^p<-_+'_;;m{2co}FLf:sa2!=qpPif ``` [Try it online!](https://tio.run/##SyotykktLixN/f9fPcDaujjRSNG2sCAgMy2uwEY3Xls93to6t9ooOb/WzSfNCiH7/398fl1dfkB8XX5@XQAA "Burlesque – Try It Online") With error checking. As above but with checks to see if lists are correct lengths and throw impossible action if not, halting execution. [Answer] # Jelly, ~~14~~ ~~[13](https://tio.run/##y0rNyan8///hjvmPGubGH9rqpWp0ePqR7kcb1z1qmFOX//9w@6OmNf//RyvF1@Xn1wXEx@fXKekoQHkQdl1@QF2@UiwA)~~ 10 bytes A monadic link taking the string as input. ``` ḟ”_m2ċⱮ⁾~o ``` You can [try it online](https://tio.run/##y0rNyan8///hjvmPGubG5xod6X60cd2jxn11@f8Ptz9qWvP/f7R6fF1@fl1AfHx@nbqOApQHYdflB9Tlq8cCAA). Port of [this](https://codegolf.stackexchange.com/a/199033/75323) Ruby answer so check it as well! ``` ḟ”_ remove all the underscores from the string m2 Then take a slice modulo 2 and for what remains Ɱ“~o go over the characters ~ and o ċ counting how many times they show up. ``` Output is `[towards, away]`. *-3 bytes* thanks to @Jonathan and @Nick. [Answer] # [PHP](https://php.net/), 108 bytes ``` for(;$b=$argn[$j++];){$b!='P'?:$p++;$b=='~'?($p&++$j?$m++:$n++):($b!='o'?:($p&++$j?$n++:$m++));}echo"$n $m"; ``` [Try it online!](https://tio.run/##RcpBCsIwEEbhq2j5MQ2DF0gM2bnuXiRYUWuhmaG6E@foxtSNm7f5ngxSdlFqrzy3Hn3Aab7lA0aio7cv9OtgOhMdhGjhYNTEFrIhwhgxETlkIuva38p1/WtetC7W@vflPHCDvMLU@FJS6pRZWROrckoflued86Ns918 "PHP – Try It Online") Back to more serious golfing, ends like a port of Noodle9's original answer (but much more readable) **ORIGINAL VERSION:** # [PHP](https://php.net/), 156 bytes ``` $a=explode('P',$argn);for($i=2;$i--;$j=0)for($b=$a[$i];$b[$j];){$t=$b[$j].$b[++$j];if($t=='~o')$i&++$j?$n++:$m++;if($t=='o~')$i&++$j?$m++:$n++;}echo"$n $m"; ``` [Try it online!](https://tio.run/##TYqxCsIwGIRfRcphGmJFHI2hm3P3UkKrrabY/KF2EMQ8ujFVEJe74/vOXVzY5y4matXe3ZVObcoKtkI9ni2XHY0pjNpKmCyT6NWGf1CjUJcwlURToq8kf2BS372OJcQMTZdGqpgnxmGWM8xhhdhhEOJnyf/ZYbbxIp/t8UIJ7AJDIkPQuvBEnrwm70nrF7nJkL2F7PAG "PHP – Try It Online") Ok, this is really horrible and far from optimal, but I had real fun writing this unreadable atrocity. Forgive me :D (the reason behind the explode was to check validity for original post rule of only one `P` in the string) **EDIT: ORIGINAL VERSION WITH ERROR CHECKING (displays `0` on error)** # [PHP](https://php.net/), 213 bytes ``` $a=explode('P',$argn);for($i=0;isset($a[$i]);$j=0,++$i<3?:die(0.))for($b=$a[$i];$b[$j];){strpos(" _~o",$b[$j])?:die(0.);$t=$b[$j].$b[++$j];$t=='~o'?($i&$j++?$m++:$n++):($t!='o~'?:($i&$j++?$n++:$m++));}echo"$n $m"; ``` [Try it online!](https://tio.run/##RY3BCsIwEER/RctisqRKwVtjyM2zd5FSNWqKZkOTgyDm063Rgh52F2bezPqLH1ba5w2tMnd/paPhbMNKaPuzQ3minoNVlbQhmMih3YLdoYROVaUQYFdLXR@t4dUC8cvu1chI2G@h20l8hNh7CryYNImKcpTxl5IQ1agt8smVOZMlxRIxnV/PoBNCw02IGpwQWHOIU8UoMV3/bfexM4Mon@ZwoQLcBG6FHIamobTJk@hFPlpyYZiv3w "PHP – Try It Online") **Caveat**: won't display the zero results, but `,$n=0,$m=0` can be added after `$i=0` to make it so. [Answer] # [GolfScript](http://golfscript.com), ~~46 bytes~~ 36 bytes ``` 1/{"_"=!},'P'%~-1%+2/.{"~o"=},,.@,\- ``` Significant improvement from my previous algorithm. Enough so that I'm willing to actually explain it. ``` 1/ #Split the string into an array of chars {"_"=!}, #Replace the prev array with one without underscores 'P'%~ #Split the array at the piper -1% #Reverse the second array (right side) #This has the function of making all correct mice #face the same way, which makes for easier matching + #Concatenate 2/ #Split the array into groups of two #so we only an array of mouse-strings! . #Duplicate our array, since we have to count twice {"~o"=},, #First count all valid mice . #Duplicate that count @, #Bring back that second array and count the mice \- #Subtract (correct mice) from (all mice) #which only leaves (correct mice) then (wrong mice) ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~46~~ 42 bytes *Inspired by [G B](https://codegolf.stackexchange.com/a/199033/80745)* ``` $a=,0*7 $args|%{$a[$i++%2+$_%6]++} $a[4,1] ``` [Try it online!](https://tio.run/##VY/dCoJAEIXv9ymGZSxtNzCLgkDwEbyXWKS2HxDG1ChQ99VtW7KfA3Mz5ztzmJLuuqrPuigGPEIM7YB5LMPZhmFenerOazHP8CKEFwlU3nonRG@tbCUXu6FnLPEZWEl/qhSZ1I6hqYRRCwlR8CVSQ2TIOEopxy1/CUMpmZ@4UyQh/BC246/AKXQ3AujAg9aRWFF@kID6Uep9ow/2M1RvR9e3orGLiX04eXFuz9Hnb4/P9ZV/ojzYjiHO@uEJ "PowerShell – Try It Online") ``` | ascii | %6 | even | odd ----------------------------- P | 80 | 2 | 2 | 3 _ | 95 | 5 | 5 | 6 o | 111 | 3 | 3 | 4 ~ | 126 | 0 | 0 | 1 ``` The 4 and 1 are `odd-numbered positions` from the `G B` answer. No error checking. --- # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 46 bytes ``` switch($args|?{$i++%2}){o{$t++}~{$a++}}+$t;+$a ``` [Try it online!](https://tio.run/##VY/dCsIwDIXv9xShRLfRCjrvFHGPsDcoQ6sbDDK3yoSuffVZiz/zQAicfCchLQ2q6yvVNBNe4ABm6odan6oEy@7aj0eDNeeLzKaGDGrOrTNY@mY56j3HcrJRlCcReIkklpJc4ctRLOCjjYAs/RGFI3LkAiVl4LZzwlFBbhYPygSsv4S/8XcgaB12pDDCAkwgsaPyLADVo1Unrc7@O5TviervjfbG0j@dv7jgM0zYe8ZW6sa@UZbuPiEW2ekJ "PowerShell – Try It Online") [Answer] ## [Unix TMG](https://github.com/amakukha/tmg), 115 bytes ``` p:ignore(<<_>>)r<P>[a=^t][t=^a][a=^t]r parse(d);r:<o~>[t++]r|<~o>[a++]r|();a:0;t:0;d:decimal(t)decimal(a)={2< >1}; ``` Expanded: ``` p:ignore(<<_>>)r<P>[a=^t][t=^a][a=^t]r parse(d); r:<o~>[t++]r|<~o>[a++]r|(); a:0; t:0; d:decimal(t)decimal(a)={2< >1}; ``` [Answer] # [Python 3](https://docs.python.org/3/), 86 bytes ``` m=input() n=m.index('P') c=count t=m[:n].c('~o')+m[n:].c('o~') a=m.c('~')-t print(t,a) ``` [Try it online!](https://tio.run/##HYsxDoAgDAB3PlIalcWNhD@4EweDJjLQElMSXfg6ouPl7vIjJ9PcWnKRchGNilwykfbj1rAAquACFxIlLnlLqwkaKgMOyZP9iWuvtj59BnASla9IomXcsLUX "Python 3 – Try It Online") Takes in the string, and finds the location of the Piper. Then just counts the number of mice behind him facing forwards, plus the number of mice ahead of him facing backwards - this is the total number of mice facing towards him. The number of mice facing away is just the total number of mice (the total number of '~'s) minus the number facing him. Uses c to replace the count function, for byte saving. [Answer] # Java 8, ~~72~~ 71 bytes ``` s->{int i=1,r[]=new int[2];for(int c:s)r[~c&1]+=c!=95?i^=1:0;return r;} ``` Port of [*@GB*'s Ruby answer](https://codegolf.stackexchange.com/a/199033/52210), so make sure to upvote him!! -1 byte thanks to *@Arnauld*. [Try it online.](https://tio.run/##VVBRS8MwEH7frzj7IClzwQo@2BJFfHYU9jhqiVmmqV0yknQyRvPX6zV16AIJd993992Xa/iBL5rN1yBa7hy8cqVPMwClvbRbLiQsxzQC6woEEZ/cYuDSAuF@ho/z3CsBS9DAYHCLxxPWgmLZDRYyLb9j711VbI0lIyVyl9p1ENdZNWfiij3cP6k3luW3hZW@sxps0Q/FKL3v3luU/p1wMGoDOzRIVt4q/YE2eDq589J5ktS1CSXeYJJo7w8vgzHBhMjV9SUbTGnCJYQyZ43/X4wGYsVkALcwjV8dnZc7ajpP90j4VhM3T3JI5g2ul3ZetfTZWn501Jupl2gqyJi@4EIjR1I808h@@AE) **Explanation:** ``` s->{ // Method with char-array parameter and int-array return-type int i=1, // Toggle integer, starting at 1 r[]=new int[2]; // Result int-array of size 2, filled with 0s by default for(int c:s) // Loop over the input char-array: r[~c&1]+= // Increase the count at index (c+1)%2 by: c!=95? // If the character is NOT '_': i^=1 // Toggle the integer (1→0 or 0→1), and add that to the current count // this will only add 1 for every odd-indexed character, ignoring '_' : // Else: 0; // Keep the count the same by increasing with 0 return r;} // And finally return this resulting pair of counts ``` [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), 18 bytes ``` {+/2!0N 2#0,x^"_"} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/Nqlpb30jRwE/BSNlApyJOKV6p9n@JVbVKdGVdkVWaQoV1Qn62tUZCWmJmjnWFdaV1kWZsLVdJtFJ8fH5dABDX5StZGyoYxULEAury8@vy68Di8fFK1sZQmbr8gPw6JWsjBQMwF6gVpM8AKPsfAA "K (ngn/k) – Try It Online") `{` `}` function with argument `x` `x^"_"` remove all `_`s `0,` prepend a `0` `0N 2#` split in pairs `2!` mod 2 as ascii codes: `P`→80→0, `o`→111→1, `~`→126→0 `+/` sum [Answer] # [C++ (gcc)](https://gcc.gnu.org/), [189](https://null.link.io/ "-5 bytes thanks to @ceilingcat") [184](https://null.link.io/ "-14 bytes when inspired by @Arnauld 's answer") 170 bytes ``` #include <string> struct a{int t;int f;};a f(std::string s){a r={0,0};for(int i=0,d=1;i<s.length();++i)s[i]%3?s[i]%2?1:d=0:s[i++]%2?d?r.f++:r.t++:d?r.t++:r.f++;return r;} ``` [Try it online!](https://tio.run/##zZRRT9swEMff8ylum6YmTSlJQYLFDX3apD1MQhpvXVUZx2ktWjtyHLGqNF@dnZPQEloYEmIaoMR397fv/zuXsiw7mjF2/0lItigSDkOhcqM5XV44RS7kDCRd8jyjjENuEvJIiDKsXzj4LpgBuhbSgCH2mZINoZC6uCOKah3k3pqCjtdBL9iQVGnXCkUc9JI4JGKY9xdczszc9YjvCy8fi8nnk1H1GozCKImDCAPft2Ey0v3U9yPdN/i0kakizBHNTaElaLK5P@46P2@FYXO4pStwB@EJXK8Mzz2I3sl01c21pr01ozmH88A6J9c40BtSZTqqE6GWuIn3mKIlKWtJG6wWbHZ8jnPFtaR6VeOF56fvjYdccXwejJrLwABpRljqtW@kqZW72hYjCslBAmHmwOZUW46zt3FUx7CXcVicj9HbxGNbIPYcDXsdynfDNTVKP9zGl7dRWJG1bTFoYRRy5P1rPhMS7YsPGHCZNBfTFVsKuzyMUVVewREf@nHufqikITsLGrI7RDus/l@/EpzusePYJktq5whrB6DxImRWGILxjJuFkNxlQvbqrGfTaJSaKVMF7o6RY1fBnIHhcFfvV@FH/G1lU@LgeI@78PU3XWYLjiZubOdsZeZK4jEJdxKeQoZ@TKNx6wnYDxGAwMaBbahVnvNkmomMa8x9o4ucY34p8Es6HuM0JxjdzgX2EDCE@gw4gkF1DLIwI7BjjOZkopZ9@8KebtA79SqBSLcabNnsgtqZ25l2eoAfPog7Ha@pCPBjCKuAL1q7Q8DDQSrTtv3kyMv9I59SXumC/7XbYOvVDmMcTHbKimrPx1a/tVKqfS8cB7yvVOUzgxgcsnbSthY@tfZvbL0wg/ZVNJub5C@J2WakvQcAD/@d7lWpylLZ53Rary5xraY2ntoVrvGvWtr6Hw "C++ (gcc) – Try It Online") Expanded Version (Full Program) : ``` // Example program #include <iostream> #include <string.h> using namespace std; struct pseudo_arr {int to_piper; int from_piper;}; pseudo_arr countRats(string s) { pseudo_arr rats = {0,0}; int direction = 1; for(auto i = s.cbegin();i!=s.cend();++i) { // Exploitable properties of the 4 characters // 'P' == 80 - %3 == 2, %3 == 0 // '_' == 95 - %3 == 2, %2 == 1 // '~' == 126 - %3 == 0, %2 == 0 // 'o' == 111 - %3 == 0, %2 == 1 switch(*i) { case 'P' : // char(80) == 'P' direction = 0; // Crossed piper, change direction break; case 'o' : // If see head, skip tail ++i; // if before piper then away, else towards direction ? rats.from_piper++ : rats.to_piper++; break; case '~' : // if see tail, skip head ++i; // if before piper then towards, else away direction ? rats.to_piper++ : rats.from_piper++; break; } } return rats; } int main() { string input; getline(cin, input); pseudo_arr rat_count = countRats(input); cout << rat_count.to_piper << " " << rat_count.from_piper; } ``` [Answer] # [Z80Golf](https://github.com/lynn/z80golf), 28 bytes ``` 00000000: 1680 cd03 8030 0578 ff79 ff76 fe5f 28f0 .....0.x.y.v._(. 00000010: 1930 ed0c fe7e 28e8 0d04 18e4 .0...~(..... ``` [Try it online!](https://tio.run/##rYw7DgIxDER7TjHlVpbDfuLlFHsDF5uEBskdAgpfPSRAwQH2jTTVzHsJX@1WauUfF4RFGHviEcIjg@coKCWuvRaUPBecpTBAHaYHPelOOtDpawjdsbZnTry3fcxtnwWceEKQPOGP9ify4aOqVXVzMzdXczdVt2NykMbf "Z80Golf – Try It Online") ``` start: ld d, $80 call $8003 jr nc, ok results: ld a, b rst $38 ld a, c rst $38 halt ok: cp '_' jr z, start add hl, de jr nc, start inc c cp '~' jr z, start dec c inc b jr start ``` Prints two bytes: `towards` and `away`. One maybe-clever trick here is using `add hl, de` as a sort of flip-flop mechanism. Since `de` is fixed to `$8000`, it will overflow and set the carry flag every other time. ]
[Question] [ Write a program or function that, given an integer `n`, construct an array with `n` dimensions of `n` length, where each element is an identifier of its own coordinates. That is, starting with one array, populate it with `n` arrays, where each of those contain `n` more arrays, up to a depth of `n-1`. The elements of the deepest arrays are the coordinates describing where they are in the full array. Some examples in case my explanation was confusing. ### n = 1 ``` ["1"] ``` ### n = 2 ``` [ ["11", "12"], ["21", "22"] ] ``` ### n = 3 ``` [ [ ["111","112","113"], ["121","122","123"], ["131","132","133"] ], [ ["211","212","213"], ["221","222","223"], ["231","232","233"] ], [ ["311","312","313"], ["321","322","323"], ["331","332","333"] ] ] ``` Here, "321" means it is the 1st element of the 2nd element of the 3rd array. ### Rules: * Coordinates and dimension (`n`) can be either 0 or 1 indexed * You may assume `n` is single digit, below 10 for both indexing options to prevent ambiguous outputs * IO is flexible. + In particular, coordinates can be arrays, strings etc. as long as they are clear. "321" => [3,2,1] + Output can be integers in base 10 with or without leading zeroes. + Coordinates can be in reverse order if you wish, as long as it is consistent. "321" => "123" + Output doesn't necessarily have to be an array structure in your language. As long as there's clear distinct markers for the start of an array, end of an array and for separating elements. + The output for `n=1` can just be 1 + If your output is atypical, make sure to explain the format. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest solution in each language wins! [Answer] # [Dyalog APL](https://www.dyalog.com/), ~~5~~ 3 bytes ``` ⍳⍴⍨ ``` -2 bytes thanks to [FrownyFrog](https://codegolf.stackexchange.com/users/74681/frownyfrog) [Try it online!](https://tio.run/##SyzI0U2pTMzJT/@v8ahvql/wo941mnqPevvUgTznSHX14sScEnX1R90tQH6wq16os68LkNs2ISm/QiE/D8jsWpyal5iUkxrs6BMCUta7Rl3hUe9chYKi1JKSSgWgutRihcSi/NK8FIWSjFSF/NKSgtKS/2lAMx71bn7Uu@VR74r//9MUDLnUdXV11bnSFIzgLGM4ywQA "APL (Dyalog Unicode) – Try It Online") `⍳` gives all the indices given the shape of an array. e.g. [2 3](https://tio.run/##SyzI0U2pTMzJT/8PBI96NxspGAMA). `⍴` reshapes the right arg to be the size of the left arg. `⍨` makes both be the right arg. [Answer] # [Python 3](https://docs.python.org/3/), 56 bytes ``` f=lambda n,*l:len(l)//n*l or[f(n,*l,k)for k in range(n)] ``` [Try it online!](https://tio.run/##FcgxDoAgDADAr3RsCQkDm4kvMQ4YqRJqIQ2Lr8d44/V33E3jnLxKeo4zgXoni2RFoRDUCTTbGP/1lbgZVCgKlvTKqLTPbkUHMkai@QE "Python 3 – Try It Online") Mr. Xcoder saved 2 bytes switching to Python 3 for starred unpacking. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~32~~ 22 bytes -10 bytes thanks to @alephalpha ``` Array[List,#~Table~#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8d@xqCixMtons7hER7kuJDEpJ7VOOVbtv6Y1V0BRZl5JdJqDso6CUkyeUqyavkM1F5ehDpeRDpcxF1ftfwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [J](http://jsoftware.com/), 18 bytes ``` ,"1/^:(]{:)~@,.@i. ``` [Try it online!](https://tio.run/##y/qfkq8Qb6iQUpRfoKCeZqunrqOQl1@ap5CSmpaZl/pfR8lQP85KI7baSrPOQUfPIVPvvyYXV2pyRr5CmoIhhGGpoq6rDhMzwiJmjCFmo2QIFDfh@g8A) Iterative solution, no built-in cartesian product. This is what peak J looks like. ``` input 2 i. range 0, 1 ,.@ reshape each element into a one-dimensional array [0],[1] (A) ^:(]{:) (input−1) times... (1 iteration) ,"1/ ~@ prepend the contents of each 1d array in A | to every 1d array from the previous iteration,| assembling the results for each A[n] into |!CANTEXPLAINTHIS! a larger array | [ [0,0], | [0,1] ], | [ [1,0], | [1,1] ] | ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 bytes ``` ṗ³s³$³¡ ``` [Try it online!](https://tio.run/##ARgA5/9qZWxsef//4bmXwrNzwrMkwrPCof///zI "Jelly – Try It Online") **Explanation** Use argument 2 as an example. ``` ṗ³s³$³¡ ṗ Cartesian power with power ³ 2 (the argument). Autoranges the left arg. Yields [[1,1],[1,2],[2,1],[2,2]] $³¡ Do 2 times: s³ Split into segments of length 2. This last step molds the array of indices into the proper shape. ``` --- If `¡` didn't vary it's right argument over iterations for dyads then this would be 4 bytes: `ṗs³¡` [Answer] # J, 13 bytes ``` [:{[;/@$,:@i. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o62qo631HVR0rBwy9f5rcnGlJmfkK6QpGEIY6rq66jAhI0whY67/AA "J – Try It Online") Interesting this is so much longer than the APL answer (though that may be my inability to see a better translation) ## explanation ``` [: { [ ;/@$ ,:@i. [ NB. the argument ,:@i. NB. range 0..arg, considered as one item: ,: is "itemize" $ NB. repeat the right range the left number of times ;/@ NB. and then put boxes around them. so, eg, if we had NB. an arg of 3, now we have the list of boxes NB. [0 1 2][0 1 2][0 1 2] [: { NB. { is "Catalog", it creates the cartesian product NB. in exactly the format we desire. ``` [Answer] ## MATLAB, 92 89 55 bytes I have a different answer having re-read the rules of the challenge, but I'll leave the previous attempt below as it's different and still fun to look at. ``` reshape(string(dec2base(0:n^n-1,n+(n<2))),[~(1:n)+n 1]) ``` **Explanation** ``` 0:n^n-1 % [0,1,...,n^n-1] dec2base( ,n+(n<2)) % Put into base n (base 2 if n=1) string( ) % Convert to strings [~(1:n)+n 1] % Dimension array [n,n,...,n] (length n) reshape( , )% Use dim array to reshape ``` This outputs an n-dimensional array of strings which are 0 indexed. **Previous Answer (89 bytes)** My first golf! This can likely be reduced more but I thought I'd post what I've got. ``` x=(1:n)';for d=2:n;y=((1:n)*10^(d-1));o=[];for p=1:nnz(y);o=cat(d,o,(x+y(p)));end;x=o end ``` **Explanation** ``` x=(1:n)'; % Create array x=[1,2,...n]' for d=2:n % d for dimension y=((1:n)*10^(d-1)); % Creates an array for each d where % y=[10,20,30,...] for n=2 % y=[100,200,...] for n=3 etc. o=[]; % o for output for p=1:nnz(y) % For each value of y o=cat(d,... % Concatenate in the dth dimension: o,... % - The current output x+y(p)); % - The sum of % - The array from the last dimension % - The current value in y (e.g. 100) end x=o % Send the output to x for the next loop end ``` Outputs x at the end to give solution Similar to the other MATLAB post, the output is an n-dimensional array, except it uses numbers to display the coordinates. It works for any value, although because loops are bad in MATLAB it begins to slow down significantly around n = 8. Edit: -2 bytes thanks to Luis Mendo. Also removed final semicolon to print the output. [Answer] # [Rust](https://www.rust-lang.org/), ~~201~~ ~~176~~ ~~167~~ ~~166~~ 154 bytes ``` enum L{S(String),L(Vec<L>)}fn h(n:u8,d:u8,s:&str)->L{if d<1{L::S(s.into())}else{L::L((0..n).map(|i|h(n,d-1,&format!("{}{}",s,i))).collect())}}|n|h(n,n,"") ``` [Try it online!](https://tio.run/##HU6xasMwFNz1FaoD4T1QRNOpKGm6ZNRm6FI6uLaUCOTnIMlZZH27K/eG4zjujgtzTKslPnaOAHlmzJvELf@ocvc9mOCeBq7md77hz2poHrnOLbQpOLqh0PBl@rO@YLHE7kBqfhfDRlHtYwp4uOjsLBvOx6yVaiFKR2kCxGJ8NJunAV6lJJRj94DFLXVEDIej2NspjF16gSaXXBoRhUNE2U/emz5tC2Wh/zSJpsG1nBiveNRfydNWU7vP2uMW3hBPrKx/ "Rust – Try It Online") The output type is a sum type with two variants as the language is strictly typed. It can be either `L`, which is a list type containing this sum type or `S` which is a result type (a string). The result can look like this. ``` L::L([ L::L([ L::S("00"), L::S("01") ]), L::L([ L::S("10"), L::S("11") ]), ]) ``` Also, reformatted using `rustfmt`: ``` enum L { S(String), L(Vec<L>), } fn h(n: u8, d: u8, s: &str) -> L { if d < 1 { L::S(s.into()) } else { L::L( (0..n) .map(|i| h(n, d - 1, &format!("{}{}", s, i))) .collect(), ) } } |n| h(n, n, "") ``` [Answer] # [R](https://www.r-project.org/), 102 bytes ``` function(n,m=array(T,rep(n,n)))`if`(n<2,'1',{m[]=apply(which(m,T)[,`[<-`(1:n,1:2,2:1)],1,toString);m}) ``` [Try it online!](https://tio.run/##dcuxCoMwEIDh3adwyx2cQ6KTNU9RNyskSFMDzSkhpUjps6edW/Jv//DF7HR2D16S3xiYgrYx2gNGitf9@4yIxjsDPCgSUtArTLO2@34/4Ln6ZYVAI05kpqExIHsm2StSvcSZJKXtnKLnG57CG/NiE4jmp5q1rJu/LiywciCxKilVVqqs2rJqy6orqw7zBw "R – Try It Online") * 1-indexed, reversed * unfortunately R stores matrix by column, otherwise we could go down to [73 bytes](https://tio.run/##dcsxDoMwDIXhnVOwYUvOEGAkpyhbOxBFBCJVJoqCSk6fMrfyP703fKl6U/3JLoeDgekyNiVbYKa0xvszIi7PSS1wUZnUZw9uv@eMZGN8FyikKR@PnAJviNXZDJ36qWWjW/XXiztsPGhsJNXLqpfVIKtBVqOsRqxf "R – Try It Online") * -9 bytes saved thanks to @Giuseppe suggestion to use `which` array indexing [Answer] # Java 10, 144 bytes The solution is method `f`. It produces a string representation of the array. ``` String h(int n,int d,String s){if(d<1)return s;var r="[";for(int i=0;i++<n;)r+=h(n,d-1,s+i)+",";return r+"]";}String f(int n){return h(n,n,"");} ``` [Try It Online](https://tio.run/##NU/NasMwDD6nTyF8srEbFnZ0/Ag79VhK8eKkdZcoxXZSRsizZ67jgZDEJ74fPfSsjw/zsz2n79420PTae/jSFmHZTsFZvMGdWgyA4t2NyKBni@2oqSvm2jA5BC9n7cApciayG13iWPUhLec1Sua4ulMU5lgJzy3jRBCZmY6TC5FrFu52N7bk65uFghAm163IKX3QIY55tAaGmJXu3PMFtLt5BsuhKNIPAyjA9pUeokxGOEaD5NBo317juZJ5rRV8/u884rtMcfr1oR3KcQrlM5qEHmm2YzCUHU0ElrTXQ6x1@wM) ## Ungolfed ``` String h(int n, int d, String s) { if (d < 1) return s; var r = "["; for (int i = 0; i++ < n;) r += h(n, d - 1, s + i) + ","; return r + "]"; } String f(int n) { return h(n, n, ""); } ``` ## Acknowledgments * byte savings thanks to [Konrad Borowski](https://codegolf.stackexchange.com/users/3103) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` LsãsGsô ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fp/jw4mL34sNb/v83BgA "05AB1E – Try It Online") **Explanation** ``` L # push range [1 ... input] sã # input repeated cartesian products of the list sG # input - 1 times do: sô # split into input parts ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~62~~ ~~60~~ 58 bytes ``` f=(n,i=n,s='')=>i?[...Array(n)].map((_,j)=>f(n,i-1,s+j)):s ``` [Try it online!](https://tio.run/##FYvBCsIwEAV/ZW/dmDRQ6Kk1inf/QERim2hi3ZSkCiJ@e0xPD2bmef3WaYhuXmoKo8nZKiThFImkqoqpndufpJSHGPUHiZ3lU8@IF@GLsmtZNyJxz1iXcm9DBHSgoOnBwVZBW5ZzBkOgFCYjRxfRomMCvnCNRj@Ohm7LvSv1Zn1yaIsbzbwyek0T/Fif/w "JavaScript (Node.js) – Try It Online") Output is 0-indexed. Edit: Saved 2 bytes thanks to @JoKing and a further 2 bytes thanks to @Arnauld. [Answer] ## MATLAB, 116 108 104 bytes I feel like there must be a shorter way to do this, given MATLAB's affinity toward multi-dimensional matrices... Thanks to Luis for the 4 bytes from some short-handing ``` a=~(1:n)+n;c=cell(1,n);[c{:}]=ind2sub(a,1:n^n);reshape(arrayfun(@(varargin)[varargin{:}],c{:},'un',0),a) ``` **Explanation** ``` % For using twice, define the array of dimension sizes [n, n, .., n] a=~(1:n)+n; % To group variable number of outputs from ind2sub into a cell array c=cell(1,n); % Convert linear indices to self-describing coordinates [c{:}]=ind2sub(a,1:n^n); % reshape to make it the n-dimensional array % arrayfun to loop over the numerous ind2sub outputs simultaneously % varargin and {:} usage to account for various numbers of inputs reshape(arrayfun(@(varargin)[varargin{:}],c{:},'uni',0),a) ``` The output is an n-dimensional cell array, where each element is an array of the coordinate values. Works for any `n` without ambiguity because of the numeric array output, so long as an `n^(n+1)` element array can be stored in RAM! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` Nθ≔EXθθ⪫⪪◧⍘ιθθ ¦0υFθ≔⪪υθυυ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05rLsbg4Mz1PwzexQCMgvxwkqKNQqKmj4JWfmacRXJCTWaIRkJjik5pWouGUWJwaXFKUmZeukQlRBMJKCkog0kBJE0iVAk1Myy9SABqtADUZYkYpRDFIPgBoAlBA0/r/f@P/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` ≔EXθθ⪫⪪◧⍘ιθθ ¦0υ ``` Generate all `nⁿ` `n`-digit numbers in base `n`. ``` Fθ≔⪪υθυ ``` Split them `n` times into an `n`-dimensional array where each dimension is of size `n`. ``` υ ``` Print the array. The default output format is each element on its own line, then each block of `n` lines is terminated by a blank line, then each block of `n` blocks of `n` lines is terminated by a second blank line, and so on up to `n-1` blank lines at the top level. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ṗṁẋ`ŒṬ$ ``` [Try it online!](https://tio.run/##y0rNyan8///hzukPdzY@3NWdcHTSw51rVP4fbgcxZvz/bwwA "Jelly – Try It Online") ]
[Question] [ Take a positive integer `X`. This number is part of the sequence we are interested in if the sum of all digits of `X` is a divisor of `X`, and if the product of all digits of `X` is a divisor of `X`. For example, `135` is such a number because `1 + 3 + 5 = 9` which divides `135 = 9 * 15` and `1 * 3 * 5 = 15` which also divides `135`. This is sequence [A038186](http://oeis.org/A038186) in the OEIS. **Your task:** given an integer `N`, output the `N`th positive integer with such properties. ### Inputs and outputs * Numbers may be `0`-indexed or `1`-indexed; please indicate which one your answer use. * The input may be taken through `STDIN`, as a function argument, or anything similar. * The output may be printed to `STDOUT`, returned from a function, or anything similar. ### Test cases The test cases below are `1`-indexed. ``` Input Output 1 1 5 5 10 12 20 312 42 6912 50 11313 ``` ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~13~~ 12 bytes Thanks to *Emigna* for saving a byte! ``` µNNSONSP‚ÖP½ ``` Explanation: ``` µ ½ # Get the nth number for which the following holds: NSO # The sum of digits of the current number NSP # And the products of digits of the current number N ‚ÖP # Divides the current number # If the nth number has been reached, quit and implicitly print N ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=wrVOTlNPTlNQ4oCaw5ZQwr0&input=NDI) [Answer] ## Pyke, 14 bytes (non-competitive) (1-indexed) ``` ~1IY'sB]im%X)@ ``` [Try it here!](http://pyke.catbus.co.uk/?code=%7E1IY%27sB%5Dim%25X%29%40&input=11) My god what a lot of new features. ``` ~1 - infinite list of natural numbers IY'sB]im%X) - filter(^, V) - remove if any truthiness Y - digits(i) 'sB] - [sum(^), product(^)] im% - map(^, %i) X - splat(^) @ - ^[input] ``` Of which are non-competitive * a bugfix in `I` where it would only check if the first item on the stack was truthy * `digits` - return a list of digits in the number * `@` used to get the nth item of an infinite list Of which were being used for the first time: * all of the above * infinite lists Remove the last 2 bytes to get all of these numbers. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` DµP;SðḍȦ 1Ç#Ṫ ``` 1-based. **[TryItOnline!](http://jelly.tryitonline.net/#code=RMK1UDtTw7DhuI3Ipgoxw4cj4bmq&input=&args=MjA)** ### How? ``` DµP;SðḍȦ - Link 1, test a number D - convert to a decimal list µ - monadic chain separation ; - concatenate the P - product, and the S - sum ð - dyadic chain separation ḍ - divides n? Ȧ - all (i.e. both) 1Ç#Ṫ - Main link, get nth entry, 1-based: n 1 # - find the first n matches starting at 1 of Ç - the last link (1) as a monad Ṫ - tail (the ultimate result) ``` [Answer] # C#, 118 bytes ``` n=>{int x=0,c=0;for(;;){int s=0,p=1,i=++x;while(i>0){s+=i%10;p*=i%10;i/=10;}if((c+=p>0&&x%s+x%p<1?1:0)==n)return x;}}; ``` Full program with ungolfed function and test cases: ``` using System; public class Program { public static void Main() { // x - output number // c - counter // s - sum // p - product // i - iterator Func<int,int>f= n=> { int x=0, c=0; for ( ; ; ) { int s=0, p=1, i=++x; while (i > 0) { s += i%10; p *= i%10; i /= 10; } if ( (c += p> 0&& x%s+x%p<1 ? 1 : 0) == n) return x; } }; // tests: Console.WriteLine(f(1)); //1 Console.WriteLine(f(5)); //5 Console.WriteLine(f(10)); //12 Console.WriteLine(f(20)); //312 Console.WriteLine(f(42)); //6912 Console.WriteLine(f(50)); //11313 } } ``` [Answer] ## [Jellyfish](http://github.com/iatorm/jellyfish), 45 bytes ``` p \Ai \& >(&]&|0 <*&d &~bN 10 ( )/+ /* ``` [Try it online!](http://jellyfish.tryitonline.net/#code=cApcQWkKXCYKPigmXSZ8MAogIDwqJmQKICZ-Yk4KICAxMAogKCApLysKIC8q&input=NTA) ### Explanation This is by far the most elaborate (and also the longest) program I've written in Jellyfish so far. I have no idea whether I'll be able to break this down in an understandable manner, but I guess I'll have to try. Jellyfish provides a fairly general iteration operator, `\`, which helps a lot with "finding the Nth *something*". One of its semantics is "iterate a function on a value until a separate test function gives something truthy" (in fact, the test function receives both the current and the last element, but we'll only make it look at the current element). We can use this to implement a "next valid number" function. Another overload of `\` is "iterate a function on a starting value N times". We can use our previous function and iterate it on `0` N times, where N is the input. All of that is set up fairly concisely with this part of the code: ``` p \Ai \& > 0 ``` (The reasons why `0`, the actual input to the resulting function, is over there are a bit complicated and I won't go into them here.) The issue with all of this is, that we won't be passing the current value to the test function manually. The `\` operator will do this for us. So we now have construct a single unary function (via compositions, hooks, forks and currying) which takes a number and tells us whether it's a valid number (i.e. one which is divided by its digit sum and digit product). This is fairly non-trivial when you can't refer to the argument. Ever. It's this beauty: ``` (&]&| <*&d &~bN 10 ( )/+ /* ``` The `(` is a unary *hook*, which means that it calls the function below (`f`) on its input (the current value `x`), and then passes both of them to the test function to the right (`g`), that is it computes `g(f(x), x)`. In our case, `f(x)` is another composite function which obtains a pair with the digit product and digit sum of `x`. That means `g` will be a function that has all three values to check if `x` is valid. We'll start by looking at how `f` computes the digit sum and digit product. This is `f`: ``` &~b 10 ( )/* /+ ``` `&` is also composition (but the other way round). `~` is currying so `10~b` gives function that computes the decimal digits of a number, and since we're passing that to `&` from the right, that's the first thing that will happen to the input `x`. The remainder uses this list of digits to compute their sum and product. To compute a sum, we can *fold* addition over it, which is `/+`. Likewise, to compute the product we fold multiplication over it with `/*`. To combine both of these results into a pair, we use a pair of hooks, `(` and `)`. The structure of this is: ``` ()g f ``` (Where `f` and `g` are product and sum, respectively.) Let's try to figure out why this gives us a pair of `f(x)` and `g(x)`. Note that the right hook `)` only has one argument. In this case, the other argument is implied to be `;` which wraps its arguments in a pair. Furthermore, hooks can also be used as binary functions (which will be the case here) in which case they simply apply the inner function only to one argument. So really `)` on a single function `g` gives a function that computes `[x, g(y)]`. Using this in a left hook, together with `f`, we obtain `[f(x), g(y)]`. This, in turn is used in a unary context, which mean that it's actually called with `x == y` and so we end up with `[f(x), g(x)]` as required. Phew. That leaves only one thing, which was our earlier test function `g`. Recall that it will be called as `g([p, s], x)` where `x` is still the current input value, `p` is its digit product and `s` is its digit sum. This is `g`: ``` &]&| <*&d N ``` To test divisibility, we'll obviously use modulo, which is `|` in Jellyfish. Somewhat unusually, it take its right-hand operand modulo its left-hand operand, which means that the arguments to `g` are already in the right order (arithmetic functions like this automatically thread over lists, so this will compute the two separate moduli for free). Our number is divisible by both the product and sum, if the result is a pair of zeros. To check whether that's the case, we treat the pair as a list of base-2 digits (`d`). The result of this is zero, only when both elements of the pair are zero, so we can negate the result of this (`N`) to obtain a truthy value for whether both values divide the input. Note that `|`, `d` and `N` are simply all composed together with a pair of `&`s. Unfortunately, that's not the full story. What if the digit product is zero? Division and modulo by zero both return zero in Jellyfish. While this may seem like a somewhat odd convention, it actually turns out to be somewhat useful (because we don't need to check for zero before doing the modulo). However it also means we can get a false positive, if the digit sum does divide the input, but the digit product is zero (e.g. input `10`). We can fix this by multiplying our divisibility result by the digit product (so if the digit product is zero it will turn our truthy value into a zero as well). It turns out to be simpler to multiply the divisibility result with the pair of product and sum, and extract the result from the product afterwards. To multiply the result with the pair, we kinda need to get back at an earlier value (the pair). This is done with a *fork* (`]`). Forks are kinda like hooks on steroids. If you give them two functions `f` and `g`, they represent a binary function which computes `f(a, g(a, b))`. In our case, `a` is the product/sum pair, `b` is the current input value, `g` is our divisibility test, and `f` is the multiplication. So all of this computes `[p, s] * ([p, s] % x == [0, 0])`. All that's left now is to extract the first value of this, which is the final value of the test function used in the iterator. This is as simple as composing (`&`) the fork with the *head* function `<`, which returns the first value of a list. [Answer] # [Perl 6](https://perl6.org), 44 bytes (0-indexed) ``` {grep({$_%%(.comb.sum&[*] .comb)},1..*)[$_]} ``` Explanation: ``` { } # A function, with an argument n (`$_`) grep( ,1..*) # Filter the infinite list {$_ } # Check that the function's argument %%( ) # is divisible by & # both: .comb.sum # - the sum of the digits [*] .comb # - the product of the digits [$_] # Get the n-th value ``` Infinite lists ftw! [Answer] # [Actually](http://github.com/Mego/Seriously), 20 bytes Naive implementation of the sequence definition. Golfing suggestions welcome! [Try it online!](http://actually.tryitonline.net/#code=dWA7OyTimYLiiYg7zqMoJUDPgCglfFlg4pWTTg&input=MjA) ``` u`;;$♂≈;Σ(%@π(%|Y`╓N ``` **Ungolfing** ``` Implicit input n. u Increment n, so that we don't accidentally include 0 in the sequence. `...`╓ Starting with x=0, return the first n+1 values of x where f(x) is truthy. ;; Duplicate x twice. $♂≈ str(x) and convert each char (each digit) into an int. Call this digit_list. ; Duplicate digit_list. Σ Get sum(digit_list). (% Get x % sum(digit_list), which returns 0 if sum is a divisor of x. @ Swap the other duplicate of digit_list to TOS. π Get prod(digit_list). (% Get x % prod(digit_list), which returns 0 if prod is a divisor of x. | Get x % sum(digit_list) OR x % prod(digit_list). Y Logical negate, which only returns 1 if both are divisors, else 0. N Return the last value in the list of x where f(x) is truthy, that is, the nth value of the sequence. ``` [Answer] ## JavaScript (ES6), 72 bytes ``` k=>eval("for(n=0;(E=o=>n%eval([...n+''].join(o))!=0)`+`|E`*`||--k;)++n") ``` ### Demo It tends to be slow for higher values, so I'm limiting it to 20 here. ``` let f = k=>eval("for(n=0;(E=o=>n%eval([...n+''].join(o))!=0)`+`|E`*`||--k;)++n") console.log(f(1)); // 1 console.log(f(5)); // 5 console.log(f(10)); // 12 console.log(f(20)); // 312 ``` [Answer] ## R, ~~132~~ 115 bytes New version thanks to @Billywob nice comments ! ``` n=scan();b=i=0;while(i<n){b=b+1;d=strtoi(el(strsplit(c(b,""),"")));if(na.omit(c(!b%%sum(d)&!b%%prod(d),0)))i=i+1};b ``` **Ungolfed :** ``` n=scan() b=i=0 while(i<n) b=b+1; d=strtoi(el(strsplit(c(b,""),""))) #Splitting the number into its digits if(na.omit(c(!b%%sum(d)&!b%%prod(d),0))) i=i+1 b ``` ~~Since **R** behave strangley with `NA`s, I had to add the whole `ifelse(is.na(...))` part!~~ Or use `na.omit(...)` [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 22 bytes ``` :1yt #>=.@e+:I*.@e*:J* ``` [Try it online!](http://brachylog.tryitonline.net/#code=OjF5dAojPj0uQGUrOkkqLkBlKjpKKg&input=MjA&args=Wg&debug=on) ### Explanation ``` :1y Evaluate the first N valid outputs to the predicate below given the main input as input t The output is the last one #>=. Output is a strictly positive integer @e+ The sum of its digits… :I*. …multiplied by an integer I results in the Output @e* The product of its digits… :J* …multiplied by an integer J results in the Output ``` [Answer] # JavaScript (ES6), 78 ``` n=>eval("for(i=0;n;!p|i%s|i%p||n--)[...++i+''].map(d=>(s-=d,p*=d),s=0,p=1);i") ``` *Less golfed* ``` n=>{ for(i=0; n; !p|i%s|i%p || n--) s=0, p=1, [...++i+''].map(d=>(s-=d, p*=d)); return i } ``` [Answer] # Pyth, 18 bytes ``` e.f!.xs%LZsM*FBsM` ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=e.f%21.xs%25LZsM%2AFBsM%60&input=20&test_suite_input=1%0A5%0A10%0A20%0A42%0A50&debug=0) ### Explanation: ``` e.f!.xs%LZsM*FBsM`ZZQ1 implicit variables at the end e print the last number of the .f Q1 first Q (input) numbers Z >= 1, which satisfy: `Z convert Z to a string, e.g. "124" sM convert each digits back to a number, e.g. [1, 2, 4] *FB bifurcate with product, e.g. [[1, 2, 4], 8] sM take the sum of each, e.g. [7, 8] %LZ compute the modulo of Z with each number, e.g. [5, 4] s and add both numbers, e.g. 9 .x Z if an exception occurs (mod 0), use number Z instead ! test, if this number is zero ``` [Answer] # Haskell, ~~94~~ ~~85~~ ~~72~~ 71 bytes ``` ([n|n<-[0..],(==)=<<map(gcd n)$[product,sum]<*>[read.pure<$>show n]]!!) ``` 1-indexed. Thanks to @Zgarb for saving 13 bytes! Thanks to @nimi for saving a byte! [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 33 bytes I followed an idea of @ngn when it comes to wrapping the function in some sort of a `⍣`-based operation. ``` {1+⍣{0=+/((1∘⊥,×/)⍎¨⍕⍺)|⍺ ⍺}⍣⍵⊢0} ``` Explanation: ``` {1+⍣{0=+/((1∘⊥,×/)⍎¨⍕⍺)|⍺ ⍺}⍣⍵⊢0} {1+⍣ ⍣⍵⊢0} ⍝ Execute the inner dfn until it returns one ⍵ times ⍝ and yield the last number it processed. {0=+/((1∘⊥,×/)⍎¨⍕⍺)|⍺ ⍺} ⍝ 1 if ⍺ is divisible by sum and product of its digits. ⍎¨⍕⍺ ⍝ digits of ⍺ , ⍝ a vector of... ×/ ⍝ product of digits 1∘⊥ ⍝ sum of digits |⍺ ⍺ ⍝ each modulo ⍺ 0=+/ ⍝ both divisible? ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqQ@1HvYurDWy19TU0DB91zHjUtVTn8HR9zUe9fYdWPOqd@qh3l2YNkFAA4lqg0ke9Wx91LTKoBWpXMDHiSlMwNQARQGwIxEYGAA "APL (Dyalog Unicode) – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 9 bytes ``` λ₍∑ΠḊA;ȯt ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%CE%BB%E2%82%8D%E2%88%91%CE%A0%E1%B8%8AA%3B%C8%AFt&inputs=10&header=&footer=) ~~Apparently there's a 10 byte 0-indexed version.~~ -3 bytes from Lyxal. [Answer] # [MATL](http://github.com/lmendo/MATL), 21 bytes ``` `@tFYAtswph\~?@]NG<]& ``` Long and inefficient... [Try it online!](http://matl.tryitonline.net/#code=YEB0RllBdHN3cGhcfj9AXU5HPF0m&input=MjA) ### How it works ``` ` % Do...while @ % Push current iteration index (1-based) tFYA % Duplicate. Convert number to its digits ts % Duplicate. Sum of digits wp % Swap. Product of digits h\ % Concatenate. Modulo. This gives a length-2 array ~? % If the two values are zero: we found a number in the sequence @ % Push that number ] % End if NG< % True if number of elements in stack is less than input ] % End do...while. If top of the stack is true: next iteration. Else: exit & % Specify only one input (top of stack) for implicit display ``` [Answer] # Python 2, ~~122~~ 110 Bytes ``` def a(m,i=1,k=1):n=map(int,`i`);p=reduce(lambda x,y:x*y,n);k+=p and 1>i%sum(n)+i%p;return(k>m)*i or a(m,i+1,k) ``` 1 indexed, you need to use a Python interpreter with a quite high recursion limit. [Answer] ## Python3, 134 80 Bytes New version thanks to [Flp.Tkc](https://codegolf.stackexchange.com/users/60919/flp-tkc) ``` t=input();h=k=0;p=int def g(x,q=0,w=1): for i in x:X=p(x);I=p(i);q+=I;w*=I return w!=0and X%q+X%w<1 while h<p(t):k+=1;h+=g(str(k)) ``` New code, I remembered a golfing way to do the factorial ``` f,t=lambda x:0**x or x*f(x-1),0 for i in str(f(int(input()))):t+=int(i) print(t) ``` The code itself isn't very golf-like, more like brute force golf ``` def g(x): q=0;w=1;X=int(x) for i in x:I=int(i);q+=I;w*=I return (w!=0+ X%q==0and X%w==0) t=input();h=k=0 while h<int(t): k+=1 if g(str(k))is True:h+=1 ``` g(x) is a function that returns True if x fits the criteria. [Answer] # x86-16 machine code, 52 bytes ``` 00000000: 33db 4351 8bc3 bf0a 0033 f6b1 0133 d2f7 3.CQ.....3...3.. 00000010: f703 f291 f7e2 9142 e314 85c0 75ef 8bc3 .......B....u... 00000020: 33d2 f7f6 8bc3 85d2 7504 f7f1 85d2 5975 3.......u.....Yu 00000030: d1e2 cfc3 .... ``` Listing: ``` 33 DB XOR BX, BX ; X = 0 NUM_LOOP: 43 INC BX ; increment X 51 PUSH CX ; save loop counter (N) 8B C3 MOV AX, BX ; AX = current X START_N: BF 000A MOV DI, 10 ; DI = decimal divisor of 10 33 F6 XOR SI, SI ; SI = sum of digits B1 01 MOV CL, 1 ; CX = product of digits SPLIT_DIGITS: 33 D2 XOR DX, DX ; clear high word of dividend F7 F7 DIV DI ; AX = quotient, DX = remainder 03 F2 ADD SI, DX ; SI = SI + digit 91 XCHG AX, CX ; AX = running product, CX = quotient F7 E2 MUL DX ; AX = AX * digit 91 XCHG AX, CX ; CX = running product, AX = quotient 42 INC DX ; ZF = NZ (hacky) E3 14 JCXZ END_N ; if digit is a 0, end with Falsey 85 C0 TEST AX, AX ; is quotient 0? 75 EF JNZ SPLIT_DIGITS ; loop until it is 8B C3 MOV AX, BX ; AX = current X 33 D2 XOR DX, DX ; clear high word of dividend F7 F6 DIV SI ; divide X by sum 8B C3 MOV AX, BX ; AX = current X 85 D2 TEST DX, DX ; if sum remainder is 0 then Truthy (ZF = ZR) 75 04 JNZ END_N ; if not, end with Falsey (ZF = NZ) F7 F1 DIV CX ; divide X by product 85 D2 TEST DX, DX ; if product remainder is 0 then Truthy (ZF = ZR) END_N: 59 POP CX ; restore loop counter 75 D1 JNZ NUM_LOOP ; if falsey, keep looping and don't decrement counter E2 CF LOOP NUM_LOOP ; otherwise decrement counter and loop C3 RET ; return to caller ``` Callable function. Input `N` in `CX`, Output `N`th positive integer in `BX`. `N` of `50` is about 4 seconds on an IBM PC 5150: [![enter image description here](https://i.stack.imgur.com/qVR6D.png)](https://i.stack.imgur.com/qVR6D.png) [Answer] ## JavaScript (ES6), 70 bytes ``` k=(b,n=1,f=c=>n%eval([...n+''].join(c))!=0)=>f`+`|f`*`||--b?k(b,n+1):n ``` This turned out quite a bit like @Arnauld's answer, but recursion is apparently 2 bytes shorter. Works in Chrome, though it's very slow on inputs greater than 30 or so (50 takes 6 seconds). [Answer] # Wonder, 33 bytes ``` @:^#0(!>@!(| %#0sum#0)%#0prod#0)N ``` Zero-indexed. Usage: ``` (@:^#0(!>@!(| %#0sum#0)%#0prod#0)N)9 ``` # Explanation More readable: ``` @ iget #0 (fltr@ not (or % #0 sum #0) % #0 prod #0 ) N ``` Basically gets an infinite list of numbers divisible by its digital sum and product by filtering an infinite list of whole numbers through a predicate. Then the `n`th item is simply picked out of the list. [Answer] # Julia, 81 bytes ``` n->(i=c=1;while c<n d=digits(i+=1);all(d.>0)&&i%sum(d)==i%prod(d)<1&&(c+=1)end;i) ``` This is an anonymous function that accepts an integer and returns an integer. To call it, give it a name. The approach is the obvious one: check every number until we've encountered `n` terms of the sequence. The `all` check is necessary to ensure we don't get a `DivisionError` from `%` when the product of the digits is 0. Ungolfed: ``` function f(n) i = c = 1 while c < n d = digits(i += 1) all(d .> 0) && i % sum(d) == i % prod(d) < 1 && (c += 1) end return i end ``` [Try it online!](http://julia.tryitonline.net/#code=Zj1uLT4oaT1jPTE7d2hpbGUgYzxuIGQ9ZGlnaXRzKGkrPTEpO2FsbChkLj4wKSYmaSVzdW0oZCk9PWklcHJvZChkKTwxJiYoYys9MSllbmQ7aSkKCmZvciBpIGluIFsxLCA1LCAxMCwgMjAsIDQyLCA1MF0KICAgIHByaW50bG4oaSwgIlx0IiwgZihpKSkKZW5k&input=) (includes all test cases) [Answer] # C89, ~~381~~ ~~226~~ ~~195~~ ~~170~~ 169 bytes 1-indexed (same exact answers as in the challenge). **Assumes *4-byte (32 bit) `int`* (most modern architectures)**. I genuinely believe this can't go any shorter. ``` x,c,*b,m,t,i,a;g(n){for(b=malloc(0);c<n;b[c-1]=x++,t=1){char s[9];for(i=m=0;i<sprintf(s,"%d",x);m+=a,t*=a)a=s[i++]-48;b=m*t?x%m+x%t?b:realloc(b,4*++c):b;}return b[c-1];} ``` Function `int g (int)` leaks memory and accesses uninitialised memory once per call but doesn't segfault and returns the right number. Full program that takes input in unary (`./prog $(seq 1 10)` for 10) with ungolfed (kinda): ``` x, c, * b, m, t, i, a; g(n) { for (b = malloc(0); c < n; b[c - 1] = x++, t = 1) { char s[9]; i = m = 0; for (; i < sprintf(s, "%d", x); m += a, t *= a) a = s[i++] - 48; b = m * t ? x % m + x % t ? b : realloc(b, 4 * ++c) : b; } return b[c - 1]; } main (j) { printf("%d\n", g(--j)); } ``` ### Old answer: ### C99, 381 bytes ``` #include <stdio.h> #include <inttypes.h> #include <string.h> #include <stdlib.h> #define U uint64_t #define S size_t S f(S n){U x=0;S c=1,l;U*b=malloc(sizeof(U));while(c<=n){char s[21];snprintf(s,20,"%"PRIu64,x);U m=0,t=1;l=strnlen(s,21);for(S i=0;i<l;i++){U a=(U)s[i]-48;m+=a,t*=a;}if(m*t?(!(x%m))&&(!(x%t)):0){b=realloc(b,sizeof(U)*++c);b[c-1]=x;}++x;}U o=b[n];free(b);return o;} ``` This can probably be golfed more. Full program: ``` #include <stdio.h> #include <limits.h> #include <stdint.h> #include <inttypes.h> #include <stdbool.h> #include <string.h> #include <stdlib.h> bool qualifies (const uint64_t); size_t f (const size_t); int main(const int argc, const char* const * const argv) { (void) argc; size_t arg = strtoull(argv[1], NULL, 10); uint64_t a = f(arg); printf("a: %" PRIu64 "\n", a); return 0; } bool qualifies (const uint64_t num) { char s[21]; snprintf(s, 20, "%" PRIu64 "", num); uint64_t sum = 0, mult = 1; size_t len = strnlen(s, 400); for (size_t i = 0; i < len; i++) { uint64_t a = (uint64_t) s[i] - 48; sum += a, mult *= a; } //printf("sum: %" PRIu64 "\nmult: %" PRIu64 "\n", sum, mult); return sum * mult ? (! (num % sum)) && (! (num % mult)) : false; } size_t f (const size_t n) { uint64_t x = 0; size_t s_len = 1; uint64_t* nums = malloc(sizeof (uint64_t) * s_len); while (s_len <= n) { if (qualifies(x)) { ++s_len; //printf("len: %zu\n", s_len); nums = realloc(nums, sizeof (uint64_t) * s_len); nums[s_len - 1] = x; } ++x; } uint64_t o = nums[n]; free(nums); return o; } ``` [Answer] # C, 110 bytes ``` p;s;i;j;f(n){j=0;while(n){i=++j;p=1;s=0;do p*=i%10,s+=i%10;while((i/=10)>0);if(p>0&&j%p+j%s==0)--n;}return j;} ``` Ungolfed and usage: ``` p;s;i;j; f(n){ j=0; while(n){ i=++j; p=1; s=0; do p*=i%10, //product s+=i%10; //sum while((i/=10)>0); //check if product is not zero since floating point exception if(p>0 && j%p + j%s == 0)--n; } return j; } int main(){ int n; scanf("%d",&n); printf("\n%d\n", f(n)); } ``` [Answer] # [Scala](https://www.scala-lang.org/), ~~80~~ 68 bytes ``` Stream from 1 filter{n=>val x=n+""map(_-48.0);n%x.sum+n%x.product<1} ``` [Try it online!](https://scastie.scala-lang.org/RA0mDGVLTxOPTFa3rsAfSg) 0-indexed. `Stream`s are not only infinite collections but also functions taking an `Int` and giving the element at that index. ``` Stream from 1 //Infinite stream starting at 1 filter { n => //Filter each n according to this predicate: val x = //List of digits n + "" //Convert to string map(_ - 48.0); //Turn each character into its corresponding number (as a double, so n%0 works later) n % x.sum + //n modulo the sum of its digits n%x.product //plus n modulo the product of its digits < 1 //Make sure that's less than 1, i.e. both are 0 } ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` !f§Λ`¦o§eΠΣdN ``` [Try it online!](https://tio.run/##AR4A4f9odXNr//8hZsKnzptgwqZvwqdlzqDOo2RO////MjA "Husk – Try It Online") Combinators good but combinators long :( -1 byte from Leo in SE Chat. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 25~~27~~ bytes This even better answer curtesy of Adam ``` 1+⍣{0=⍺|⍨(+/∧×/)⍎¨⍕⍺}⍣⎕⊢0 ``` This is essentially the same just hcf is taken of the sum and product saving 2 bytes ``` 1+⍣{0=∨/⍺|⍨(+/,×/)⍎¨⍕⍺}⍣⎕⊢0 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b@h9qPexdUGto86Vug/6t1V86h3hYa2vs7h6fqaj3r7Dq141DsVKFwLVPSob@qjrkUGIG3/07hMjLjSuEwNQAQQGwKxkQEA "APL (Dyalog Unicode) – Try It Online") ``` ⎕ ⍝ takes user input {...}⍣n ⍵ ⍝ repeats the function n times 1∘+⍣{0=∨/⍺|⍨(+/,×/)⍎¨⍕⍺} ⍝ given a number repeatetly adds 1(1∘+) untill the condition is satisfied {⍵|⍨(+/,×/)⍎¨⍕⍵} ⍝ converts numbers to a list of numbers and then take there sum and product and then take there reminder after dividing with the given number ∨/ ⍝ takes HCF of the list escecially checking if both the numbers are not zero 0= ⍝returs true if the hcf is zero ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `ct`, 6 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` ƘçSpḊp ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDNiU5OCVDMyVBN1NwJUUxJUI4JThBcCZmb290ZXI9JmlucHV0PTQyJmZsYWdzPWN0) #### Explanation ``` ƘçSpḊp # Implicit input, n Ƙ # nth positive integer, k, where: ç # Parallelly apply: S # Sum of digits of k p # Product of digits of k Ḋ # Is k divisible by them p # Both return true? # Implicit output ``` [Answer] # PHP, 96 bytes Takes `n` as a command line argument. ## Golfed ``` for(;$i<$argv[1];)!($p=array_product($d=str_split(++$j)))|$j%array_sum($d)||$j%$p?:$i++;echo $j; ``` ## Ungolfed ``` for (; $i < $argv[1];) // Loop until we've found the nth number as pass by command line !($p = array_product($d = str_split(++$j))) || // Split our current number into its digits and assign that to a variable, then assign the product of that array to another variable. // As well, we're checking if the product equals 0, to prevent an error from trying to mod by 0 later. The condition short circuits before it happens. $j % array_sum($d) || // Check if the sum of the array is a divisor $j % $p // Check if the product is a divisor ?: $i++; // Increment the number of found instances only if all conditions are met. echo $j; // Output to screen. ``` [Answer] ## PowerShell v2+, 84 bytes ``` param($n)for(;$n){$n-=!(++$a%(($b=[char[]]"$a")-join'+'|iex)+$a%($b-join'*'|iex))}$a ``` Iterative solution. Takes input `$n` and enters a `for` loop so long as `$n` is not zero. Each iteration, we subtract from `$n` the result of a Boolean statement, broken out below: ``` !(++$a%(($b=[char[]]"$a")-join'+'|iex)+$a%($b-join'*'|iex)) !( ) # Encapsulate in a NOT ++$a% # Increment $a and take mod ... ($b=[char[]]"$a") # Turn $a into char-array, store in $b -join'+' # Join the char-array together with + |iex # and eval it $a%($b-join'*'|iex) # Similar for * + # Addition ``` Thus, only if `$a%(sum)` and `$a%(product)` are *both* equal to zero will the addition also be zero, and thus the Boolean-not will be True and therefore `$n` is decremented. Once we exit the loop (i.e., we hit the *nth* term), we simply place `$a` on the pipeline, and output is implicit. ### Examples Note: This tosses a *bunch* of "Attempted divide by zero" errors to STDERR, which is ignored by default. I've explicitly added a `2>$null` to the example below to cleanup the output. It's also pretty slow once it gets to about `30` or so, and `50` takes about 45 seconds on my machine. ``` PS C:\Tools\Scripts\golfing> 1,5,10,20,30,42,50|%{"$_ --> "+(.\numbers-divisible-by-sum-and-product.ps1 $_ 2>$null)} 1 --> 1 5 --> 5 10 --> 12 20 --> 312 30 --> 1344 42 --> 6912 50 --> 11313 ``` ]
[Question] [ What general tips do you have for golfing in TI-BASIC for the TI-83/84+ series calculators? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to TI-BASIC (e.g. "remove comments" is not an answer). Please post one tip per answer. [Answer] Your calculator is pretty smart at inferring the end of lines for you, and thus you can omit quite a few characters. ``` :Disp "HELLO WORLD //is the same as... :Disp "HELLO WORLD" ``` `For(` loops have a syntax like this - `For(variable, start, end, increment)`, but you can omit the increment and it will use 1: ``` :For(A,1,5 //is the same as... :For(A,1,5,1) ``` and you can omit ending parentheses (at the end of lines) across the board: ``` :Output(1,1,A :int(A :round(A etc. ``` Tested on my TI-84 Silver Edition calculator If you think this is more than one idea (inferring endings) then I'll split them up [Answer] # Use `Ans` If you will only use an expression in the next line, don't store it to a variable! The special Ans variable is a one-byte token that stores the value of the last expression evaluated. Thus: ``` Xsin(A)->R Disp R+tanh(R ``` can be ``` Xsin(A) Disp Ans+tanh(Ans ``` saving two bytes. [Answer] # Use a lookup table encoded in floating-point numbers A slightly advanced tip: Small lookup tables are useful for code golf: it's very often that we need a function that maps, for example, 0 to 1, 1 to 2, 2 to 1, and everything else to 0. However, TI-BASIC arrays are not suited for this purpose: for one thing, they're one-based, and for another, a value cannot be extracted until the array is stored in `Ans` or a list variable. In my answer [here](https://codegolf.stackexchange.com/a/51421/39328), I store a small lookup table in a magic constant in base 11. Simply list the values you want to use, ``` {0,-1,5,-1,-1,2,9,-1,8,6} ``` convert to a useful form ``` {1,0,6,0,0,3,10,0,9,7} ``` write in your desired base (base 11) ``` .106003A097 ``` and convert to base 10 ``` -1+int(11fPart(11^Ans.0954191904 ``` The shortest array approach is 8 bytes longer! ``` {1,0,6,0,0,3,10,0,9,7}-1:Ans(X+1 ``` TI-BASIC only stores floats to 14 decimal digits, so you can store up to 44ish bits but only 14 decimal digits. This technique can often be improved further by using brute-force search to find a magic constant rather than base-N encoding. I'm still in the process of golfing the answer above, but the lengendary TI-BASIC golfer Weregoose [used this method](http://tibasicdev.wikidot.com/forum/t-154246/prime-factoring#post-2147207) to generate the differences between numbers coprime with 30 (that is, a repeating list of `6, 4, 2, 4, 2, 4, 6, 2` ) on the wiki/forum TI-BASIC Developer with this snippet: ``` 2+2iPart(3fPart(576e^(fPart(I/8 ``` The magic constant 576 was found using Mathematica, but if you don't own a copy use a script in your favorite language. [Answer] Put repeated expressions equation variables. EX: ``` Remainder(randInt(1,9),1 Remainder(randInt(1,9),5 Remainder(randInt(1,9),10 ``` Can be: ``` "randInt(1,9→u Remainder(u,1 Remainder(u,5 Remainder(u,10 ``` Note: it is hard to find a good use for this, but that does not mean you should forget equation variables :P Source: <http://tibasicdev.wikidot.com/selfmodify> -c4ooo from Omnimaga [Answer] # Skip unnecessary variable initialization Current consensus is to allow all code to be run on a fresh interpreter. We can take advantage of this—all uninitialized real variables start at `0` in TI-BASIC, and `Xmin` starts as the possibly useful value `-10`. So if you ever need to take a running total in a program that doesn't take input from Ans, or you really need a `-10` in one less byte, this tip can help you. [Answer] # Eliminate End statements for If blocks at the end of a program Saves two bytes: one for the End and one for the linebreak. It also allows you to use the implied Disp on the last line, often saving an additional byte. ``` [code] If A>5 Then Output(1,1,Ans²+Ans+A Disp 3ln(A End //end of program ``` Can be: ``` [code] If A>5 Then Output(1,1,Ans²+Ans+A 3ln(A //end of program ``` [Answer] # Smaller list generation If you need a list `{1,2,...,N}`, where N is, say, 42, the obvious way to create it is ``` seq(X,X,1,42. ``` However, one byte smaller than that is a neat hack using the `binomcdf(` (cumulative binomial distribution) command. ``` cumSum(binomcdf(41,0 ``` This only works when N is a constant, because the savings comes from replacing N-1 with its value in the code. There are two cases that allow even shorter code. If you already have a list `L1` of dimension N: ``` cumSum(1 or L1 ``` If you don't care about order: ``` randIntNoRep(1,N ;random permutation of numbers from 1 to N ``` [Answer] # Know your idioms Here are some snippets I commonly use in code golf: * Convert to truth-value (0/1): `not(not(Ans`, or `Ans and 1`. Which one to use depends on the parentheses needed. * Add one to a truth-value: `int(e^(Ans`. Saves an open-paren over `1+(Ans`. Very useful, because TI-BASIC has one-based arrays. * Map `{0,1}` to `{1,-1}`: `cos(πAns`. Saves one byte over `1-2Ans`. --- * Sign function of a number: `tanh(ᴇ9Ans` * Round towards positive infinity: `-int(-Ans` * Number of digits in a positive integer: `1+int(log(Ans` * Complex number to list `{Re,Im}`: `imag(Ans{i,1` --- * Convert string to list: `seq(inString("...",sub(Ans,X,1)),X,1,length(Ans` (where `...` is the search string) * Chop off first element of a list: `ΔList(cumSum(Ans` * Chop off last element of a list: `ΔList(cumSum(Ans)-Ans` * Check if all elements of list `L1` are unique: `SortA(L1:min(ΔList(L1` * Search for the number X in a list (returns first occurrence): `1+sum(not(cumSum(Ans=X` * Mode of a list when a single mode exists, and the list has at most 10 elements: (ugly, but short): `median(Ans,10^(seq(sum(Ans=Ans(X)),X,1,dim(Ans` [Answer] If you find yourself using ``` 0→G ;or any other variable ;other lines of code ``` Then, you could use (to save a byte): ``` DelVar G;other lines of code ``` This is because when you delete a variable (`G`), it becomes its default value, in this case, `0`. Then, you could put another line after the `DelVar` statement, *without a newline*. Be careful when putting crucial control statements directly after a `DelVar` statement. (Tested on TI-84) [Answer] # Which list variables to use? When using lists, avoid the default lists `L₁` through `L₆` in favor of named lists with one-letter names: `ᶫA` through `ᶫZ` (where `ᶫ` is the little L). Either one costs two bytes to reference (though `L₁` is a single token, it is a two-byte token) but when storing values in a list, you can drop the `ᶫ` symbol, saving a byte: ``` {1,2,3,4,5→ᶫA ``` can be ``` {1,2,3,4,5→A ``` The calculator checks the data type of the expression when deciding where the result is stored. Similarly, `Input A` or `Prompt A` will store to `ᶫA` if the user enters a list instead of a number. Several other commands can be used without the `ᶫ`, though most of them are rarely used in golfing. For example, `Matr►list(` allows the `ᶫ` to be removed in its third, fourth, and higher arguments. The general rule is that, if the command takes a list *variable name* and not a list *expression*, and if there is no alternative syntax that could put a different kind of variable there, then the command *might* work with the `ᶫ` left off. This doesn't work with modifying a single entry of a list: `1→ᶫA(3` cannot be changed to `1→A(3`. Of course, the best list variable to use is always `Ans`. [Answer] # Know your variable assignment costs If you use a `B`-byte expression `N` times, should you assign it to a variable? `Ans` costs `1+N` bytes to use (one for the linebreak and one for each time it's used, so use Ans when `(B-1)*(N-1)>2`. There can be only one `Ans` per line, so try all values for `Ans` that might be useful. Real variables (e.g. `X`) cost `3+N` bytes, so use them when `(B-1)*(N-1)>4`. List variables cost `3+2N` bytes, so use them when `(B-2)*(N-1)>5`. Equation variables are the least useful: they need `4+2N` bytes. Use them when `(B-2)*(N-1)>6`. ``` Min. bytes in an expression to save N \ var. | Ans | Real | List | Eqn ------------------------------------ 2 4 5 8 9 3 3 4 5 6 4 2 3 4 5 ``` When a function evaluates to a list, store it to a list rather than an equation variable like `u`; this saves one byte. Keep in mind that the presence or absence of close parentheses can often cause storing expressions to be advantageous if they're rearranged. Now I'll contradict myself and say that one should write code on one line as much as possible. Why? Usually when there's a long repeated expression on a line, it can be simplified. [Answer] ## int(rand over randInt( X+int(Yrand is equal to or fewer bytes than randInt(X,Y as randInt is a 2 byte token. Some potential benefits: X+ can be left out when lower bound is 0, saving two bytes X+ is necessary before randInt( anyway in certain situations, for example random from a step function like {2,5,8,11} X+int(Yrand(N can be used just as randInt(X,Y,N to generate a list of N random numbers ## Graphscreen initialization To use functions like Line( easily with pixel coordinates it's necessary to initialize the graphscreen axes to square pixels and remove axes: ``` AxesOff 84→Xmin 72→Ymax ZInteger ``` ## Clamp ``` min(U,max(L,N ``` Where N is the number or algorithm and U and L are upper and lower bounds ## Is N in List ``` max(N={X,Y,Z ``` ## More List math ``` L1*L2→L3 instead of for(A,1,dim(L1 L1(A)*L2(A→L3(A End This also works for things like this: not(L1 L1 and L2 ``` ## Output Disp and Text( can both be chained, so Disp A,B will Display A then B on separate lines and Text(28,40,A,B will print A next to B on one line If you only need to display a single thing at the end of a program you can drop the Disp command, the final line acts as an implicit Disp ## Tech from the optimal movement loop A lot of these optimizations are part of the tech used to move a character around the screen in the fewest bytes <http://tibasicdev.wikidot.com/movement> ## Token Size Lists <http://tibasicdev.wikidot.com/tokens> For help scoring ]
[Question] [ It is very hard to remember my password, so I came up with a way to generate a password. The way I generate my password is from a word or a sentence, following these steps: 1. Start from left to right 2. Find the count of each letter 3. Put letter with its count in an order * Letters with higher repetition will be in the end * Letters with the same repetition will be ordered alphabetically 4. Numbers and special letters will be ignored including whitespace (e.g. 9, 4, @, (, \*, etc. are ignored) 5. Group letters ignoring case. In the output, use the case of the last occurrence in the input 6. The count of the letter can be any number e.g. 5H17M345K 7. If input is all numbers or special letters then output will be empty string e.g. Input "12$\*34^!" then output "" 8. when order for the same occurrence alphabetically case does not matter e.g. 1a1B1c Example: ``` Input: Kitkat Tango (2k / 1i / 3T / 2a / 1n / 1g / 1o) Output: 1g1i1n1o2a2k3T ``` Another example: ``` Input: Database Partitions Task (1D / 5a / 4T / 1b / 3s / 1e / 1P / 1r / 2i / 1o / 1n / 3s / 1k) Output: 1b1D1e1k1n1o1P1r2i3s4T5a ``` Note: the letters with 1 repeat are in the beginning ordered alphabetically then the letters with more reps This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~19~~ ~~17~~ 16 bytes Saved 1 byte thanks to *Kevin Cruijssen* ``` áΣl}.γl}éεgyθJ}J ``` [Try it online!](https://tio.run/##ATgAx/9vc2FiaWX//8OhzqNsfS7Os2x9w6nOtWd5zrhKfUr//0RhdGFiYXNlIFBhcnRpdGlvbnMgVGFzaw "05AB1E – Try It Online") or as a [Test Suite](https://tio.run/##yy9OTMpM/V9TVvn/8MJzi3Nq9c5tzqk9vPLc1vTKczu8ar3@V9orKejaKSjZ6/z3zizJTixRCEnMS8/nckksSUxKLE5VCEgsKsksyczPKwbKFGcDAA) **Explanation** ``` á # keep only letters in input Σl} # sort by lower-case .γl} # group by lower-case é # sort by length (stable) ε } # map each to g # its length J # joined with yθ # the last letter J # join to string ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~66~~ 63 bytes ``` {[~] map {+$_~.tail},sort {+$_,.lc},m:g/<:L>/.classify(&lc){*}} ``` [Try it online!](https://tio.run/##HcmxDoIwEADQna@4gVDQpmwORJzcdHBwM4achJKGQknvFtKUX6/G9b118PaU5g0KDW0Kr/0NM64Qjnm3K0ZjoyTn@Q9S2T7KuRnrc3O/1Kq3SGT0Vha2r8IhxkS4gS7zrgLtfCZuhidkeOIyOiEzcUXGD9IAD/Rs2LiFfkmTkOkL "Perl 6 – Try It Online") ### Explanation ``` { } # Anon block m:g/<:L>/ # Match all letters .classify(&lc) # Group by lowercase {*} # Get hash values sort {+$_,.lc}, # Sort by array length and lowercase map { }, # Map to +$_~.tail # Concat array length and last letter [~] # Join ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 105 bytes ``` x=>x.Where(char.IsLetter).GroupBy(a=>a%32).OrderBy(a=>(a.Count(),a.Key)).Select(a=>a.Count()+""+a.Last()) ``` [Try it online!](https://tio.run/##hU67CsJAEOz9CgkIt6hXaKlJ4RMxoKBgvTmX5FAvsrsB/foYX42NUw3zYpz0nfh6UQU3FmUf8t5qHqoLMWZn@khJoiQa17c4udlDQUzGFch2JSmpEoNdclldJ3eDcYKd4QDsho/Eb8GgnZZVUAM9tGu6A9gdncnpK/31ulHURZuiNBzqUevAXin1gcz7Q5MLDtU8n5ho7fWE2t5jyMtfRADwrz9DxQyF2ltk9erLIM2YnF7d@gE "C# (Visual C# Interactive Compiler) – Try It Online") Thanks to dana for bringing it down to 105 bytes from 138 bytes. [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-P`](https://codegolf.meta.stackexchange.com/a/14339/58974), 14 bytes ``` f\l üv ñÊ®ÌiZÊ ``` [Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=ZlxsIPx2IPHKrsxpWso=&input=IktpdGthdCBUYW5nbyIKLVA=) ``` f\l üv ñÊ®ÌiZÊ :Implicit input of string > e.g., "Kitkat Tango" f :Split to an array of characters \l : Matching RegEx /[a-z]/gi > ["K","i","t","k","a","t","T","a","n","g","o"] ü :Sort & group (Preserves original order within each group) v : By lowercase > [["a","a"],["g"],["i"],["K","k"],["n"],["o"],["t","t","T"]] ñ :Sort Ê : By length > [["g"],["i"],["n"],["o"],["a","a"],["K","k"],["t","t","T"]] ® :Map each Z Ì : Last element of Z > ["g","i","n","o","a","k","T"] i : Prepend ZÊ : Length of Z > ["1g","1i","1n","1o","2a","2k","3T"] :Implicitly join & output > "1g1i1n1o2a2k3T" ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~67~~ ~~66~~ ~~41~~ 39 bytes ``` \P{L} O$`. $l$0 ir`\1*(.) $.0$1 N`\d+. ``` -25 bytes and a minor bug-fix thanks to *@Neil*. -2 bytes thanks to *@Neil* and *@Shaggy* together. [Try it online](https://tio.run/##K0otycxLNPz/Pyag2qeWi8tfJUGPSyVHRY0rsyghxlBLQ0@TS0VPTcWQyy8hJkVb7/9/l8SSxKTE4lSFgMSiksySzPy8YoWQxOJsBQfFeEMjYwA) or [verify all test cases](https://tio.run/##K0otycxLNPyvquGe8D8moNqnlovLXyVBj0slR0WNK7MoIcZQS0NPk0tFT03FkMsvISZFW@//f@/MkuzEEoWQxLz0fC6XxJLEpMTiVIWAxKKSzJLM/LxioExxtoKDYryhkTEA). **Explanation:** Remove everything except for upper- and lowercase letters: i.e. `Kitkat Tango 123!` → `KitkatTango` ``` \P{L} ``` Sort the individual letters case-insensitive ([thanks to *@MartinEnder* for this](https://codegolf.stackexchange.com/questions/148228/sort-an-option-string/148231?noredirect=1#comment431171_148231)): i.e. `KitkatTango` → `aagiKknottT` ``` O$`. $l$0 ``` Capture every chunk of case-insensitive repeated adjacent letters: i.e. `aagiKknottT` → [`aa`,`g`,`i`,`Kk`,`n`,`o`,`ttT`] ``` ir`\1*(.) ``` Prepend the length of every match, and only keep the last letter of every chunk: i.e. [`aa`,`g`,`i`,`Kk`,`n`,`o`,`ttT`] → `2a1g1i2k1n1o3T` ``` $.0$1 ``` Sort the numbers and letter groups based on the numbers: `2a1g1i2k1n1o3T` → `1g1i1n1o2a2k3T` ``` N`\d+. ``` After which the result is output implicitly. [Answer] # [Python 3](https://docs.python.org/3/), 105 bytes ``` s=input() t=s.upper() for n,c in sorted((t.count(i),i)for i in{*t}if'@'<i<'['):print(n,end=s[t.rfind(c)]) ``` [Try it online!](https://tio.run/##Fco9CgIxEEDh3lOkm0SWNHayAQsPYLHdYhHzg4MwCZlJIeLZY@wefK@@5VnoNAY7pNpFm4M4tr3W1Gbn0hQtQSEpLk1S1FpsKJ1Eo1nQ/B2nfo7yxQwXWHGFHcy5NpwPLYmi411sy0hRB3M3Y8DVi394Turmm6BgIVab5xf8AA "Python 3 – Try It Online") -1 thanks to [ArBo](https://codegolf.stackexchange.com/users/82577/arbo). [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~102~~ ~~96~~ ~~93~~ 87 bytes ``` ""<>Map@ToString/@Sort[(r=Reverse)/@Tally[r@#/." "->Nothing,Equal@@ToLowerCase@{##}&]]& ``` [Try it online!](https://tio.run/##FU7Pa8IwFL77VzxSEJVqeNXdpgR0p7lRZm6lh6fENrQ2W/JURunf3mXH7/d3I67NjdheaLzCFkYhXncf9K20O7G3XSXVyXkuZn77ZR7GBzOXSlPb/hZeJXIlQCx3n47raE3ffu7Uqhg9uqfxewpG9UkyTMtyOlIs78W75YYYNHWVEymIAzGdow9y8mzZui5EMTRiACkh/ij2NXm6cFwuJ5M8PuLiKhVFALMF9FihxQ5dRlmz1ingGQ9osPnnMEef2XXY6BcaYDEf/wA "Wolfram Language (Mathematica) – Try It Online") ``` Tally[r@#/." "->Nothing,Equal@@ToLowerCase@{##}&] Start with a char list #/." "->Nothing Remove spaces r@ Reverse the result Tally[ ,Equal@@ToLowerCase@{##}&] Make a list of letters and multiplicities, where two letters are considered the same if their lowercase values are equal. Then: ""<>Map@ToString/@Sort[(r=Reverse)/@ ... ]& (r=Reverse) Reverse each {letter, freq} to {freq,letter}. Then the standard Wolfram order function sorts lower frequencies first, with ties broken by by letters earlier in the alphabet, Sort[ ] exactly what we want. Map@ToString/@ @ has higher precedence than /@, so this effectively does Map[Map[ToString]]. ""<> StringJoin the nested list into a single string. ``` [Answer] # Pyth, ~~27~~ ~~24~~ 22 bytes ``` ssrD0m,lded.gr0k@+Gr1G ``` Try it online [here](https://pyth.herokuapp.com/?code=ssrD0m%2Clded.gr0k%40%2BGr1G&input=%22Database+Partitions+Tasksssssssssss%22&debug=0). ``` ssrD0m,lded.gr0k@+Gr1GQ Implicit: Q=eval(input()), G=lowercase alphabet Trailing Q inferred r1G Uppercase alphabet +G Concatenate with lowercase alphabet @ Q Keep those characters in Q which are also in the above .g Group the remaining characters, as k, using: r0k Convert k to lowercase (Grouping preserves relative order) m Map the sorted groups, as d, using: ld Length of d , Pair the above with... ed ... last element of d D Sort the above... r 0 ... by their lowercase values ss Flatten, then concatenate the result of the above into a string, implicit print ``` *Edit: Golfed 3 bytes by ordering by character before group, previous version: `sm+ldedo,lNr0eN.gr0kf}r0TGQ`* *Edit 2: Golfed off another 2 bytes by formatting output before any ordering, previous version: `sm+ldedlD.gr0krD0f}r0TGQ`* *Edit 3: Golfed off another byte by changing the filter, thanks to @FryAmTheEggman. Also had to fix a bug when OP clarified that a single letter can appear more than 9 times, which added a byte back on :o( Previous version: `srD0m+lded.gr0kf}r0TGQ`* [Answer] # Perl 5 (`-n`), ~~74~~, ~~68~~, ~~66~~, 65 bytes -6 bytes changing `-p` to `-n` and using `say` instead of `$_=join"",` -2 bytes thanks to Abigail using `\pL` instead of `[a-z]` -1 byte thanks to Kjetil S. removing `i` flag no more necessary after using `\pL` ``` s/\pL/($h{lc$&}+=1).=$&/ge;say sort{$a-$b||lc$a cmp lc$b}values%h ``` [TIO](https://tio.run/##PYqxDsIgFAB3v4KBNm0MxQ6dGjY3NXFwdHk0pDRFIDw0MW1/XSQO3nSXnFfBdKnQoqr7hPzuz7yiejEDLbe9aOtG0JKPqkd4E3QhLhQYleuaByDDw5MscnuBeSosdEqnKc4QyQ3s6P7sjhBBAipyhRCnODmLecH54/wvErt0zaFNzH4B) 58 bytes, in case there is no more than 9 occurence of each character ``` s/\pL/($h{lc$&}+=1).=$&/ge;say sort{lc$a cmp lc$b}values%h ``` [Answer] # [Python 2](https://docs.python.org/2/), 116 bytes ``` def f(s):a=s.lower();return''.join(`n`+s[a.rfind(c)] for n,c in sorted((a.count(c),c)for c in set(a)if c.isalpha())) ``` [Try it online!](https://tio.run/##Pc0xSwNBEIbh3l8xYHE7GBb2oo1il84mxXUiZLK3m4wXZo6dCeKvPy8K1s/38s3fflbpl2UsFWowfKZXixf9Ki3gSyt@bdJ18VNZwkEOD/ZOsVWWMWT8gKoNZJOBBUyblzEEilmv4itvMt78T4sHQq6QIxtd5jMFRFzmxuLrbffGPpHDQHLSDuE@nRInSdpTP22Hu//djpyOZAX21JydVWyNbPptjmmXSppuXdqn1vPWHocnWn4A "Python 2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~114/113~~ 105 bytes -9 bytes thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni) (using list-comprehension and `(||)` instead of `filter` with `elem` & shorten `length` to get rid of ugly `zip`)! ``` f s=id=<<[show(h r)++[last r]|l<-[1..h s],a<-['A'..'Z'],r<-[[x|x<-s,x==a||x==[a..]!!32]],h r==l] h=length ``` [Try it online!](https://tio.run/##XZHRSsMwFIbv@xRnRehGu0I2vRnNhbgLUZGBA8FaJLNZG1qTkZyxbvTaB/ARfZF6OgWnN@Gc5P@/8ycphatkXXfdGhxXOU@S1JVmNyzBjsIwrYVDsFlbJ@OUxXEJLosE1cFlEMfBU5BFlrq0aZtk7KKGc9G2tKYijrPBYDrJsohInNeZV/Ja6gLL7k0oDRxy4wH4tworgbAUujA@fL5/wM2WRvqsYIppZiZiUk2Xfi@dCxQr4SQshEWFymhHPlf9sa3YnElW9Va2YHaipu58eSF6wLCX3RsslS5GQDeFQuKV0Sg1Os9rfjEHUrewB87hQEk3W3xAe6fhDPq3gQbCEL6n@n153NwfPUSXdqcoJIe1UDVZfNls5CvKfHaiPhwRz1gYnP2D7Igg@@GwhuYn1Qt1J/mGdDLqrunfTASPxtb54As "Haskell – Try It Online") [Answer] # [Red](http://www.red-lang.org), ~~220~~ ~~196~~ 206 bytes ``` func[s][a: charset[#"a"-#"z"#"A"-#"Z"]trim/all form sort/skip collect[foreach c sort unique reverse rejoin parse s[collect[any[keep[a]| skip]]][i: 0 foreach d s[if(c% 32)=(d% 32)[i: i + 1]]keep i keep c]]2] ``` [Try it online!](https://tio.run/##bYwxT8MwEIX3/IrTRZWKECqULRIDMxti4nTDyTlTN6kdbAepFf89tSOViVve0733vqj98q49cWM7WOzsDSUm6cAcJCbN1KLgQ4sXbPG1mk/kHN1pJ@MINsQTpBDzLg1uAhPGUU2m8lYxBzBr1szefc8KUX@0EIseg/MwVTwkuo3En2lQnUj4FyqOmcl18NjccH1pO7s1G3je371s@1VrxcE9PDHXdfGrGOY9L1N0PoMFfHN5kAwf4r/C32Hzb47LFQ "Red – Try It Online") Thanks to Shaggy for finding a bug. [Answer] # [Scala](http://www.scala-lang.org/), 103 bytes ``` _.filter(_.isLetter).groupBy(_%32).values.map(l=>l.size+""+l.last).toSeq.sortBy(_.toLowerCase).mkString ``` [Try it online!](https://tio.run/##XY5NawIxEIbPu79iWBASLHOwt8IuWHpsQbD3ZdTpEo1Jmhm1Kv72dKngoaf3ObxfsiZPJa62vFb4IBeAf5TDRmCeElzrqq6O5GHgwJmUFyRyinnzAkvNLgzQdg8qPX45r5xNj07eWUe0OOR4SK9n00@eZxbHrgML7ikZ33YexV142jRTj55ELWpc8jdKzDpGpO2M/FmexFrc7@5LpUqjqA/m/yvTvJHSioRhQVmduhgEPkl2jbX1rZRf "Scala – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` fØẠµŒlĠLÞịµL,Ṫ) ``` A full program printing the password as specified (as a monadic Link it yields a list of lists each containing an integer and a character). **[Try it online!](https://tio.run/##AT0Awv9qZWxsef//ZsOY4bqgwrXFkmzEoEzDnuG7i8K1TCzhuaop////RGF0YWJhc2UgUGFydGl0aW9ucyBUYXNr "Jelly – Try It Online")** [Answer] # [Husk](https://github.com/barbuz/Husk), 15 bytes No problems with imports when using Husk, therefore we can make use of the various handy functions such as `groupOn`, `sortOn`, `toLower` etc: ``` ṁ§:osL→ÖLSġÖ_f√ ``` [Try it online](https://tio.run/##AS4A0f9odXNr///huYHCpzpvc0zihpLDlkxTxKHDll9m4oia////S2l0a2F0IFRhbmdv "Husk – Try It Online") or [try them all!](https://tio.run/##AVwAo/9odXNr/23Cp28rYCsiIC0@ICJzb3PigoHCtv/huYHCpzpvc0zihpLDlkxTxKHDll9m4oia////S2l0a2F0IFRhbmdvCkRhdGFiYXNlIFBhcnRpdGlvbnMgVGFzaw "Husk – Try It Online") ## Explanation ``` ṁ§:(sL)→ÖLSġÖ_f√ -- example input: "Kitkat Tango" f√ -- `filter isAlpha`: "KitkatTango" S _ -- apply _ to .. then .. Ö -- | sortOn: `sortOn toLower` ġ -- | groupOn: `groupOn toLower` -- .. compose: `groupOn toLower . sortOn toLower` -- `sortOn toLower` (stable): "aagiKknottT" -- `groupOn toLower`: ["aa","g","i","Kk","n","o","ttT"] ÖL -- `sortOn length` (stable): ["g","i","n","o","aa","Kk","ttT"] ṁ -- map and flatten (`concatMap`) § -- | fork argument .. → -- | | `last`: ['g','i','n','o','a','k','T'] (sL) -- | | `show . length`: ["1","1","1","1","2","2","3"] : -- | .. and `snoc`: ["1g","1i","1n","1o","2a","2k","3T"] -- : "1g1i1n1o2a2k3T" ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 28 [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. ``` (∊⍤∧⌊(⊂⍕⍤≢,⊢/)⍤⊢⌸⊢)'\PL'⎕R'' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X@NRR9ej3iWPOpY/6unSeNTV9Kh3KojfuUjnUdcifU0Qu2vRo54dQFJTPSbAR/1R39QgdfX/aY/aJjzq7QPyPP0fdTUfWm/8qG0ikBcc5AwkQzw8g/@nKah7Z5ZkJ5YohCTmpefDgToA "APL (Dyalog Extended) – Try It Online") `'\PL'` non-letters `⎕R` PCRE **R**eplaced with `''` empty strings `(`…`)` apply the following tacit function:  `⌊` with the lowercase as keys,  …`⌸` apply the below tacit function to each key and its corresponding set of values, namely  `⊢` the argument:   `(`…`)` apply the following tacit function   `⍤` to   `⊢` the list of values:    `⊢/` the last value    …`,` prepend the following to that:     `⍕` the stringification     `⍤` of     `≢` the tally    `⊂` enclose (to treat character list as single string)  `∊` **ϵ**nlist (flatten)  `⍤` the  `∧` sorted-ascending version of that [Answer] # [JavaScript (Node.js)](https://nodejs.org), 127 bytes ``` s=>[...s].sort(o=(x,y)=>p(0+x,36)-p(0+y,36),p=parseInt).join``.match(/([a-z])\1*/ig).map(x=>(l=x.length)+x[l-1]).sort(o).join`` ``` [Try it online!](https://tio.run/##NY2xTsMwFEV3vsKb/UjiUiGxIGeiQ8XCwJZG6iM4qVvjZ9lPyOXngyvBdI/uke494zfmKbnIXaBPu85mzaYftNZ51JkSKzKqtFcwfVQPTWkfn6C70fVGbTQRU7b7wKDP5MLxqL@Qp5PaqAG7nxEO2/uNW6C2URXTK2@K9jYsfIKmDL7bjvB38z@wshnkq@MLsnjHsJBshXxBxg/MVrxhYseOQq4yX@T4fMd6prTDesqmn6ohb7WnRbFohDwEWWNWDADrLw "JavaScript (Node.js) – Try It Online") * `parseInt(numberAsString, radix)` will try to parse integer in the beginning of string. For example, `parseInt('120px', 10)` will output 120. When parsing failed, it returns `NaN` instead. We connect an `'0'` to the beginning of each character so it will return `0` for any non numeric-alpha characters. And we can sort same letters together and non-alpha character to the beginning by this algorithm. * After `sort` and `join`, `"Hello world!123"` would become `" !123deHllloorw"`. An matching against `/([a-z])\1*/ig` will ignore any non-alpha character and split the string into chunks with same letters. `. * `map` convert `"aaa"` to `"3a"` as required in the question. * The second sort use same function as the first one. Thanks to the number system, `"3b"` would be less than `"12a"` in base 36 just as we expect: It compare counts first (`n div 36`), and compare the letter later (`n mod 36`). * Finally `join` them together. --- # [JavaScript (Node.js)](https://nodejs.org), 146 bytes ``` f=(s,...a)=>(s=s.replace(/[^a-z]/ig,''))?f(s.replace(RegExp(s[c=0],'ig'),x=>(l=++c+x,'')),...a,l):a.sort((x,y)=>p(x,36)-p(y,36),p=parseInt).join`` ``` [Try it online!](https://tio.run/##RY0/TwMhGId3PwUbLzmOqk0caqiLHYyLMW7nmb4ih7QECLwxV7/8Sbs4PcPz@3PAH6ym@Ex9TF92WSYNVSqlUOgtVF1VsTmgsbAaPrD/HVfeSc6FeJjg371at5sz1MHo61Fy77iQc@sH3XWmmy@Fy6gMYoOqpkIAszy1j9y4vhN9htOZMuuMpdqnSEIdko/7/UJ64M@ejkjsDaNLXDL@iISfWC17wUKefIq1yXo8u5vbNR/vr0hNqezQfAPprWmBFKwKyQGxjvH3yBsmICHE8gc "JavaScript (Node.js) – Try It Online") [Answer] # Java 10, ~~223~~ ~~209~~ 301 bytes ``` s->{int i=32,t;String M[]=new String[i],r,R="";for(var c:s)M[c%32]+=c>64&c<91|c>96&c<123?c:R;for(;i-->0;M[i]=(t=r.length()-4)>0?t+r.split(R)[t+3]:R)r=M[i]+R;java.util.Arrays.sort(M);for(var p:M)R+=p;return R;} ``` +92 bytes as a fix for inputs with more than 9 of a single letter.. Will see if I can bring that down again with a different approach. [Try it online.](https://tio.run/##lVJRa9swEH7Pr7gZNiRsizQphcazu25921yG1zfXjIuiJEocyUiXlNDlt2dyMWMPXWH3IHTS932n@04bPGC6WWzPskXvoURtnkcA2pByS5QK7vsU4Ac5bVYgmVyjqxvwPAvnp1FYPCFpCfdgIIezT4vnwAadTycJZQOvrJvcqKdBptZN4pIqj6JsaR07oAM587ys5fvppIlzWVxdfpAfry9@yeL6KuwuJtMbOate0JlO02KclUEkZ5Q70SqzojXj6SUvxjcUO@G7VhOreE3xtJlV3OU9Oq6yTehW7Em34tY5PHrhrSNWJgyTOU@L/oWfj6QYG8fIhVNdGyy4bVsWPT7eRUkUcS6k3XXo1INlf8Pn/4Bz/qfFblbyKs67zCnaOwNVdjpnvYHdft4GAwcfD1YvYBfmwAazGkA@DOHoSe2E3ZPowhW1hhkhWfRV0xYJHtCsbCTIfgkzemmQ9fXfpN4h4Ry9gu/oSJO2xgcdv4VP734G1/9T7Zt9I/DVWHiwS6C1Ao87Ba2i8PNeLXsanc6/AQ) **Explanation:** ``` s->{ // Method with character-array parameter and String return-type int i=32, // Index-integer, starting at 32 t; // Temp-integer, uninitialized String M[]=new String[i], // Create a String-array of size 32, filled with null by default R="", // Result-String, starting empty r; // Temp-String, uninitialized for(var c:s) // Loop over the characters of the input-array: M[c%32]+= // Append the string at index code-point of `c` modulo-32 with: c>64&c<91|c>96&c<123? // If the character is a letter: c // Append the character : // Else: R; // Append an empty String for(;i-->0 // Loop `i` in the range (32, 0]: ; // After every iteration: M[i]= // Replace the String at index `i` with: (t=r.length()-4) // Set `t` to the length of String `r` minus 4 // (the minus 4 is for the prepended "null") >0? // If this length minus 4 is larger than 0: t // Set the String to this length minus 4 +r.split(R)[t+3] // Appended with the last character of `r` as String : // Else: R) // Make the String at index `i` empty r=M[i] // Set `r` to the `i`'th String +R; // Converted to String // (null becomes "null", to prevent NullPointerException-errors) java.util.Arrays.sort(M, // Now sort the array of Strings on: (a,b)-> // For each pair of two Strings: new Byte( // Convert the first String to a number (0+a).replaceAll("\\D","")) // after we've added a leading 0 and removed all non-digits .compareTo( // And compare it to: new Byte( // The second String converted to a number (0+b).replaceAll("\\D","")))); // after we've added a leading 0 and remove all non-digits for(var p:M) // Loop over the Strings of the array: R+=p; // And append each to the result-String `R` return R;} // And finally return the result-String `R` ``` [Answer] # [Swift 4.2.1/Xcode 10.1](https://developer.apple.com/swift/), ~~1054~~ ~~1050~~ ~~1048~~ ~~370~~ ~~368~~ 364 bytes ``` s.map{String($0)}.filter{$0.rangeOfCharacter(from:.letters) != nil}.reversed().reduce(into:[String:Int]()){d,s in if let l=[s.uppercased(),s.lowercased()].first(where:{d[$0] != nil}){d[l]=d[l]!+1}else{d[s]=1}}.sorted{let c=$0.value-$1.value;return c==0 ?$0.key.compare($1.key,options:.caseInsensitive) == .orderedAscending:c<0}.map{"\($0.value)\($0.key)"}.joined() ``` [Try it online!](https://tio.run/##fVE9T8MwEN35FUfVwRbFSiWmQEAIhIQYQIKtZDDxpZimduS7tEJRfnu5tMCEWKx3X@/ePdPW13y28@s2Joa72AVn2cdwVHehgiUGTJbxyRJtY3KKcnjm5MNSw@nlN4QeEnKXwo7M2rb9IaummR5M7RvG1E8zk2xY4mN9826TrSSn6hTXuWmQJSANxwUE3wwm4UZidEoLdF2FygeO@eLAmt8HLpXWvZsR@AC@BmGApliQ6doWU2X3szMyTdz@hqUIScRq@44J894tpln5s1G4Fk1ZjM/xyXzAhlAyVBbzYTAkrqDrxx1VIVdsbNPh6XR@AOeHu6VUZHAl5RV@miquW5tQSZOEs9iOdlJuRin3gTCQZ79BDUUBRjwVRe6aKgxuvK@6yIa9i5NX9bNP76GQ6clgPqIP40m74agVR1j99UeTB88ry/AipseJ1v@13lq2b6INnmxivxcrc7SSsd0X "Swift 4 – Try It Online") @KevinCruijssen also removed some spaces. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes ``` F⌈Eβ№↧θιFβ¿⁼№↧θκ⊕ι⁺⊕ι§Φθ⁼↧λκ±¹ ``` [Try it online!](https://tio.run/##bY7PCsIwDIfvPkWOGdSDZ0/iHxio7OALZFumZV3r2lT39rUOQQQDye@QLx9pbuQbRyalznnAE016iEPOO9YKti5awaN7sm8oMI6FAl3kgpmuC9Ad4H6MZAL@g/vcpW08D2yFW3wfQ@V1BisTA/7uFGyktC1PeNBG2OOo4CP/as2szePMVxLG1fufdUo7EqozABV50aKdDXCh0C/S8mHoBQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F⌈Eβ№↧θι ``` Run through the lowercase alphabet and find the highest character count in the lowercased input. Loop over the implicit range. (The loop actually goes from `0` to `n-1` so I have to increment the loop variable at each use.) ``` Fβ ``` Loop over the lowercase alphabet again. ``` ¿⁼№↧θκ⊕ι ``` If the count of the current letter is equal to the outer loop value... ``` ⁺⊕ι§Φθ⁼↧λκ±¹ ``` Concatenate the current count with the last occurrence of the current letter and implicitly print. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` fØẠŒuL,ṪƊƙ$ŒuÞ ``` [Try it online!](https://tio.run/##y0rNyan8/z/t8IyHuxYcnVTqo/Nw56pjXcdmqgA5h@f9///fJbEkMSmxOFUhILGoJLMkMz@vWCEksTgbAA "Jelly – Try It Online") Full program. [Answer] ## NodeJS, 299 bytes, -6 bytes thank to @tsh Not so beauty but it work! ``` (x,l={},g=p=>p.charCodeAt(),q=p=>p.toLowerCase())=>Object.entries([...x[R='replace'](/[^a-z]/gi,'')].reduce((m,n)=>(r=q(n),l[r]=g(n)>96?1:0,{...m,[r]:-~m[r]}),{})).sort((a,b)=>a[1]^b[1]?a[1]-b[1]:g(q(a[0]))-g(q(b[0]))).map(([m,n])=>[n,m]).join``[R](/,/g,'')[R](/[a-z]/g,v=>l[v]?q(v):v.toUpperCase()) ``` ## Javascript (ES8) (Firefox or Chrome), 294 bytes, -1 byte thank to @tsh With new `.flat` method, I can save 10 bytes: ``` (x,l={},g=p=>p.charCodeAt(),q=p=>p.toLowerCase())=>Object.entries([...x[R='replace'](/[^a-z]/gi,'')].reduce((m,n)=>(r=q(n),l[r]=g(n)>96?1:0,{...m,[r]:-~m[r]}),{})).sort((a,b)=>a[1]^b[1]?a[1]-b[1]:g(q(a[0]))-g(q(b[0]))).map(([m,n])=>[n,m]).flat().join``[R](/[a-z]/g,v=>l[v]?q(v):v.toUpperCase()) ``` Try this online: <https://repl.it/repls/ConcernedHorribleHypothesis> [Answer] # [R](https://www.r-project.org/), ~~131~~ 129 bytes ``` cat(paste0(N<-by(X<-utf8ToInt(gsub('[^a-z]','',scan(,''),T)),G<-X%%32,length),L<-intToUtf8(by(X,G,tail,1),T))[order(N,L)],sep='') ``` [Try it online!](https://tio.run/##bY/NasMwEITvfoolIVgC2UR2Cz04t0AoDSEHFwJpCmtXdoWNZKQN6Q99dtduqWmhexzmm5l1/RwuDjvwJRomwpCDNoBQnU1J2hogC9i29gIKvVYOSHnSpg6q1Y@F0Qvx95HPokmL45gPel8isQ49qSXbZVHxyg5ZdKbqJre3hljtzwULj48YvZ3CoVxMK0TOudhk0WGxSBPRKlPTMxfbLNKGcns/JLAxTGwEoW6F/AKO1j0px3Ziy0/Cq241BPUfQVCx2Z2mBglyNLWdcZiDrKWWRtoEkybNg3Fn@GBCPprXSFigV7BHR3r8xw@kb77BQq6lks0Iy710iU79VX6NfyN@9033T7Fc2v4T "R – Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), 158 bytes ``` ¬t=(c=Dict();C=Dict();for i=eachmatch(r"\w",t);l=i.match;k=lowercase(l);c[k]=get(c,k,0)+1;C[k]=l;end;*(["$v$(C[k])" for (v,k)=sort([(v,k) for (k,v)=c])]...)) ``` Original ungolfed version with same logic: ``` function password(text) letter_counts = Dict() cases = Dict() for i in eachmatch(r"\w", text) letter = i.match[1] letter_key = lowercase(letter) letter_counts[letter_key] = get(letter_counts, letter_key, 0) + 1 cases[letter_key] = letter end sorted_counts = sort([(value, key) for (key, value) in letter_counts]) return string(["$v$(cases[k])" for (v,k) in sorted_counts]...) end ``` [Try it online!](https://tio.run/##VY4xDsIwEAR7XhFZFHdgRVBbrqCjoaALKQ5jwNjYyDkCj@IVfCwkIAq61exotedbcDR/dN3ryRqMXjrDgGrxC4eUC6ctmdOF2Jwgi@1dSEYVtCs/SHkd0t1mQ42FgMpUvtZHy2CklzOcztViIEHZuFcTqMS4HcOAUBTDOrTSo25SZqg@@Uu9bFGbGuuyLBG70TW7yCHC6wli5dgTFxuKxyQQ/7olMe36K8WaMjt2KTa92Pje694 "Julia 1.0 – Try It Online") [Answer] # Perl 6, ~~86~~ 82 bytes ``` {[~] flat map *[0,2],sort map {+$^b,$^a,$b[*-1]},kv classify &lc,.comb: /<alpha>/} ``` [Answer] ## Rebol, 149, 146 bytes ``` f: func[s][l: charset[#"a"- #"z"#"A"- #"Z"]rejoin sort/skip collect[parse sort s[any[copy t[copy o l any o](keep length? t keep last t)| skip]]]2] ``` [Try it online!](https://tio.run/##TY1BSwQxDIXv@yueGQ8qLOLqaS8iePMi4slSIVM6s2VKU5p4WPG/jzO7IF5e8j5e8lrsJc9vq8L5edhj@CrBqXd5j3DgptFcR0xbdPRNHT2dtg/yJlu1lsoIlWa3OqWKIDnHYK6udycOdVyOLkg9ws5DkLEwiL@aYqzIsYx2eIThbFkNdv2D9aP3fuc3c23SRwygl2QTG965jEKbP/zMxj0vla/cLFmSoktGp3@Ru93lzf3D5wXNvw) Ungolfed: ``` f: func [s] [ l: charset[#"a" - #"z" #"A" - #"Z"] rejoin sort/skip collect [ parse sort s [ any [ copy t [copy o l any o] (keep length? t keep last t) | skip ] ] ] 2 ] ``` Example usage in Rebol console: ``` >> f "Kitkat Tango" == "1g1i1n1o2a2k3T" >> f "Database Partitions Task" == "1b1D1e1k1n1o1P1r2i3s4T5a" >> f "12$*34^!" == "" ``` ]
[Question] [ Having a function *f* that takes arguments *x1*, *x2*, …, *xn*                                                – ie.  *f : X1 × X2 × … × Xn → Y* – [currying](https://en.wikipedia.org/wiki/Currying) redefines *f* as a function taking a single argument *a1* which maps to yet another function. This technique is useful for partial application, for example with a curried `pow` function we could write `exp = pow(e)`. ### Example Assuming we have the following function *f* taking three arguments (*f : X1 × X2 × X3 → Y*): ``` def f(a,b,c): return a + b * c ``` Currying this function leaves us with *f\_curry: X1 → (X2 → (X3 → Y))*, if we would now call that function twice with `f_curry(1)(2)` we would get a function (`h`) equivalent to the following returned: ``` def h(c): return 1 + 2 * c ``` The curried function `f` could be written like this (Python 3): ``` def f_curry(a): def g_curry(b): def h(c): return a + b * c return h return g_curry ``` [Try it online!](https://tio.run/##lZFfS8MwFMXf8ykO7CFJV8VuUqToo99AfFEZaZf@wS4rSSoO2WevSZe1E0GwD83Juef@btN0B1vv1XoYtrJEuSl6rQ9M8IwA3qmCk4/OyatZEXaAlrbXCgJL5IhQkAuzJpMMGEKIXxtp8IAXV6ZhIo0xPwtY8e4iCYSu@p1UNg4cg7JXhW32ykcaVWEFdiJu@ZQ2F2CW8Jn9H/Cc@UljqzPwL5rqd7nUvzrZemxeoGyUaCE/Oy2NcVMzR1m6w0RYk7eh042yjD5OZeqKdxGFX@mzaHvpVZqcradDJ1/HVHKziugV5YSUez0eamOsRqMQfry/OG@7C5AfomXnCHd@mPuV4T5JzRHwKr0d1ZFeO@JO2KkjhnuNOx7Dui84ac6Hbw "Python 3 – Try It Online") ## Challenge Your challenge will be to curry a function as described above, here are the rules: * Input will be a [blackbox function](https://codegolf.meta.stackexchange.com/a/13706/48198) which takes at least 2 arguments * The input function will always have a fixed number of arguments (unlike `printf` or similar, note: you need to support functions with any number of arguments ≥2) * If your language uses curried functions by default (eg. Haskell), you may expect the input function to be defined over *N*-tuples, instead of a "higher-order function" * You may take the number of arguments as input * Output will be the input's curried equivalent\* * You may assume that the output function will only ever be: + called with less or equal to the number of arguments that the input function takes + called with arguments of the right type --- \* This would mean for an input `f` with `N` arguments and an output `h` that for all valid arguments `a1,…,aN` it holds that `f(a1,a2,…,aN) == h(a1)(a2)…(aN)`. [Answer] ## JavaScript (ES6), 35 bytes ``` f=g=>g.length<2?g:a=>f(g.bind(f,a)) ``` [Answer] # [Idris](https://www.idris-lang.org/), 204 bytes ``` import Data.HVect C:(a:Vect n Type)->(HVect a->Type)->Type C[]T=T[] C(h::t)T=(x:h)->C t(T .(x::)) c:{a:Vect n Type}->{T:HVect a->Type}->((b:HVect a)->T b)->C a T c{a=[]}f=f[] c{a=h::t}f=\v=>c(\u=>f(v::u)) ``` [Try it online!](https://tio.run/##VY0xb4MwFIR3/4pTJjtAlmSyZC90aKWqHWp1IR6MgeAhgIhJW6H8dmpoqiTLe3f3Tt9zRe9O0@SOXdt7PBlvNs@fpfUk5dTwWaGB@ulKlki6XGASeQ3mRdJMK6EyTVJac@6ZEvSb1@GawlOFTXCcMWL5@MC7JHJU/IEYIkrz/2zmI184BorY0YhMXypRhVezmZ8Fuz8Lael@ELKiZ84HxqahsUPfu7IAxx8sezM@xjI@fO@ag0Yir5Lc6pmJkcewGgKnuv0CNWuDCPk6Z4giWEKOxjX85Z2yRYmiJUAXMP61Ab0jbWPsYqx8vdLsvmJxK22xWxps@gU "Idris – Try It Online") Sounds like a job for dependent types! Well, maybe. --- **C** is a currying type function. Given a vector of types **a = [t1, t2, … tn]** and a type function **T : HVect a → Type**, it returns a new type: > >            **(x1 : t1) → (x2 : t2) → … → (T [x1, x2, … xn])** > > > Here, **HVect** is the [heterogeneous vector type](https://www.idris-lang.org/docs/current/base_doc/docs/Data.HVect.html) from the Idris Prelude — the type of *n*-tuples whose elements are of *n* different types. **c** is a function that takes **a** and **T** as implicit arguments, and then converts an *uncurried* function `f` of type **((b : HVect a) → T b)** into a *curried* one of type **C a T**. (**C** simply describes what we wish to do; **c** actually does it. But we can't get away with not defining **C**, as Idris demands that every top-level definition have a type signature.) --- The TIO link gives a usage example. If we define a function on 3-tuples **(Nat, Nat, String)** as follows: ``` uncurried : HVect [Nat, Nat, String] -> String uncurried [a, b, c] = show (a*a + b*b) ++ c ``` then **`uncurried [3, 4, "th"]`** yields the same result as **`c uncurried 3 4 "th"`**. Idris infers the arguments `a=[Nat, Nat, String]` and `T=const String` for us, I believe. I based this code on [this gist](https://gist.github.com/timjb/6258302) by timjb. [Answer] # [Python 3](https://docs.python.org/3/), ~~54~~ 53 bytes ``` c=lambda n,f,*x:lambda y:(f,c)[n>1](*1%n*(n-1,f)+x,y) ``` [Try it online!](https://tio.run/##LctBCsIwEEDRtTnFbISZdLqIRZBAvYi4SNIOCjotIUJz@thFlx/eX2t5LTq0lsZP@MYpgLKw3fxR1aNwoofe3ROtO6tF7R0LdRtXatMsIBg47sabU57LLysE6CCChWTMmt9aMOGwL3ghvBLeiNof "Python 3 – Try It Online") [Answer] # [R](https://www.r-project.org/), 96 bytes ``` y=function(f,n=length(formals(f)),p=list())function(x,u=c(p,x))`if`(n<2,do.call(f,u),y(f,n-1,u)) ``` [Try it online!](https://tio.run/##ZcxNCsIwEIbhfU8x4GZGp2q0BZXmLqZpooWYlNpCi3j2Gn8QxFnN4vnedppGaXuvuzp4tOylM/7UndGG9qLcFS0RN9LV1w6JvnDgXmpseCA61vaIvthwFZZaORcjPfH4bKUivjTZEKBI4TtWXLImuIGCBZQwBw33pFTtP@LqzdIPW0F1T2I6BMKccEO4JXjdDMzQGN2Z6gBCRBN7hGK9JsxeMKcfs98ts2R6AA "R – Try It Online") --- [Previous version (97 bytes)](https://tio.run/##PYxBDsIgFAX3nuIv/1NqYo27chiKoCTIbwokbYxnx3bT5SQzM7e2al@TLUESe5V0dOlV3uxl/piY2QNq0jHkwsAhLqpqy5NagOA5DT2ecrUmxm1R4WJ2p3W/dbcNmxehoaOjNmpUFvQlQxca6UyWfrsvAn6Ae/Ad7Q8 "R – Try It Online") -1 byte thanks to @JayCE [Answer] # [Coconut](http://coconut-lang.org/), 54 bytes ``` def c(f,*a): try:return f(*a) except:return c$(f,*a) ``` [Try it online!](https://tio.run/##NY1BCoAgFAX3nuItWvxftqh2Qt3FfgptLEShoLubEG2HYUYOOUJOpWzOQ8jr1rJRSPE20aUcAzxVpOAucWf6oTSfWjxmkNWrFka/wKLDihaiVI0xDUwj08R4FpxxD3X0Ag "Coconut – Try It Online") --- # [Coconut](http://coconut-lang.org/), 40 bytes Port of [Erik's Python answer](https://codegolf.stackexchange.com/a/162240/64121). ``` def c(f,n,*a)=n and c$(f,n-1,*a)or f(*a) ``` [Try it online!](https://tio.run/##FYwxDoAgEAR7X7GFxR1igdTwFzglsTkM0c6/o1STTDIjVao@d@/7USBUrFqTOCiS7pB5iNUNVRsK/ewFAZRstsJYIxIWZBjINI3cMzmmjckz3oirnfrPPw "Coconut – Try It Online") [Answer] # C++~~17~~ 20, ~~214~~ ~~200~~ ~~189~~ 184 bytes ``` #include<regex> template<class R,class A,class...B>auto c(std::function<R(A,B...)>f){if constexpr(sizeof...(B))return[=](A a){return c<R,B...>({std::bind_front(f,a)});};else return f;} ``` [Try it on Wandbox](https://wandbox.org/permlink/tHGtWjVuRWMc4hlv) (TIO doesn't support gcc 9+ which is needed for std::bind\_front) This is a template function that takes an std::function of any arity/type and returns a curried lambda expression. Uses constexpr if FTW. If any template gurus have any idea how to eliminate or reduce the need for std::function let me know. Edit: replaced inner lambda with std::bind\_front. Edit: replaced include with shorter <regex> Ungolfed version: ``` #include <functional> template <class R, class A, class... B> auto curry(std::function<R(A, B...)> f) { if constexpr(sizeof...(B) > 0) { return [=](A a) { return curry(std::function<R(B...)>{std::bind_front(f, a)}); }; } else { return f; } } ``` [Answer] # [Python 2](https://docs.python.org/2/), 60 bytes ``` c=lambda f,n,l=[]:lambda a:n-1and c(f,n-1,l+[a])or f(*l+[a]) ``` [Try it online!](https://tio.run/##PYxNCsIwFIT3PUV2SeyrUN0FepKQxTM/WIkvIaZQj@UZPFhUrG5mvo@Byfd6TnRozU4RryeHLABBnLRRm6OiYURyzIr3NIwQe41GpsKC2H255TJTZcW7xXrx/1lVEKsEbcVMealCwtbS9D9qt1r2xeeI1nfHTvMLRsyeEgfG6RPPBzcv "Python 2 – Try It Online") The footer is a tester which uses STDIN in the following way per line: 1. The function itself 2. The number of the function's arguments, ≥2 3. A list of the arguments (`[a,b,...]`) Note that, while a list of the arguments is given as input in the tester, in reality, the curried equivalent gets prepended to the list and the list is reduced by function call. A similar 55-byte version has been kindly provided by [ovs](https://codegolf.stackexchange.com/users/64121/ovs): ``` c=lambda f,n,*l:lambda a:n-1and c(f,n-1,*l,a)or f(*l,a) ``` [Try it online!](https://tio.run/##VYxBCsIwEEX3niK7zGgqlO4KnqSUMKYpVtJJSFOpx/IMHiy2ooKbz388eOGeLp6rnM3J0XjuSPSK1d7VH6Kai5K4EwZWUZSrUoQ@ih7eL4c4cAKthzH4mLQG2c9skvdukniMtpuNhV96qXtYUDUG7I0cDBzmBIhqa3wB28OfRMxTimsqODJ2V@0aeSVHwbKXSkje5vmQ7Qs "Python 3 – Try It Online") [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/attache), 5 bytes ``` Curry ``` [Try it online!](https://tio.run/##SywpSUzOSP2fbGX737m0qKjyP1diSkp0hY5CZayCla1ChYK2QiVIyBgspqNQhRAG4iqugKLMvJLo5Gigkthoo9ho49hYZDHj2GjD2GiT2GhzoDhXbkF0Hlh/mH4eXBVQEKgpOhqIlRKVwCb8BwA "Attache – Try It Online") Simple built in, largely uninteresting. But, here's a version from scratch: ## Attache, 35 bytes ``` {If[#__2<#_,Fold[`&:,$'__],_@@__2]} ``` Explanation: ``` {If[#__2<#_,Fold[`&:,$'__],_@@__2]} { } lambda If[ , , ] if #__2 the number of parameters after the first <#_ is less than the arity of the first Fold[ , ] then fold: `&: right-function bonding $ over this function '__ paired with the rest of the parameters , otherwise: _@@ call the first parameter __2 with the rest of them ``` [Answer] # [Rust](https://www.rust-lang.org/), 73 69 bytes ``` macro_rules!c{($f:tt$(($n:tt:$a:ty))*)=>{$(move|$n:$a|)*$f($($n),*)}} ``` [Try it online!](https://tio.run/##PcpBDoMgEIXhfU@BySxmDF1odzT2KoYaSEwEU0CDEc9O0SadxbzF97vFh5yNHNzcu2VSvhp2BC1CAESwZQVIETaimrrXDmjmVaUCIBPVoBFKRbym48jaMiNHi7TfWLlJBRZZx1IU46Pl2/lTvG/Pv@qiQ4UR5WmE72voF0jvlQu9@pxBw1viGhvCy4/8BQ) Rust is statically typed and because of this taking in a function with an unknown number of arguments is not allowed. Fortunately, macros have no such restrictions. This macro takes in a function of the form `name(arg1:type1)(arg2:type2)...(argN:typeN)`. and outputs a function that outputs an appropriately long chain of `impl FnOnce`s that ends with the desired function call. I shaved a few bytes by changing the input form to something more natural with the question. Ungolfed version: ``` macro_rules! c{ //declare a macro named c ( //match on $f:tt //A token tree (should be an ident, but this is codegolf) $( //followed by zero or more sequences of ($n:tt : $a:ty) //a token tree (again, should be ident) colon type in parentheses )* //end repetition )=>{ //replace with $(move|$n:$a|)* //FnOnce closure heads for every matched name:type $f( //call initially matched function $($n),* //with a comma separated list of closure argument names ) //end call } //end rule } //end macro ``` [Answer] # [Cauliflower](https://github.com/broccoli-lang/broccoli), 84 bytes ``` (:= c(\($f$n(@a))(if$n(\($a)(call c(cat(list$f(-$n 1))@a(list$a))))else(call$f@a)))) ``` [Try it online!](https://tio.run/##LYy9CsMwDIRf5QYNEqVD2i1Q8IN0EaoNBuEUx6GP7zpupzu@@zE9PCffPrH2zusDxk@mRIWDinA@3QAqbOo@UtPGnvdGia9UsIgE/YHRF4m@x1mlFCbo/K65NHCNr8Mi5j2oCP46zDkHGy64Cxbchkj/Ag "Cauliflower – Try It Online") [Answer] # Java 8, 19 + 126 = 145 bytes This is a curried (hah) lambda taking a function and an argument count and returning the curried function. ``` import java.util.*; ``` ``` f->p->new C(){List a=new Stack();public Object f(Object r)throws Throwable{a.add(r);return a.size()<p?this:f.f(a.toArray());}} ``` [Try It Online](https://tio.run/##fVJLbxoxED7DrxjlEjsFp0lu3UBFkSpVatUDuUUchl0vGLy2a3sXbdH@djK7LAJFaS/jh@bxPWaLFY6tk2ab7Y6qcNZH2NKfKKPS4i4ZDpWJ0ueYSpiZ@ntp0qisgcNw8Hu1lWmEnJ0ur0tAvw4c4sbbfYCX9sCVlsmwue4y/6C2rfxHoStXWqWQagwBfqHqRoeIkT4vQPMelzgDfL4CO/pv4g9CtpZ@BPPpFNLS@xomx3w8deOpkXuYM374qQJBnLTPRcR0x3jSw3rPw/P3JA4oMMuY54mXsfQGUAT1VzL@7L7GjQpfcpEzFNHOvMeacZ40zXFAug/6ET3XyqoMCuLPFtErsya529fsQ8lbjQbXdinjyggTuHjlcX@qHU@77MH9PdVLL28DGAs3FXqFGQ1eSyO9SsPNCIKFvYQNVhKiBVdqDbb0ne10iWBzQCLYEhF9y2/0nVlzG2FvSdoEVA61LSH8KWklQEXip6iPtnYXILWF0zJKXZ/Gou76UGa/XUTh4mWnWBAheokFOxMSBboXS66yquXGen85VPyictK2PRtCVa@fl/DpdHtYwt3p9rhs05o2zLvNUDIjAN2OCHRO16zTlfePp67tog5RFoL0EI6MitowxuYcutB3IcsfOKf42MUn3lY2w@b4Bg) ## Submission type The submission defines appropriate functional interfaces for the input and output functions. The definitions of the interfaces aren't included in the byte count because they only provide type information and don't contribute any code to the solution. (In fact, both of them are general enough that they could well have been included in the set of functional interfaces in the standard library.) For more details see the TIO. ## Usage Because the submission returns a function (instance of `C`), the output may be invoked directly (with `f`), but subsequent intermediate return values must be cast to an appropriate type before being invoked. Consult the TIO for a usage example. Note that in Java functions (i.e. methods) are not first-class objects. Thus the syntax used in the output bullet of the challenge description is meaningless in Java. Rather than `f(a1, a2, a3)` we have `f.f(a1, a2, a3)`, and rather than `f(a1)(a2)(a3)` we have `f.f(a1).f(a2).f(a3)` (modulo typecasting). ## Limitations When an intermediate result is applied (an argument added), the result is actually a mutated copy of the original result. This violates the spirit of currying, but meets the specific requirement stated in the challenge. The form of input functions is limited by the decision to use functional interfaces, since a fully general functional interface has to use variadics or otherwise pack function parameters, and as a result the implementors of the interface must do so as well rather than listing parameters in the standard fashion. Technically this might disqualify the solution, since it is possible to support fully general non-variadic multi-parameter input functions by invoking them using reflection. My [solution using this strategy](https://tio.run/##dZHNjtMwEIDP8VOM9mQvrSXYG2mLUBACiRXSdm@Ig@M4qVvHjuxJl1Ll2YvjpAsCVrLG4/H8fDOzF0exdJ2y@@pw0W3nPMI@2niP2vDbnBBtUflaSAXF6mEDZ5I9QE2/lnslEYRvGODOu6cAj@MlSqNyMvwZtnUmJnMW1A9Utgok@12g7q0c//jHWVmRbPo2wjbcq9rEMvxe4c5Vi@vfC6GfY8lG@QUUG5LFcx5I5O/60mgJ0ogQ4F5oO7YQUGA0PqPJ3vsTrC/tctMtN1Y9QUHZ@YsOscX1@NyikAfK8jnb3P7zHDz7ewhnwUVVUc9yr7D3FgQP@qeibNW9w50Ob1uu7dEdFBULwdG9916cKGP5MFyyiH1FnLg/uUgSua/WOF0QXWdONGmLZCinS7LkmV3rwiso4RZkHo0DiYdkcxdzsqPTFbRxMnSLXtvm2/dxr@Hfxaa8L20HWlgnTp6QeaPwg4qqV9XkQG8S8U2inJz@r7KRtACvQm8wJk3L4VO7LZuVu@S1PQVULXc98i6io7GU0oJBElMCXtPXjEX5Jsk7NgYOZLj8Ag) (taking a `java.lang.reflect.Method` instead of an instance of a functional interface thanks to @user) is a bit longer, so I stick with this one. ## Ungolfed ``` f -> p -> new C() { List a = new Stack(); public Object f(Object r) throws Throwable { a.add(r); return a.size() < p ? this : f.f(a.toArray()); } } ``` ## Acknowledgments * -211 bytes thanks to ideas from KrystosTheOverlord [Answer] # [Python 2](https://docs.python.org/2/), 78 bytes ``` c=lambda f,*a:f.func_code.co_argcount>len(a)and(lambda x:c(f,*a+(x,)))or f(*a) ``` [Try it online!](https://tio.run/##LctBCsMgEEDRvaeY5YyRQNOd0F4ljKO2hXQMopCe3qbQ3V/8t3/as@gyhtw2fofIkJ1ln@fcVVYpMc1SVq4PKV3bfUuKTKwR//fhBX9iwsMRUamQ0TKNmPJZ7IIT8gagptarAsMEASyIMXt9aYNTE14IF8IrjS8 "Python 2 – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~42~~ 40 bytes ``` my&c={.count>1??{c(.assuming($^a))}!!$_} ``` [Try it online!](https://tio.run/##K0gtyjH7/z@3Ui3ZtlovOb80r8TO0N6@OllDL7G4uDQ3My9dQyUuUVOzVlFRJb4WqFBBLUPBViFZoxoorKCtoBKXpKAFJJNrNa25ihMrFTI0DDU1jDQ1jDWt/wMA "Perl 6 – Try It Online") -2 bytes thanks to [Brad Gilbert b2gills](https://codegolf.stackexchange.com/users/1147/brad-gilbert-b2gills). [Answer] # [Haskell](https://www.haskell.org/), ~~211~~ ~~209~~ ~~189~~ 163 bytes Flags: ``` -XMultiParamTypeClasses -XFlexibleInstances ``` Actual code (119 bytes): ``` class C a b c where c::(a->b)->c instance C()b b where c f=f() instance C a b c=>C(d,a)b(d->c)where c a b=c(\d->a(b,d)) ``` [Try it online!](https://tio.run/##bVBNS8NAEL3nV7yDh12aHNreAglIQCgoCnrwIMjsR5rFTVqyG2r/vHGSpqDoLm@HnXnz5jENhQ/r/ThqTyGgAkFB49TY3kLnuaCsVDIrdeK6EKnTFpWQikkLBXVRC/mjelEoykqYlKQShpvllcy1Qos3zpFQqZFybMl1yHPsHsEy86@AOSTAcYjPsb/vcIPQHE4c2vOtMRDrFGLD2DIkH@Z6G6GHvnfWcLsWM1POul1EVv4N/w64SqyxwTZJLvNYRHBD@vuVEtNdxBZnxAXF0Cne2RhbIax4HSvo8UvXnvZhzF4fBh/dE/XUvpyPtpoWb6f8nbefTnm7W3YZvgE) The input type of the function to be curried is a nested tuple in a cons-like structure. The uncurried version of a function that adds 3 numbers together would look something like this, where it ends in an empty tuple. ``` myAdd :: (Int, (Int, (Int, ()) ) ) -> Int myAdd (a, (b, (c, _))) = a + b + c ``` It works from the bottom up. There's an instance to curry a function of type `() -> r` that just applies the empty tuple to the function. Then there's another instance of `C` that can curry a function of type `(a,b)->c` if there is already an instance of `C` for `b -> c`. Here's an `uncurr` function to accompany the currying function: ``` class Uncurry a b c d where uncurr :: (a->b)->c->d instance Uncurry a r (a,()) r where uncurr f (a,()) = f a instance Uncurry a b c d => Uncurry e (a->b) (e,c) d where uncurr f (e,c) =(uncurr(f e) c) ``` [Try it online!](https://tio.run/##zZNda4MwFIbv8ysOdBcJMxe1d4JCka0Uug/YejcYMUmpzNriB10Z@@3uRONMP9jF2MWUaPS85z2PJ3EtyjedZc0HH8Fiej9bTmc3cFdnVfooCrF5Pux0nImy1CWM@Cc5kt1m@j1NMj3Py0rk0krIRqQ5BAHMH4Cy7ikEtSUAu7p6qopFDldQrrd7vG0OU6WAjj2gPo4JDoYHajNdgayLItUK0yVtlaz1zSvg0fntYoHeYgw@TKxtnQ/GtHvodX0Nin6eczFQQxmHzTdwjuMv@XwLSLqG9ATHV0Qwp3WzrRMYSHBID14NZAgCriHBIQkZvupHMEcmMFWemJj1h9iGFOzXutAgg4AKHiWMR5JHiqR2E0CMSIiatHqrNfNQICcGHOW3ZRjFVHsCkzQ1bszNk/RF8chkK8wmTcezbFt@OKbCFtv1NB108YaqQ2IBHSpOTrJXfSTEqbiY3IN/v9K2IOCXSHZOtLKB0G45ugLNQLLmH/8vf7odmy8) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 5 bytes Good ol' Mathematica built-ins ``` Curry ``` Takes 2 arguments, the function and the number of arguments. [Try it online!](https://tio.run/##TY29CsJAEIT7PMWAnZ7kvzAhlS9gvyxh70dMESPHCfr05xkRMrDbzHwzs4SbmyVMRqJ5ej/Ec/rveF0WklFBpzMjoxsgOEBjD9NnWvzGVbD/xPGXQA7bZxc/3QN9WynVKdRMLVPFVDNj1Q7u9XAmONuhLLdAWlBomMqiYGpWqk3UFmhOVd5m8QM "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), 40 bytes ``` f>n=n<2 ? f : ((x...)->y->f(x...,y))>n-1 ``` [Try it online!](https://tio.run/##LYkxDgIxDAT7vGJLWzjROdchzvAVGh8gFAqESO7zuQhRrDQz@/g871etvbuVpZwyznAcQVRTShytRfMfS2O2ErU7FlCVJhsjGupBpzY2bWEdj9scwuV9e33hpJJl5r@upEyZaYS@Aw "Julia 1.0 – Try It Online") [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~58~~ 57 bytes ``` ∇r←(a f g)x :If a[1]=≢a r←g 1↓a,x :Else r←(a,x)f g :End ∇ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//UUd70aO2CRqJCmkK6ZoVXFaeaQqJ0Yaxto86FyVygaTSFQwftU1O1AHKueYUp3JBlOtUaAI1AIXyUriAZvx/1DdVASihoKGhYaxgDDSs@lFXk7b@o96ttZoKhgqaRpr/AQ "APL (Dyalog Classic) – Try It Online") Calling syntax (with curried function `g`, arguments `x1` through `x3`, and number of arguments `n`): `((n x1 f g) x2) x3` Requires `⎕IO←1` [Answer] # [Julia 0.6](http://julialang.org/), 48 bytes ``` c=(f,n,a=[])->n>1?x->c(f,n-1,[a;x]):x->f(a...,x) ``` [Try it online!](https://tio.run/##TYy9CsJAEIT7e4r1SLGrm4C/iJIIVpY2VmKxuURzcjklKOTt4x1aWAyzM8s397ezshpgMDle2bPk5wulhS@muz4tTOzSKZ9l219oE5orSpZl3NNgxBkULtkQ5CAwgRLGYNQtJIPxyzAn9eysfzmPN5wRLgnXREo19ktyFVl9qJ17MCQSVAYFUnwFCVY00r/BxjIs/uf0QTqrCfWplWjHrm6j75s6HqSGDw "Julia 0.6 – Try It Online") Port of @EricTheOutgolfer's Python answer. [Answer] **Java 8... Using lambda insanity, 152 bytes** Ok so I know that there is already a java 8 answer, but I wanted to use one using almost entirely lambdas without the use of java's Function<> class. Here is the functional interface for the lambda expressions ``` interface K{Object f(int...x);} ``` And here is the actual expression ``` a->a.length==2?(K)c->a[0]+a[1]*c[0]:a.length==3?a[0]+a[1]*a[2]:(K)b->(b.length == 1)?(K)c->a[0]+b[0]*c[0]:a[0]+b[0]*b[1]; ``` Yeah, so I know this looks really crazy, but the latter is mainly just using ternary operators to distinguish different number of arguments to what needs to be returned. Given the submitted function ``` K function = a->a.length==2?(K)c->a[0]+a[1]*c[0]:a.length==3?a[0]+a[1]*a[2]:(K)b->(b.length == 1)?(K)c->a[0]+b[0]*c[0]:a[0]+b[0]*b[1]; ``` `function(a, b, c)` is `function.f(a, b, c)`, `function(a)(b)(c)` is `((K)((K)function.f(a)).f(b)).f(c)` Basically any situation that results in a curried result, the answer must be cast to `(K)` so then it can have a function called on it, otherwise the result is an integer. You can even do the following! `(function(a))(a,b)` which would be `((K)function.f(a)).f(b,c)` etc... This probably took me way too long, and we already have a java 8 answer, but I feel like it is still an interesting way to go about it. [Answer] **[Lispy](https://github.com/andrakis/node-lispy), 169 bytes** ``` (define f(lambda A(begin(define G(lambda(X)(if(>=(length X)C)(proc:apply(head A)X)(lambda Args(G(concat X Args))))))(define C(length(lambda:args(head A))))(G(tail A))))) ``` Implements the [generic abritrary ES5 currying algorithm](https://rosettacode.org/wiki/Currying#Generic_currying) on Rosetta Code. Ungolfed and test: ``` (begin ;; f is a lambda that captures all arguments (define f (lambda Arguments (begin ;; function extraCurry(f) { (define F (head Arguments)) (define A (tail Arguments)) (define _curry (lambda (XS) ;; function _curry(xs) { (if (>= (length XS) intArgs) ;; xs.length >= intArgs ? (proc:apply F XS) ;; f.apply(null, xs) (lambda Args ;; : function() { (_curry (concat XS Args))) ;; return _curry(xs.concat([].slice.apply(arguments))) ) )) (define intArgs (length (lambda:args F))) ;; intArgs = f.length (_curry A) ;; return _curry([].slice.call(arguments, 1)) ))) (define product3 (lambda (a b c) (* a b c))) ;; [14, 28, 42, 56, 70, 84, 98, 112, 126, 140] (print (map [1 2 3 4 5 6 7 8 9 10] (((f product3) 7) 2)))) ``` Try online link coming soon. [Answer] # Dotty, ~~345~~ ... ~~221~~ 186 bytes ``` def>[F,T,X](f:F)(using? :F TupledFunction T,e:T=>X)=e(?tupled f) given[A]as((EmptyTuple=>A)=>A)=_(Tuple()) given[A<:Tuple,B,C,D](using t:(A=>B)=>C)as((D*:A=>B)=>D=>C)=f=>h=>t(c=>f(h*:c)) ``` [Try it in Scastie](https://scastie.scala-lang.org/YZMS7304S8e11GAlA9N0RQ) **This will not work in Scala 3.0 as `TupledFunction` will be [removed](https://github.com/lampepfl/dotty/commit/f4e1ca4f565c74fbe1aa56ea88ce6f59409ccdf0).** However, it may be added back later. This one doesn't do any unsafe casting or other trickery. `>` is the method to call. The type parameters `F`, `T`, and `X` represent the type of the input function, the type of the input function if it took a single tuple instead of multiple arguments, and the type of the resulting curried function, respectively. The first parameter, `f`, is the function to be curried. There are also two implicit parameters, `?` and `e`. `?` is a `TupledFunction` object that can convert between `F` and `T`, i.e., tuple and untuple a function. It is provided in the standard library automatically, and makes it easier for `e` to do its work. `e` operates on the tupled form of `f`. There's a base implicit function that takes an a function `EmptyTuple=>A` and returns an `A` by just passing an empty tuple to that function. Another `given` builds on top of that by deconstructing `f` into `D *: A => B` (`D` is the type of the first parameter of `f`, `A` is the type of the rest of the parameters as a tuple, and `B` is the type of `f`'s result). It uses another implicit function of type `(A => B) => C`, where `C` is the curried version of `A => B`. This second case returns a function taking a `D` and then applying `t` to a new function where the `D` from before is cons-ed to an `A` before applying `f` to it. ## Dotty, 144 bytes ``` def a[T](x:Any)=x.asInstanceOf[T] def c[T,R](f:T=>R,n:Int):Any=>Any=h=>a(n match{case 1=>f(a(Tuple1(h)))case _=>c(t=>f(a(h*:a[Tuple](t))),n-1)}) ``` [Try it in Scastie](https://scastie.scala-lang.org/3QJTPxrITk2tA0A2xns7Jw) Requires function to be tupled beforehand. [Answer] # [Factor](https://factorcode.org/), 6 bytes ``` ncurry ``` [Try it online!](https://tio.run/##BcExDkBAEAXQ3il@TSJBxwFEoxGVKCabwcYaMkbB5dd7Czk7NY5D17c1VhZWCv4j86fc2FmFAw6yDZey2XupF0OTJAVKVJiQIsOMMop7VN@Y33CBSeMP "Factor – Try It Online") Builtin. A non-trivial implementation might be: ``` [ [ curry ] times ] ``` Currying is a pretty uncomplicated affair in a concatenative language. :) [Answer] # [Ruby](https://www.ruby-lang.org/), 12 bytes Ruby has a built-in method `curry` which can be called on a lambda that gives the desired behavior. The below code returns a lambda that calls `curry` on its argument. ``` proc &:curry ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhZrCorykxXUrJJLi4oqIUI3ddMVbBV07RJ1knSSqxUStZO0khVqubjS44HCbtHpsVxcBQrp8dGGOkax0caxEE0LFkBoAA) ]
[Question] [ An Integer is *prime* if and only if it is positive and has exactly 2 distinct divisors: 1 and itself. A twin prime pair is made of two elements: `p` and `p±2`, that are both prime. You will be given a positive integer as input. Your task is to return a truthy / falsy depending on whether the given integer belongs to a twin pair, following the standard [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") rules (the values need to be consistent). ## Test Cases * Truthy (Twin Primes): `3, 5, 7, 11, 13, 17, 19, 29, 31, 41, 43` * Falsy (not Twin Primes): `2, 15, 20, 23, 37, 47, 97, 120, 566` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~9~~ 8 bytes ``` ṗ∧4√;?+ṗ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@HO6Y86lps86phlba8N5Pz/b2T5HwA "Brachylog – Try It Online") ### Explanation ``` ṗ Input is prime ∧ And 4√ A number whose square is 4 (i.e. -2 or 2) ;?+ That number + the Input… ṗ …is prime ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes ``` %6+_2_ÆP⁺ ``` [Try it online!](https://tio.run/##y0rNyan8/1/VTDveKP5wW8Cjxl3/DQ0MD7cfnpDmrfBwx/ZHDXMUQsoz8xQKijJzU4sVSgsUSvIVgEr0/gMA "Jelly – Try It Online") ### Background With the exception of **(3, 5)**, all twin prime pairs are of the form **(6k - 1, 6k + 1)**. Since **(6k - 1) + (6k - 1) % 6 - 3 = 6k - 1 + 5 - 3 = 6k + 1** and **(6k + 1) + (6k + 1) % 6 - 3 = 6k + 1 + 1 - 3 = 6k - 1**, given an input **n > 3**, it is sufficient to check whether **n** and **n + n % 6 - 3** are both prime. This formula *happens to* work for **n = 3** as well, as **3 + 3 % 6 - 3 = 3** is prime and **3** is a twin prime. ### How it works ``` %6+_2_ÆP⁺ Main link. Argument: n %6 Compute n%6. + Add n to the result. _2 Subtract 2. _ÆP Subtract 1 if n is prime, 0 if not. If n is not a prime, since (n + n%6 - 2) is always even, this can only yield a prime if (n + n%6 - 2 = 2), which happens only when n = 2. ⁺ Call ÆP again, testing the result for primality. ``` [Answer] # [Python 3](https://docs.python.org/3/), 53 bytes ``` lambda n:sum((n+n%6-3)*n%k<1for k in range(2,4*n))==2 ``` [Try it online!](https://tio.run/##RckxDkAwGAbQmVP8i6SlhtIYRG9iqVAafKQYnL6YbC95@31OG8pgSVMbFrN2vSHUx7UyhgxJlZc8RTI30m6eZnIgbzAOrBAqBedaF@Eb/CMFVUrxOo6cJcvwKdq9w/k6PA "Python 3 – Try It Online") ### Background All integers take one of the following forms, with integer **k**: **6k - 3**, **6k - 2**, **6k - 1**, **6k**, **6k + 1**, **6k + 2**. Since **6k - 2**, **6k**, and **6k + 2** are all even, and since **6k - 3** is divisible by **3**, all primes except **2** and **3** must be of the form **6k - 1** or **6k + 1**. Since the difference of a twin prime pair is **2**, with the exception of **(3, 5)**, all twin prime pairs are of the form **(6k - 1, 6k + 1)**. Let **n** be of the form **6k ± 1**. * If **n = 6k -1**, then **n + n%6 - 3 = 6k - 1 + (6k - 1)%6 - 3 = 6k - 1 + 5 - 3 = 6k + 1**. * If **n = 6k + 1**, then **n + n%6 - 3 = 6k + 1 + (6k + 1)%6 - 3 = 6k + 1 + 1 - 3 = 6k - 1**. Thus, *if* **n** is part of a twin prime pair and **n ≠ 3**, it's twin will be **n + n%6 - 3**. ### How it works Python doesn't have a built-in primality test. While there are short-ish ways to test a single number for primality, doing so for two number would be lengthy. We're going to work with divisors instead. ``` sum((n+n%6-3)*n%k<1for k in range(2,4*n)) ``` counts how many integers **k** in the interval **[2, 4n)** divide **(n + n%6 - 3)n** evenly, i.e., it counts the number of divisors of **(n + n%6 - 3)n** in the interval **[2, 4n)**. We claim that this count is **2** if and only if **n** is part of a twin prime pair. * If **n = 3** (a twin prime), **(n + n%6 - 3)n = 3(3 + 3 - 3) = 9** has two divisors (**3** and **9**) in **[2, 12)**. * If **n > 3** is a twin prime, as seen before, **m := n + n%6 - 3** is its twin. In this case, **mn** has exactly four divisors: **1, m, n, mn**. Since **n > 3**, we have **m > 4**, so **4n < mn** and exactly two divisors (**m** and **n**) fall into the interval **[2, 4n)**. * If **n = 1**, then **(n + n%6 - 3)n = 1 + 1 - 3 = -1** has no divisors in **[2, 4)**. * If **n = 2**, then **(n + n%6 - 3)n = 2(2 + 2 - 3) = 2** has one divisor (itself) in **[2, 8)**. * If **n = 4**, then **(n + n%6 - 3)n = 4(4 + 4 - 3) = 20** has four divisors (**2**, **4**, **5**, and **10**) in **[2, 16)**. * If **n > 4** is even, **2**, **n/2**, and **n** all divide **n** and, therefore, **(n + n%6 - 3)n**. We have **n/2 > 2** since **n > 4**, so there are at least three divisors in **[2, 4n)**. * If **n = 9**, then **(n + n%6 - 3)n = 9(9 + 3 - 3) = 81** has three divisors (**3**, **9**, and **21**) in **[2, 36)**. * If **n > 9** is a multiple of **3**, then **3**, **n/3**, and **n** all divide **n** and, therefore, **(n + n%6 - 3)n**. We have **n/3 > 3** since **n > 9**, so there are at least three divisors in **[2, 4n)**. * Finally, if **n = 6k ± 1 > 4** is not a twin prime, either **n** or **m := n + n%6 - 3** must be composite and, therefore, admit a proper divisor **d > 1**. Since either **n = m + 2** or **m = n + 2** and **n, m > 4**, the integers **d**, **m**, and **n** are *distinct* divisors of **mn**. Furthermore, **m < n + 3 < 4n** since **n > 1**, so **mn** has at least three divisors in **[2, 4n)**. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 9 bytes Saved 1 byte thanks to *Datboi* ``` ÌIÍ‚pZIp* ``` [Try it online!](https://tio.run/##MzBNTDJM/f//cI/n4d5HDbMKojwLtP7/N7IEAA "05AB1E – Try It Online") or as a [Test Suite](https://tio.run/##MzBNTDJM/V9TVvn/cE/l4d5HDbMKoioLtP5XKh3eb6VweL@STsx/Yy5TLnMuQ0MuQ2MuQyDDksvIksvYkMsEiIy5jLgMTbmMDLiMjLmMzblMzLksgUqAfFMzMwA) **Explanation** ``` Ì # push input+2 IÍ # push input-2 ‚ # pair p # isPrime Z # max Ip # push isPrime(input) * # multiply ``` [Answer] # [Perl 6](http://perl6.org/), 24 bytes ``` ?(*+(0&(-2|2))).is-prime ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPvfXkNLW8NATUPXqMZIU1NTL7NYt6AoMzf1v7VCcWKlQnpRagFQoY5CnKGBgfV/AA "Perl 6 – Try It Online") `*` is the argument to this anonymous function. `0 & (-2 | 2)` is the junction consisting of the numbers `0` AND either `-2` OR `2`. Adding `*` to this junction produces the junction of the number `*` AND either of the numbers `* - 2` OR `* + 2`. Calling the `is-prime` method on this junction returns a truthy value if `*` is prime AND either `* - 2` OR `* + 2` are prime. Finally, the `?` collapses the truthy junction to a boolean value, satisfying the consistent-return-values condition. [Answer] # PHP, 52 bytes ``` <?=($p=gmp_prob_prime)($n=$argn)&&$p($n+2)|$p($n-2); ``` without GMP, **84 bytes** (using [my prime function from stack overflow](https://stackoverflow.com/a/39743570)) ``` <?=p($n=$argn)&&p(2+$n)|p($n-2);function p($n){for($i=$n;--$i&&$n%$i;);return$i==1;} ``` Run as pipe with `-nF`. Empty output for falsy, `1` for truthy. [Dennis´ great solution](https://codegolf.stackexchange.com/a/135300) ported to PHP, **56 bytes** ``` while($i++<4*$n=$argn)($n+$n%6-3)*$n%$i?:$s++;echo$s==3; ``` Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/d1f6d9fb6f701b41661aa2b3d66d617539f51c93). [Answer] # Mathematica, 33 bytes ``` (P=PrimeQ;P@#&&(P[#+2]||P[#-2]))& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvtfI8A2oCgzNzXQOsBBWU1NIyBaWdsotqYGSOsaxWpqqv0HSueV6Duk6TtUG@somOoomOsoGBoCMZBnCGJb6igYAbExUMwEhI1ruZD0GAFVADUZGQAxUIcxUIcJEFuCdIIETc3Mav8DAA "Mathics – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 11 bytes ``` HOht_v+ZpAa ``` Output is `0` or `1`. [Try it online!](https://tio.run/##y00syfn/38M/oyS@TDuqwDHx/39DYwA "MATL – Try It Online") ### Explanation ``` H % Push 2 O % Push 0 h % Concatenate horizontally: gives [2 0] t_ % Push a negated copy: [-2 0] v % Concatenate vertically: [2 0; -2 0] + % Add to implicit input Zp % Isprime A % All: true for columns that only contain nonzeros a % Any: true if there is at least a nonzero. Implicit display ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~45~~ 44 bytes ``` .* $* 11(1+) $1¶$&¶11$& m`^(11+)\1+$ 1<`1¶1 ``` Returns 1 if the input is a twin prime, 0 otherwise [Try it online!](https://tio.run/##DYsxDsIwFEP3d45QhVZCdX7TKBI7l6hQGBgYYECcrQfoxcKXPNjP9vf5e30e/RRvrV9GwogUNZ0JOvYwHLsUBt7tHuV00xRA1@alejcyxQ/IkJtKqphYXEZCmTSTDCssheoTz3ld/w "Retina – Try It Online") ### Explanation ``` .* $* ``` Convert to Unary ``` 11(1+) $1¶$&¶11$& ``` Put n-2, n, and n+2 on their own lines ``` m`^(11+)\1+$ ``` (Trailing newline) Remove all composites greater than 1 ``` 1<`1¶1 ``` Check if there are two consecutive primes (or 1,3 because 3 is a twin prime) [Answer] # [Pyth](http://pyth.readthedocs.io), ~~14 12~~ 11 bytes ``` &P_QP-3+%Q6 ``` [Test Suite.](http://pyth.herokuapp.com/?code=%26P_QP-3%2B%25Q6&test_suite=1&test_suite_input=5%0A7%0A11%0A15%0A20%0A37&debug=0) --- Saved 3 bytes using the formula in @Dennis' answer. Saved 1 byte thanks to @Dennis. --- # [Pyth](http://pyth.readthedocs.io), 14 bytes \**Initial Solution* ``` &|P_ttQP_hhQP_ ``` [Test Suite.](http://pyth.herokuapp.com/?code=%26%7CP_ttQP_hhQP_&input=9&test_suite=1&test_suite_input=3%0A%0A5%0A%0A7%0A%0A11%0A%0A13+%0A%0A17%0A%0A19%0A%0A2%0A%0A15%0A%0A20%0A%0A47%0A%0A9&debug=0&input_size=2) [Answer] # [Factor](https://factorcode.org/) + `math.primes`, 42 bytes ``` [| x | 0 2 -2 [ x + prime? ] tri@ or and ] ``` [Try it online!](https://tio.run/##HYyxCsIwFEV3v@LsYpFs6qCbuLiIU@kQasRimoSXB7bQf4@h2z3nwH3bXqOU5@N2vx75OgnOk8SpzkmGoIxWP/jYW5/X3VQ9usyptAsTC3sMO0NbYcsaz3SoDBeiYMOLrpjDJv9sor54mvIH "Factor – Try It Online") Originally inspired by trying to golf [Michael Chatiskatzi's answer](https://codegolf.stackexchange.com/a/220617/62393), I've then modified it enough that I thought worth posting it as a separate answer. ### Explanation This is a lambda function using the local variable `x` to refer to the element at the top of the stack when the function is called (its argument). `[ x + prime? ]` defines a function that adds `x` to a number and checks if the result is prime. This is then applied using `tri@` to the three values `0`,`2`,`-2`, resulting in three booleans determining if `x`,`x+2` and `x-2` are primes. We combine the last two with `or`, and the result of this with the first with `and`. The total function is then equivalent to `isprime(x+0) and (isprime(x+2) or isprime(x-2))` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes Port of [Dennis' Jelly answer](https://codegolf.stackexchange.com/a/135293/47066) ``` 6%+ÍIp-p ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fTFX7cK9ngW7B//9GlgA "05AB1E – Try It Online") or as a [Test Suite](https://tio.run/##DYoxCoAwEAT7fYUErFTI3eUS4ltsFOxTCQG/4JtS5GFnYIoZGK/nRbe9T60W56V/tWzFquttn3pz62ECRQIRSEBDMjhDCGEgYJCCPVggCSEhj2W0xvgD) **Explanation** ``` 6% # n mod 6 + # add n Í # subtract 2 Ip- # subtract isPrime(n) p # isPrime ``` [Answer] # JavaScript, 91 bytes, 81 bytes thanks to [Jared Smith](https://codegolf.stackexchange.com/users/59429/jared-smith) ``` p=n=>{for(i=2;i<n;)if(n%i++==0)return !!0;return n>1},t=n=>p(n)&&(p(n+2)||p(n-2)) ``` **Explanation** `p` tells wether the given number `n` is prime or not, and `t` tests given number `n` and `n±2`. **Example** ``` var twinPrimes = [3, 5, 7, 11, 13, 17, 19, 29, 31, 41, 43]; var notTwinPrimes = [2, 15, 20, 23, 37, 47, 97, 120, 566]; p=n=>{for(i=2;i<n;)if(n%i++==0)return !!0;return n>1},t=n=>p(n)&&(p(n+2)||p(n-2)) for (var n of twinPrimes) { console.log(n, ': ', t(n)); } for (var n of notTwinPrimes) { console.log(n, ': ', t(n)); } ``` [Answer] # Excel VBA, ~~102~~ 100 Bytes No primality built-ins for VBA `:(` ### Code Anonymous VBE immediate window function that takes input from cell `[A1]` and outputs either `1` (truthy) or `0` (falsy) to the VBE Immediate window ``` a=[A1]:?p(a)*(p(a-2)Or p(a+2)) ``` ### Helper Function ``` Function p(n) p=n>2 For i=2To n-1 p=IIf(n Mod i,p,0) Next End Function ``` --- ## Alternatively, 122 Bytes ### Code Recursive primality checking function based solution ``` a=[A1]:?-1=Not(p(a,a-1)Or(p(a-2,a-3)*p(a+2,a+1))) ``` ### Helper Function ``` Function p(n,m) If m>1Then p=p(n,m-1)+(n Mod m=0)Else p=n<=0 End Function ``` [Answer] # J, 23 bytes ``` 1&p:*.0<+/@(1 p:_2 2+]) ``` [Try it online!](https://tio.run/##RYqxCsJAEAX7@4ohhcQE4u1uLscFBX8kWIhBLGLafP25nfCKecx8al1vA3La526I1/5yb4V9fijaL@dwuDMSGRHEEIeCFkwYfRY2LxRJaEQNy4yZ4pn/NE3h9Xx/WZvI8cet1h8 "J – Try It Online") ### how? ``` 1&p: is the arg a prime? *. boolean and one of +2 or -2 also a prime (1 p:_2 2+]) length 2 list of booleans indicating if -2 and +2 are primes @ pipe the result into... 0<+/ is the sum of the elements greater than 0 ie, at least one true ``` [Answer] # Ruby, 38 + 6 = 44 bytes Requires options `-rprime`. ``` ->n{n.prime?&[n-2,n+2].any?(&:prime?)} ``` [Try it online!](https://tio.run/##KypNqvyfpmD7X9curzpPr6AoMzfVXi06T9dIJ0/bKFYvMa/SXkPNCiKuWfu/KLWwNLMoVUG9oECdq6BAQcNST8/IWFMvN7FAoVqhpqJGIbpCRyEtuiI2VqH2/7/8gpLM/Lzi/7pFYBMA "Ruby – Try It Online") [Answer] # JavaScript(ES6), 54 bytes ``` a=x=>f(x)&(f(x+2)|f(x-2));f=(n,x=n)=>n%--x?f(n,x):x==1 ``` ``` a=x=>f(x)&(f(x+2)|f(x-2));f=(n,x=n)=>n%--x?f(n,x):x==1 console.log("True") console.log("---------------------") console.log(a(3)) console.log(a(5)) console.log(a(7)) console.log(a(11)) console.log(a(13)) console.log(a(17)) console.log(a(19)) console.log(a(29)) console.log(a(31)) console.log(a(41)) console.log(a(43)) console.log("False") console.log("---------------------") console.log(a(2)) console.log(a(15)) console.log(a(20)) console.log(a(23)) console.log(a(37)) console.log(a(47)) console.log(a(97)) console.log(a(120)) console.log(a(566)) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 13 bytes ``` j ©[U+2U-2]dj ``` Returns `true` and `false` for whether or not the number is part of a prime twin pair. [Try it online!](https://codepen.io/justinm53/full/NvKjZr?code=aiCpW1UrMlUtMl1kag==&inputs=Mg==,Mw==,MTU=,NQ==,MjA=,Nw==,MjM=,MTE=,Mzc=,MTM=) ## Explanation Implicit: `U` = input integer ``` j © ``` Check if the input is prime (`j`), AND (`©`) ... ``` [U+2U-2]dj ``` Using the array `[U+2, U-2]`, check if any items are true (`d`) according to the primality function (`j`). Implicit output of the boolean result of `is input prime AND is any ±2 neighbor prime`. [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` Vṗ(§e+-2 ``` [Try it online!](https://tio.run/##yygtzv7/P@zhzukah5anausa/f//39AQAA "Husk – Try It Online") [Answer] # [Factor](https://factorcode.org/) + `math.primes`, 46 bytes ``` [ dup 2 [ + ] 2keep - [ prime? ] tri@ or and ] ``` **Demonstartion** of every state of the stack for the example number 43: ``` 43 dup 2 [ + ] 2keep - [ prime? ] tri@ or and | | | | + | 2 | | prime? | | | | | | | 2 | 2 | 43 | 41 | 41 | t | | | | | 43 | 43 | 43 | 45 | 45 | 45 | f | t | | | 43 | 43 | 43 | 43 | 43 | 43 | 43 | t | t | t | ``` [Try it online!](https://tio.run/##HYqxCoNAEAV7v@L1ooWxMkXsxCaNWInFohsUz3NZV0K@/nLYDMwwH5rs0NB37bupsLF6dtjJlhu56LrzCVE2@0XxhmcYMF@CAgNSjCg2ZkEW7Z5fMZmuNQ4F@RljKB/J@SXBRM4hD38 "Factor – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 35 bytes ``` {∨/2∧/∊∘{(⊢~∘.×⍨)1↓⍳⍵}¨⍨|2(-,⊢,+)⍵} ∨/ ⍝ reduce by bitwise OR 2∧/ ⍝ logical AND bit array, two at a time (overlapping) ∊∘{...}¨⍨ ⍝ for each, check if in list of primes (⊢~∘.×⍨)1↓⍳⍵ ⍝ find element of range that is not in matrix of composite numbers (list of primes) | ⍝ absolute value of array 2(-,⊢,+)⍵ ⍝ create array (2-n, n, 2+n) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqRx0r9I0edSzXf9TR9ahjRrXGo65FdUCG3uHpj3pXaBo@apv8qHfzo96ttYdWAAVqjDR0dYBKdLQ1QWJAQxSMudIUTIHYHIgNDUEESMQQzLUEEkYgwhgkYQImQLJGIEmQJiMDEAESMgZpMAERlmCtYBlTMzMA "APL (Dyalog Unicode) – Try It Online") [Answer] # Regex (ECMAScript or better), ~~48~~ ~~35~~ ~~29~~ 28 bytes *-20 bytes thanks to [H.PWiz](https://chat.stackexchange.com/transcript/message/57424541#57424541)* ``` ^(xx)?(?!(xx(x*))\3?\2+$)xxx ``` [Try it online!](https://tio.run/##TY@9bsIwFEZfBaIK7iVNSGjVAddk6sDC0I6llaxwcdwax7INuPw8exqGSp2@4XzS0fkSB@Frp2zIvFUbcrvWfNNP57ih4@CV5Eu0ACe@mE66T4gRK6iG/UKcIK4fqvUsvcMYYzeZnjAP7VtwykjA3GtVEzzdZ4@IzPOCHRulCUBzR2KjlSFAHHKz1xrPkuvcW60CjLMxMrUFMFzmmowMDS5ml4vyK7ECxa1wnpYmgHwvPhD/AP0HZlFW5fyGMTSuPSZLcxBabQZOGEnzQZJqtm0dMPXMiak0xV6YxCR3ZEkEUJjvRKgbcIhnPxrZPinAraJkdh98cP2FXa9dkZVFUfwC "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript [Try it online!](https://tio.run/##RU7BasMwDP0VrZjGWhJid/Qyx00K3XWn3ZbOdKUBg9dmdgYexvv1zM0Ku0h6T096bzhZs54@voFYAcFcjgcDpBIJynq3fdluIvQXS4mTTNQbgQF0nxCGwerzCIvuvBARWiPdYPRIszIr3Ne7G9OJKkpecDx9XkXNP8sSj49Eobj@csnxYFtTrzC05pXvZapsL26@@gaJruW8TlOeY9A9UJr5DDwkESLIH6iIrTAQt1zO4eZsKTgXf1mJFjFGpZ6ed0pNb9R7bGhzlzr194jdQ9OtcoLe@2liJWeM/QI "Perl 5 – Try It Online") - Perl Takes its input in unary, as a string of `x` characters whose length represents the number. Commented and indented: ``` ^ # tail = N = input number # Assert either that N-2 and N are prime, or that N and N+2 are prime. (xx)? # tail -= 2, optionally # Assert that neither tail nor tail+2 are composite. For testing that they are both prime, # this has false positives for tail=0, tail=1, and tail=2. (?! # Assert that the following can't match: (xx(x*)) # \2 = any number >= 2; \3 = \2 - 2 \3? # tail -= \3, optionally; if this is done, we're asserting that tail+2 is # composite (divisible by \2 with a quotient >= 3), otherwise # we're asserting tail is composite (quotient >= 2). \2+$ # Assert that tail is positive and divisible by \2 ) xxx # Assert that tail >= 3, preventing the false positives. # The "quotient >= 3" requirement above is why tail=2 can be one of them, # as it prevents 2+2 from being seen as composite. ``` ## 29 bytes ``` ^ # tail = N = input number # Assert either that N-2 and N are prime, or that N and N+2 are prime. (xx)? # tail -= 2, optionally # Assert that neither tail nor tail+2 are composite. For testing that they are both prime, # this has false positives for tail=0 and tail=1. (?! # Assert that the following can't match: (xx)? # tail -= 2, optionally; if this is done, we're asserting that tail is # composite, otherwise we're asserting tail+2 is composite. (x*) # \3 = S-2, where S is a potential divisor to test against M = tail+2; # tail -= \3 (\3xx)+$ # assert that tail is positive and divisible by \3+2, which is # equivalent to asserting M is divisible by S with a quotient >= 2 ) xx # Assert that tail >= 2, preventing the false positives. ``` ## 48 bytes This misses the fact that we can switch between testing N-2 and N or testing N and N+2. Instead, this regex switches between testing N and N-2 or testing N and N+2, which results in tests not having enough in common to be collapsed together. ``` ^ # tail = N = input number ( # Assert that neither N nor N-2 are composite. But we want N and N-2 to be prime, so # this gives false positives for 0, 1, and 2. (?! # Assert that the following can't match: (xx)? # tail -= 2, optionally (xx+) # \3 = any number >= 2 \3+$ # Assert that tail is positive and divisible by \3 ) | # or... # Assert that neither N nor N+2 are composite. But we want N and N+2 to be prime, so # this gives false positives for 0 and 1. (?! # Assert that the following can't match: (xx(x*)) # \4 = any number >= 2; \5 = \4 - 2 \4*(xx)?\5$ # Assert that either tail or tail+2 is positive and divisible by \4 ) ) xxx # Block the false positives on every number less than 3 ``` ## 51 bytes (not golfed at all) ``` ^ # tail = N = input number (?!(xx+)\1+$) # Assert that N is not composite. But we want N to be prime, # so this gives false positives for 0 and 1. ( (?!xx(xx+)\3+$) # Assert that N-2 is not composite. But we want N-2 to be prime, so this # gives false positives for 0, 1, and 2. | # or... (?!(x*)(xx\4)+$) # Assert that N+2 is not composite. Has no false positives for primality. ) xxx # Block the false positives on every number less than 3 ``` # Regex (ECMAScript), 67 bytes Just for kicks, here is a port of [Dennis's Jelly algorithm](https://codegolf.stackexchange.com/a/135293/47066): ``` ^(?!(xx+)\1+$)(?=(x{6})*(x*))xxx(?!(xx+)(?=\4*(x*)).*(?=\5\3$)\4+$) ``` [Try it online!](https://tio.run/##Tc9Nb8IwDAbgvwIVArtdS7sxDmSB0w5cOGzHdZMiMG22kEZJgIyP394VTZN2tJ/Xst5PcRBubaXxqTNyQ3bX6C/6bi3XdOy9UPUcDMCJz8dx@wGLPoSQYFkkA4QFh3CeXjGGECOGEP64k3Lyu83i2/BYPgywnHRHbTw@YeabV2@lrgAzp@SaYHqXThCZ4zk71lIRgOKWxEZJTYDY53qvFJ4rrjJnlPQwSkfI5BZA8ypTpCtf4/z@cpFuJVYguRHW0VJ7qN7yd8Q/oP@g58WimN0YfW2bY7TUB6HkpmeFrmjWixLFto0FJp84MZkk2D2MQpRZMiQ8SMx2wq9rsIhnNxyarpKHW4uCmb133nYRdr22eVrkef4D "JavaScript (SpiderMonkey) – Try It Online") ``` ^ # tail = N = input number (?!(xx+)\1+$) # Assert N is not composite (?=(x{6})*(x*)) # \3 = N % 6 xxx # assert N>=3; tail -= 3 # Assert tail + \3 is not composite (?! # Assert the following can't match: (xx+) # \4 cycles through all values such that 2 <= \4 <= tail, # and is tested as a possible divisor of tail + \3 (?=\4*(x*)) # \5 = tail % \4 .*(?=\5\3$) # tail = \5 + \3 \4+$ # Assert that tail is positive and divisible by \4 ) ``` ### \$\large\textit{Anonymous functions}\$ # JavaScript (ES6), 50 bytes ``` n=>/^(..)?(?!(..(.*))\3?\2+$).../.test(Array(n+1)) ``` [Try it online!](https://tio.run/##Tc1BbsIwEIXhqwCqYKZRjEN3uE7UJRsuUFrJahxnWndi2QaEgLOn6aJSV2/xSe//NCeTPiKFXKZArY3fA3/Zy9jpkXW9fgchsIFmPi2IR8TDU3PYFA8ohFiLbFOGlxjNBbioEMekpTr35C2A19Ga1hNbQJxrPnqPV6e9SMFThlW5QkUdAGsnvGWXe6w3txulvdkD6WBisjvO4F7lG@If2P/AddVU21/G3MfhvNjxyXhqZ9Gws9vZovCqGyIoetZWUVHgFOyAEK9puQyRphdUSVcqHHPKcRJ1v4@yrKSUPw "JavaScript (SpiderMonkey) – Try It Online") # Ruby, 41 bytes ``` ->n{?x*n=~/^(xx)?(?!(xx(x*))\3?\2+$)xxx/} ``` [Try it online!](https://tio.run/##PY7NDoIwEITvPsViTGg1LQWPWHkQQBMjP02axUCNNUZfHReiHNruTOebbH@/PMdaj@KIr8xvUX@iE/OeZywL6GV@y3mxz4pkt@He@@g9Gq1SeLTGVmB1U7lhBWBqsLmIS63XBa5T@rC5klIkZQoVXilBjhxu1jgWipD/EGkrbFzL@CEhJieesAWpux4QDMJkStedDYsVl3IKLpJyc1edI4E0mGDa73Z3w9xDno5J9wYd4L96uumMSsRKqS8 "Ruby – Try It Online") [Try it online!](https://tio.run/##DcXBCkVAFAbgvac4U7fMwR3FyoJ5ENyiKAs6ptSv4b768G0@d4xnmKkO32bzFslW//OfBthqq941EuautF2RfhhAfgc37cfiJopF4kiEdGVMUbJZByFPFy5qkZFSc4u@pzs8 "Ruby – Try It Online") - test cases only ### \$\large\textit{Full programs}\$ # [Retina](https://github.com/m-ender/retina), 34 bytes ``` .* $* ^(11)?(?!(11(1*))\3?\2+$)111 ``` [Try it online!](https://tio.run/##DYoxCgIxFAX7uYWwQpIF8f2/2ZAqpZdYRAsLGwvx/vHDg5mB93393p/nPKfbY14KS@GepDzSOAWTSs6Hj8PWJUua06k0JOQopGMdF1vMMVSxK@Z4Y2v0uETXff8D "Retina 0.8.2 – Try It Online") - test cases only [Answer] # PHP, 85 bytes **24 bytes thanks to Mayube** ``` e($n){return f($n)&&((f($n-2)||f($n+2))) f($n){for($i=$n;--$i&&$n%$i;)return $i==1;} ``` [Answer] # [Python 2](https://docs.python.org/2/), 75 bytes ``` lambda x:p(x)*(p(x-2)|p(x+2)) p=lambda z:(z>1)*all(z%i for i in range(2,z)) ``` [Try it online!](https://tio.run/##XYmxCoMwFEV3v@IthXetBc0YiF/iErFpH8QkBAcN/nvq4NTlHDgnHds3BlWdmaq367xY2nXiHS1ffCmcl54KaJK5f9FcxgGt9Z7LQ8jFTEISKNvwebPqClD/4tD30A2JI8cCnbKEjaT@AA "Python 2 – Try It Online") [Answer] # Excel, 84 bytes Current Excel 365: ``` =LET(x,SEQUENCE(A1+2),(SUM((MOD(A1,x)=0)*1)=2)*(SUM((MOD(A1+MOD(A1,6)-3,x)=0)*1)=2)) ``` Future Excel (73 bytes): ``` =LET(p,LAMBDA(a,SUM((MOD(a,SEQUENCE(a))=0)*1)=2),p(A1)*p(A1+MOD(A1,6)-3)) ``` ]
[Question] [ ## Background Information: What is a [Fenwick Tree](https://en.wikipedia.org/wiki/Fenwick_tree)? With a normal array, it costs \$O(1)\$ to access and modify an element, but \$O(n)\$ to sum \$n\$ elements. Working with a prefix sum array (an array where the \$i\$th value represents the sum of the first \$i\$ values in the underlying data), access and summation are \$O(1)\$, but modification is \$O(n)\$. Thus, if you want to do a large amount of both, you will need a different data structure. A Fenwick Tree is one such data structure that can solve this problem. The following diagram will help with the understanding: [![image representation of a Fenwick tree in a flat array](https://i.stack.imgur.com/lHqao.png)](https://i.stack.imgur.com/lHqao.png) Don't worry too much about the "tree" part of it. This looks like a flat array but it does represent a tree (and probably not in the sense the image makes it look like) - if you're curious about the tree part, I would recommend checking out the Wikipedia page, but it's a bit much for me to explain here. This image shows what each value in the FT represents. For example, the 12th element of the FT is the sum of the 9th to 12th elements. The 8th element of the FT is the sum of the first 8. The 16th is the sum of all 16 values. Note that the \$N\$th value represents the sum of the \$k+1\$th value to the \$N\$th value, where \$k\$ is the number you get when you flip the least significant bit of \$N\$ (the rightmost bit that is turned on). For example, 12 is `1100` in binary, so removing its LSB gives `1000`, which is 8. Now, the above logic lets us get both our summation (and by extension, access) and modification operations to \$O(\log N)\$, which is individually worse than both normal and prefix-sum arrays, but combined, is a more efficient data structure if you need to do both operations a lot. **To sum the first \$N\$ elements**, we start with `FT[N]`. This gives us the sum from \$k+1\$ to \$N\$. Thus, the sum of the first \$N\$ elements is `FT[N]` plus the sum of the first \$k\$ elements. We get \$k\$ by subtracting the least significant bit from \$N\$. Eventually, we reach a number like 8, and subtracting the LSB gives 0, so we stop at 0. **The next part is about modifying a FT. This isn't required for this challenge, so feel free to skip it, but it's cool if you're interested.** **To modify the \$N\$th element** (as in increasing it by a certain value) we start by modifying `FT[N]`, which clearly needs to be updated. The next value to be updated is actually very simple to find. Observing the diagram, if we modify 12, note that we don't want to modify 13, 14, or 15. This is because they don't contain the 12th element in their summation range. We know this because by removing the LSB of any of those numbers repeatedly, we will eventually get 12. Thus, we want the first number that doesn't contain the non-trailing-zero-digits of 12 as a prefix. In this case, 12 is `1100`, so we need a number that doesn't look like `11__`. The smallest number satisfying this condition is obtained by *adding* the LSB. Adding any smaller value would just fill in the trailing zeroes of the original number; adding the LSB changes the bit in the position of the LSB from a 1 to a 0, which gives the smallest number that doesn't share the prefix. Therefore, if we want to update element 9, we first update 9, then the LSB of 9 is 1, so we update 9+1=10. Then, the LSB of 10 is 2, so we update 10+2=12. Then, the LSB of 12 is 4, so we update 12+4=16. Then, we would update 32, but that value is now out of range, so we stop here. The following pseudocode shows implementations of the modify and sum operations on a FT iteratively. ``` func modify(index, change) # index points to the value in the represented array that you are modifying (1-indexed); change is the amount by which you are increasing that value while index <= len(fenwick_tree) fenwick_tree[index] += change index += least_significant_bit(index) func sum(count) # sum(n) sums the first n elements of the represented array total = 0 while index > 0 total += fenwick_tree[index] index -= least_significant_bit(index) least_significant_bit(x) := x & -x ``` # Challenge Given the Fenwick tree for an array `a` and an integer `n`, return the sum of the first `n` values of `a`; that is, implement the `sum` function given as an example. # Reference Implementation A reference implementation in Python for both the `make_tree` and `sum` functions is provided [here](https://tio.run/##bVHLbsMgEDybrxhFcmU3pMLKqVHdSz8jiiJUkwbFxhYmSvP1Lgs4stqe2GV2HizD3Z17s52mRp3QyYs6OqtUIa2V93LHspMyN/15QY29OOAZrTIJ9FhvoaENrDRfqqj4AsUaFfGz21m3yo@91QFNegGaxfcaG1QHrGsEcuppQtOlxhM2mmVWuas1SCzGKPJ47WZN7qM06pukXe9k6zMLNvsTgncI8o2oF374BzR5pqZOHLKm4mEf2Izpbuito6c3fcfY311UgpJEkTrNvdChjSsEx6vfYHgu7fY/GKR5XGiK0uej7/GM31/FssESc/UhR4W82cVVQo/IR47ASnWMRE3DaX@xXCFHoXmkRUIaDUPF4qIsy2n6AQ). # Test Cases These test cases are given 1-indexed, but you can accept a leading 0 to 0-index it if you would like. You may also request a trailing 0 to be included (though adding a trailing 0 should not break any solutions that do not request this). ``` [6, 6, 3, 20, 8, 12, 9, 24, 8, 12], 6 -> 32 [6, 4, 3, 36, 1, 8, 3, 16, 5, 4], 3 -> 7 [2, 10, 1, 4, 4, 2, 0, 32, 1, 14], 4 -> 4 [7, 8, 4, 36, 9, 0, 0, 8, 1, 4], 5 -> 45 [3, 0, 7, 12, 4, 18, 6, 64, 6, 14], 6 -> 30 [3, 4, 3, 28, 5, 6, 8, 40, 1, 8], 9 -> 41 [4, 8, 8, 4, 0, 18, 7, 64, 0, 12], 7 -> 29 [9, 0, 6, 16, 8, 14, 5, 64, 3, 18], 0 -> 0 [3, 14, 7, 12, 2, 6, 5, 0, 7, 18], 2 -> 14 ``` # Rules * Standard Loopholes Apply * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes in each language will be considered the winner of its language. No answer will be marked as accepted. * You may take the two inputs in any order and the list in any reasonable format. * You may assume that the integers in the tree are all non-negative. * No input validation - the index will be non-negative and at most the length of the Fenwick tree * You may assume that all values (in the list, as the index, and the output) will be at most \$2^{32}-1\$ Happy Golfing! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` &’$ƬịS ``` A dyadic Link that accepts \$N\$ on the left and the Fenwick Tree (using the trailing `0` option) on the right and yields the prefix sum. **[Try it online!](https://tio.run/##y0rNyan8/1/tUcNMlWNrHu7uDv7//7/Z/2gzHQUgMtZRMDLQUbDQUTA00lGwBPJM4DyDWAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##RY@9DcIwEEb7TOECUVnC/3Y6dqCMXNKgLECHaJmACWjYgBKJPcgi5vydHSRLyfnefX53Os7zuZTtcrlvPs/v63Yo78d@t1yfpUzTFKSgY6UwSookhTZSjFS5tVKZkDxIsA6spT8NgApNhUenkhYkjWkFxuHUGOoZXOmGOqAROY5DR3DNZM30AC0akaWooxPUg8Onh4bOsqlJkAv8iOralRxB8p5soDg0cqj6rx@BslzgjRM/6Zm1PFlZ1QVqu9kajPl1gYaaPOQf "Jelly – Try It Online"). ### How? ``` &’$ƬịS - Link: N, FT Ƭ - start with k=N and collect up while distinct applying: $ - last two links as a monad - f(k): ’ - decrement (k) & - (k) bitwise AND (k-1) ị - index into (FT) S - sum ``` [Answer] # JavaScript (ES6), 24 bytes Expects `(array)(n)`, using the 1-indexed format. ``` a=>g=n=>n&&g(n&--n)+a[n] ``` [Try it online!](https://tio.run/##bZDNasMwEITvfYo9mRW1G/1Zsg/OiwQfTJqYliCXpvT13dWuyEENCKyx9Glm9nP5Xe7n74@vny5t75f9Ou3LdFynNB1T06yYmq5L6nU5pXk/b@m@3S5vt23FK55CC7RcC1a3MLRgbAsjKV/UrDAoBYcDOPvyn/XMOtoZBkgYEj2dzAoAnbCxRsnFaIY8L9IkneVfJrPoBfU1GtnIi@vIXIleTAH7gvY16/hulJr0hBm4fvD8yb6PtvoJK23twAWD5JAWA7cdi6@pWZmmxNZiG8VWy5ABo7B2rFmpGGSwuaYXewljyBm1sM8i59ulr@VX@scIcma0ghq//wE "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // outer function taking the array a[] g = n => // inner recursive function taking n n && // stop if n = 0 g(n & --n) // otherwise: do a recursive call where n AND n - 1 is passed, // which clears the LSB (e.g. 0b110 & 0b101 -> 0b100) + a[n] // add a[n] to the final sum (where n was decremented above) ``` [Answer] # [J](http://jsoftware.com/), 18 15 bytes ``` +/@:{~#:#]\&.#: ``` [Try it online!](https://tio.run/##NZDLSsRAEEX3fsXFgOPgGLuqK52kYWBgwJUr185KHMSNHyD465m6/aBJaMjh1Kn8bPfj7opjxg4HBGR/nkec399et6eXU/77H/Jw@XgYh7ztcff1@f2LqDjiMSD5idCABaJYoVZue1z9Q0XnTpqTMUGciJCECUYuNs4qp5DgjPlRD/FBAimgdXCq5Owio3F1rhRU4dQbQ@UiyHqeQRYWm7@qsjeadJSRurgj0c6SheDaQF0ryDU5PVA5Uxna2nMj23C2JW7reUYtB0hxhkaK9eF@K6EK/p1SXUjFdgM "J – Try It Online") -3 thanks to Jonathan Allan for pointing out that I could take the lists with an extra 0 in front Consider index 6: * `]\&.#:` Prefixes "under" conversion to binary. Since 6 is `1 1 0`, its prefixes, including 0 fill on the right, are: ``` 1 0 0 1 1 0 1 1 0 ``` And after "under" converts back to decimal we get: ``` 4 6 6 ``` * `#:#` Filter by the binary number: ``` 1 1 0 # 4 6 6 becomes: 4 6 ``` * `+/@:{~` Select `4 6` from the list we're given and sum. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), ~~41~~ ~~22~~ 9 bytes ``` ≬:‹⋏↔Ṫ‹İ∑ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%86%92f%7B%3A%7C%3A%E2%86%90f%24i%C2%A5%2B%C2%A3%3A%3A0%24-%E2%8B%8F-%7D%C2%A5&inputs=%5B0%2C%206%2C%204%2C%203%2C%2036%2C%201%2C%208%2C%203%2C%2016%2C%205%2C%204%5D%0A3&header=&footer=) -13 bytes thanks to Razetime. [Answer] # x64 (Windows), 13 bytes ``` 31 c0 03 04 8a c4 e2 70 f3 c9 75 f6 c3 ``` In assembly: ``` xor eax, eax _sumloop: add eax, [rdx + rcx*4] blsr ecx, ecx jnz _sumloop ret ``` Takes the address of the FT in `rdx` and the index in `ecx`. The FT must have a zero stored as its zeroth element, to ensure that passing zero as index returns zero (it doesn't affect anything else, the only way in which the zeroth entry is used is if the index is zero to begin with, otherwise when it becomes zero the loop stops). [blsr](https://www.felixcloutier.com/x86/blsr) directly implements "reset lowest set bit", and sets the zero flag according to the result, which we can then branch on. Fun facts: * `blsr` weighs in at a gigantic 5 bytes, which does not save space compared to a `lea \ and` pair .. but there is more to it. In any case `blsr` seemed like more fun. The fun thing is, in order to use `lea \ and`, we'd need an extra register, and on Windows we'd be forced to either pick a non-volatile register (adding size for save/restore) or one of the "numbered registers" (which would cost two extra REX prefixes to encode). However, switching to the SysV x64 calling convention would work around that, since it uses `rdi` and `rsi` for the first two parameters and that frees up `rdx` or `rcx` as a scratch register. * `loop` (with its built-in `dec rcx`) seemed useful, but isn't, since we need the value from before the decrement as well and recreating it cancels the size benefit that `loop` might have had. * can be adapted at no addition cost to deal with an FT with over 232 entries, but adapting it to deal with results of 232 are greater would cost an extra byte (`REX.W` on the `add`, the `xor` can stay the same). Adapting the `lea \ and` version for giant FTs would cost additional `REX.W` bytes, but for `blsr` the `W` bit is already present in the VEX-prefix so it doesn't cost extra space. [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` ΣM!U¡Sn← ``` [Try it online!](https://tio.run/##yygtzv7//9xiX8XQQwuD8x61Tfj//7/Z/2gzHTMdYx0jAx0LHUMjHUsdIxMIyyAWAA "Husk – Try It Online") There may be a way to shorten with `ṁ` here. Not sure how, though. ## Explanation ``` ΣM!hU¡Sn← ¡ infinite list using n: S Self n bitwise AND with ← its decrement U keep all unique results h remove last M! map left(indices) to indexes in right(fenwick tree) Σ sum ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ü→,¿(≡Y▓ ``` [Run and debug it](https://staxlang.xyz/#p=811a2ca828f059b2&i=%5B0,+6,+6,+3,+20,+8,+12,+9,+24,+8,+12%5D,+6+%0A%5B0,+6,+4,+3,+36,+1,+8,+3,+16,+5,+4%5D,+3+%0A%5B0,+2,+10,+1,+4,+4,+2,+0,+32,+1,+14%5D,+4+%0A%5B0,+7,+8,+4,+36,+9,+0,+0,+8,+1,+4%5D,+5+%0A%5B0,+3,+0,+7,+12,+4,+18,+6,+64,+6,+14%5D,+6+%0A%5B0,+3,+4,+3,+28,+5,+6,+8,+40,+1,+8%5D,+9+%0A%5B0,+4,+8,+8,+4,+0,+18,+7,+64,+0,+12%5D,+7+%0A%5B0,+9,+0,+6,+16,+8,+14,+5,+64,+3,+18%5D,+0+%0A%5B0,+3,+14,+7,+12,+2,+6,+5,+0,+7,+18%5D,+2+&m=2) Takes inputs with a leading 0 for 0-indexing. ## Explanation ``` {cvIgi@|+ { gi generate values from n, till invariant: c copy v decrement I bitwise AND @ get elements at those indexes in a |+ sum ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 31 bytes ``` f=->a,n{n>0?f[a,n&n-=1]+a[n]:0} ``` [Try it online!](https://tio.run/##PVBBCsIwELz3FYGCWEwhm8Q0FVofEoJUsMcgWg8ivr1udlMh0MzOZGa2j9f1va7z0I6TTJ80qvMc8LZL7QDxMIUUT@q73sUcgpMCj5FCKym8FKCl6BHZgiLysdqklqQGb0A8AkBwRAaFJlZ1wPegiLd0ECM0mkaQZaGjt5aNeuJLOPsEQ4OO26AOPLV0lj6wabiN9lTAsSlH@6zgFThJsUnHJqpsFjjc8Ra5gGUvdgZfgvK4tNEkP/4L@thU9XJ7LpckBrHnf2m3Rj2JUKqb9Qc "Ruby – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~36~~ 34 bytes Saved 2 bytes thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! ``` f=lambda a,n:n and a[n]+f(a,n&~-n) ``` [Try it online!](https://tio.run/##PVHRboMwDHznK/w0iJpKJKRAK7EfYWhKaVCrbSkqTNqG2K8zx4ahSOTsy93F6b/H691ny9JV7/bjfLFgpT95sP4CtvbNrkuw8PS792IZ3TC@WqggqXMJuDIJOpVQSlBawhGRWVEjIXAMcTLcKWogUAgO2AkMPKRS6hlaiBFmmkqKKAWdMyxypP7quGpkVCg4AvJUSdFyQz@1cTiJLsk8Z1G2LgODc7NTyiIFi6Tbddg85xuEAIa1WFmVq1Eor2k00Q//ActGRDRDH2bI8zNboCNxkKlF5L56147uEmhhGgUPCIkZEgyG1pxGGRG1V9e@uUfgxi@fujBtLIF2KotF1N0f4Umlg5uHn1uf8CtK4CQSNjNxigC/MwrVaQM7sIQHxF1yll4Q7B83PyZdPNlZwuRn2D/DNMwwrTFqV1VDM8di@QM "Python 3 – Try It Online") Inputs Fenwick Tree \$a\$ (with a leading \$0\$) and \$1\$-indexed \$n\$. Returns the sum to \$n^{\text{th}}\$ element. [Answer] # Java, ~~49~~ ~~47~~ 35 bytes ``` a->n->{for(;n>0;n&=n-1)a[0]+=a[n];} ``` Expects array with leading zero and sets the first element of the input array to the sum. [Try it online!](https://tio.run/##dVDBSsNAED3br5iTJLpZmraKkjYXQfDgqceQw5puytZkEnYnlRLy7XGyDYKIwx72zZt57zEndVbR6fA5mrptLMGJsezIVLLssCDToLxLFn9I7rXdR2UKKCrlHLwrg9AvgMuRIu6/zutbg5Tl4qVB19Xabt@Q9FHbNC13o4pSjNK@bGyQYLpM8HaHURyqbJnf71SGeTKMiRedzWbtc2MOULNlsCdr8JjloOzRhf3ihrSjAPUXeNt@KeDRv7WAFYMnAfFKwDOjzYwG5sPkn82N31zzL/bjDGIGD8wMYh1eww3XiNacFelfGb2m1@OAVkzSgOH1TlOVUrVtdQmYDKUqCt1yhCnM/uJI17LpSLIuUoXTDN/lx3IYvwE) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~31~~ ~~38~~ 36 bytes Added 7 bytes to fix a problem kindly pointed out by [Nick Kennedy](https://codegolf.stackexchange.com/users/42248/nick-kennedy) and [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld). ``` f(a,n)int*a;{n=n?f(a,n--&n)+a[n]:0;} ``` [Try it online!](https://tio.run/##bVRtb5tADP6eX2EhZYLk0OA4XlKa9cO0X5GgCRHSorJrFSItWsRfX@azgXJZI4Kxn@exfWe4yn@uqtvt6JZCe40@r8r8qrf6iQK@/0V763Kni4cg72/vJyS4RBKABloPrnB8O4EJQgNbCHI0j9DmsF43HpDi6DrLbnlwhNs8OQKcB8fxBJS7pvBy6BdG@qtstOstrgvAnwmc6@4c7ArMeE0E4BUJkIGATEAoBWzQU4PX55MinBSKFBE@hURDJ0QnRmTGl8zHhGFATEUX@uhGkkLhXBCxIKWcigtsiD30ZudXTI8ITrl1VIUZLSlRZKwC8aTgFciMmk64IDeZzfgJ83kvuKeAC6RcILjbopQF3HTCu2IaV1yHq4bzEtnUkiENq5AkjqeFoWCc3YpUHatojoKHw0ayidgoNjGbhE3KZpaT/J8t5@yaP/Xb0aXU3tfBW7ErYIaGNhraqLRRaaORjUY2qmxU2Whso7GNJjaa2Ghqo6mNZjaaefdbpKcvgF8hfnc2NCScg5zx68t7XZ3rwzBeSRzzAaAmQq7CgUl@T8wrSrrqpTyt8F5Xr/UJhWCkzv7yQ@4vm@/4j80HPvMjZ1B@nBL6UF@Gk4IeH8cFjg19rHGK0HFi2HjgULpxERozDQsnvMjn8Koc4O4zFNpR3H4KdwjzuWjHa4xPm3cvHE@8nePdBTETHpj/MwsBywP438x92e017qDGoYtpm@vttisGYb/ob3@rY1s@dzf/9z8 "C (gcc) – Try It Online") Inputs a pointer \$a\$ to the Fenwick Tree and a \$1\$-based \$n\$. Returns the sum to \$n^{\text{th}}\$ element. [Answer] # [Haskell](https://www.haskell.org/), 48 bytes ``` import Data.Bits a!n|n<1=0|y<-n-1=a!!n+a!(n.&.y) ``` [Try it online!](https://tio.run/##PY/PaoQwEIfveYoIS1dptEmM/7qmh9Jj30D2EFjbhrpR1MMu7LvbyUQKAZ3Ml99882OW334Yts1ep3Fe6YdZTfZu14WYyD1cKzR/3NvUpUKbKHLPJopd9pTdk@1qrNOXkdDYsjFp06@rmeLLPE40T7JlMi5@0cf0mLSHt@9@/bSuJ3To1y42hjmXnPXcm8tC7clo/mrMyeHFYTV2oM6dblhSyJ9m69YYdLS@MXjLbgmhfvrWlYzCyRmVnNGaUSEZbaBSe3WGPk3faC6JZxWyOfwJBKAQUBTQATL3ZEU6yBAcEYUHaihziVfCk8qTinQVpqgQ2SC2e4TEArmCdDk2qiAIvKhRvFT4wczgyZENnrJGtTIMCUY1kA2mCtKFLYMBD6FVCOX78pVHZUO6IFeGfb2gCtlhkvCx3LNhvu/ushJfFf/@npSeFOoP "Haskell – Try It Online") The relevant function is `(!)`, which takes the Fenwick tree `a` as a list of integers with a leading 0 and `n` as a 0-indexed integer. Haskell is probably the only language which needs an import to perform bitwise operations. [Answer] # [R](https://www.r-project.org/), 49 bytes ``` f=function(a,n)"if"(n,f(a,bitwAnd(n,n-1))+a[n],0) ``` [Try it online!](https://tio.run/##K/r/P802rTQvuSQzP08jUSdPUykzTUkjTycNyEnKLCl3zEsB8vJ0DTU1tROj82J1DDT/p2kka5jpKACRsY6CkYGOgoWOgqGRjoIlkGcC5WkC5TW5iFQJNBMA "R – Try It Online") The same approach as [@Arnauld's answer](https://codegolf.stackexchange.com/a/225635/55372). [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 61 bytes ``` function f($a,$n){for(;$n-gt0;$n=$n-band$n-1){$r+=$a[$n]};$r} ``` [Try it online!](https://tio.run/##DcZBCsIwEEbhvaeYxb9IcAqtVqmUgPcQF6M2KpSJpBUXpWePs3nv@6TfkKfXMI4FEs5uz9QyWXcd04HpyGRoa6bG5DfQcCrxq/f5nZSigzDULzFl10Or51zbgukm@rA1fkHeBsgFel175LVEghC0/AE "PowerShell – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Port of [Arnauld's solution](https://codegolf.stackexchange.com/a/225635/58974) so be sure to +1 them. ``` ©ßU&´U +UgV ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=qd9VJrRVICtVZ1Y&input=NgpbNiwgNiwgMywgMjAsIDgsIDEyLCA5LCAyNCwgOCwgMTJd) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~19~~ 17 bytes ``` IΣE⮌↨η²∧ι§θ&η±X²κ ``` [Try it online!](https://tio.run/##NYrNCsIwEIRfZY8bWKHWfzzZnjwoRY@lh6VdbLBNNYmtbx@j4DDMwDdTt2zrgbsQCquNx5ydx@urxxM/8CKjWCeYcYyWIFWK4GAa1LH80TTyxidBpv2knXyHeDrLjb1gMUxiMSW4q7/2IZRlQrAh2BIsCRZrgh1B8nNE80grglUVZmP3AQ "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Explanation: Turns out to work somewhat like Jonah's J answer, but having to use bit twiddling instead of that handy zero-filled prefixes function. ``` η Input integer `n` ↨ ² Converted to base 2 ⮌ Reversed E Map over digits ι Current digit ∧ Logical And θ Input array `a` § Indexed by η Input integer `n` & Bitwise And ² Literal `2` X Raised to power κ Current index ± Negated Σ Take the sum I Cast to string Implicitly print ``` [Answer] # MMIX, ~~40~~32 bytes (~~10~~8 instrs) Assumes array of octas, preceded by 0 octa, which first argument points to. (jxd) ``` 00000000: e302 0000 3b01 0103 8eff 0001 2202 02ff ẉ£¡¡;¢¢¤⁾”¡¢"££” 00000010: 27ff 0101 c801 01ff 5b01 fffc f803 0000 '”¢¢Ṁ¢¢”[¢”‘ẏ¤¡¡ ``` ``` sfen SET $2,0 // s = 0 SLU $1,$1,3 0H LDOU $255,$0,$1 ADDU $2,$2,$255 // loop: s += a[n] SUBU $255,$1,$1 AND $1,$1,$255 // n &= n - 1 PBNZ $1,0B // if(n) goto loop POP 3,0 // return s ``` --- Old version: Assumes the tree is an array of octas. (jxd) ``` 00000000: 27020008 e3000000 3b010103 42010006 '£¡®ẉ¡¡¡;¢¢¤B¢¡© 00000010: 8fff0102 220000ff 27ff0101 c80101ff Ɓ”¢£"¡¡”'”¢¢Ṁ¢¢” 00000020: 5b00fffc f8010000 [¡”‘ẏ¢¡¡ ``` ``` sfen SUBU $2,$0,8 // a = arr - 1 SET $0,0 // s = 0 SLU $1,$1,3 BZ $1,1F // if(!n) goto end 0H LDOU $255,$1,$2 ADDU $0,$0,$255 // loop: s += a[n] SUBU $255,$1,$1 AND $1,$1,$255 // n &= n - 1 PBNZ $1,0B // if(!n) goto loop 1H POP 1,0 // end: return s ``` [Answer] # [R](https://www.r-project.org/), 40 bytes ``` function(a,n)sum(a,-a[n%%2^(0:n)-n])*!!n ``` [Try it online!](https://tio.run/##bZDxSsMwEMb/31NkyKCRFHKXa9MK@iKiMoqDMcxgOnz8erlrqmRCIPmS/O677y7z4T19H6fT2@f143E@XNP0dTynZu@S5Rve2/1z2u3wtfEPybbpxd5vt@kv1UxN7wyv4Ax6ZwZnAJ0ZWdGiLL8ba@5M@2QCbm5gEjjwCYRgASw6fmE0FDRWJLuAF4ZksWYZUK4go1RQqtAoPqSmo3BL6@rZrWBXkUF@Rg3JBWCQ8D3JJq6/Wf0trFlxkHi9tqEhBkbH1RcqVGepTXu1jWrrlxHHwuJYsRqw16nmkKTu2gtkY1/gf1rO35fAKGW6dQYZxYICbeYf "R – Try It Online") Non-recursive approach: the unique values of `n-n%%2^(0:n)` give the indices that we need to sum. We could use `sum(a[unique(n-n%%2^(0:n))])` for [41 bytes](https://tio.run/##bZD9asQgEMT/v6dYKAcKHuhqYlJoX6TclSPcQSi13Efo46frbkyLVxCSUX/OzF7n8yl9j8PH@236fJnPUxru41dSR5M07ajj25TGy3RSaZe2Wzwo@5y03uu/mBpUa4CWN4DWQGfAoYGeVFiUpnPQ8AS7V/C4eYADw57@HBMkHImGTgj1BY0VSS7OMhN4kSbpkbdcRkNBQ4VG9gli2jO3RBfPZgWbivR8M0pJesB1XL4N/GHX3672EZau2HG9VmJIiY7QfvV1FSqzlNBWbKPY2mXEsbDYV6wUbGWquWQQd8nisrEt8D@R8/WlMPIzzTqDjGJBXdjMPw). However, since negative indices in [R](https://www.r-project.org/) specify elements to *exclude*, they're effectively used uniquely already, so we can subtract the sum of the elements of `a` that we *don't* want (`a[n%%2^(0:n)-n]`) from the sum of `a` to get the same answer saving one byte. This unfortunately fails when `n` equals zero, so we need to multiply the result by zero in this case (or by 1 otherwise), hence the ugly `*!!n` at the end. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Dλ£D<&}èO ``` [Try it online](https://tio.run/##yy9OTMpM/f/f5dzuQ4tdbNRqD6/w///fjCvaQMcMCI11jAx0LHQMjXQsdYxMwKxYAA) or [verify all test cases](https://tio.run/##NY89CsIwGIavUjo4vUN@vqYtCF26e4BQUMHByaEgdHD1AF7BxTu46e4hvEj93qQSCEme7/3Jadztj4f5PHVl8b3eirKbtuPcf56ve79eXd6PzYw5xoBoEHR5OIMG1qGFk3QaBhTR5wHRAR9gFXjYgAqSsBA7WKNIdDkYeL3DZl6R16oSylulKWVRp3QPTmiwwDbsIrot8jYPMN01GhroxKwm4ZqYZelvKK8pN//yhpyhgZ01V@hBN5sNXPbX99TAgT9LdZQPPw). ### [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` bη0ζζCÙèO ``` Port of [*@Jonah*'s J answer](https://codegolf.stackexchange.com/a/225644/52210), so make sure to upvote him as well! [Try it online](https://tio.run/##MzBNTDJM/f8/6dx2g3Pbzm1zPjzz8Ar////NuKINdMyA0FjHyEDHQsfQSMdSx8gEzIoFAA) or [verify all test cases](https://tio.run/##NY89CsIwGIavUjo4vUN@vqYtCF26e4BQUMHByaEgdHD1AF7BxTu46e4hvEj93qQSCEme7/3Jadztj4f5PHVl8b3eirKbtuPcf56ve79eXd6PzYw5xoBoEHR5OIMG1qGFk3QaBhTR5wHRAR9gFXjYgAqSsBA7WKNIdDkYeL3DZl6R16oSylulKWVRp3QPTmiwwDbsIrot8jYPMN01GhroxKwm4ZqYZelvKK8pN//yhpyhgZ01V@hBN5sNXPbX99TAgT9LdZQPPw). Both take the inputs in the order \$n,a\$, and are 0-based with the additional leading `0` in \$a\$. **Explanation:** ``` λ # Start a recursive environment, D £ # to output the first (implicit) input amount of values D # Starting with a(0) = the first (implicit) input # Where every following a(n) is calculated as: # (implicitly push the previous term a(n-1)) D # Duplicate this a(n-1) < # Decrease the copy by 1 & # Bitwise-AND the a(n-1) and a(n-1)-1 together } # After the recursive environment: è # 0-based index each value into the second (implicit) input-list O # And sum those together # (which is output implicitly as result) ``` ``` b # Convert the (implicit) input-integer to a binary-string η # Get the prefixes of this string 0ζζ # Pad each with trailing 0s until the list of strings is rectangular-shaped: ζ # Zip/transpose; swapping rows/columns, 0 # using a "0" as filler for unequal length rows ζ # Then zip/transpose back C # Convert each string back to an integer Ù # Uniquify it è # 0-based index each value into the second (implicit) input-list O # And sum those together # (which is output implicitly as result) ``` Note: the legacy version didn't had the recursive environment `λ` yet, so the first program only works in the new version of 05AB1E. Also, zip/transpose doesn't work with a list of strings in the new version, so the second program only works in the legacy version of 05AB1E - and would require an additional `S` (split to characters/digits) and `J` (join together) for the new version of 05AB1E: `bSη0ζζJCÙèO` - [try it online](https://tio.run/##yy9OTMpM/f8/KfjcdoNz285t83I@PPPwCv///824og10zIDQWMfIQMdCx9BIx1LHyATMigUA). ]
[Question] [ # Context (Feel free to skip, doesn't really matter for the algorithmic explanation of the task) European Portuguese is a fairly complicated language to learn, mostly because of its grammar. One particular annoying thing is conjugating the verbs correctly: We have this mechanism that, when we have a verb followed by a noun, we may replace the noun by a pronoun and create a contraction with the verb, by means of a hyphen (-). This introduces a problem because many verb tenses sound like verb-pronoun contractions and many verb-pronoun contractions sound like verb tenses... And then, (Portuguese!) people want to write Portuguese and they know how it should sound, but they don't know if they should insert a hyphen or not... (Strictly speaking, the two variants have subtle differences in intonation.) So we are taught a decent method to help us discern if we should use a hyphen or not, that revolves around putting the sentence in the negative form. When the hyphen belongs there, the negative form makes the contracted pronoun go before the verb. When the hyphen doesn't belong there (and it is really just a verb tense) the verb doesn't change. So you negate the sentence and try placing the suspect pronoun in both places. What sounds right is probably the right choice. # Task Given a Portuguese sentence, perform the basic test to help discern if a sentence should use a hyphen in a contraction or not. ## Basic algorithm for the challenge We are going to simplify things a bit here. Your code should do the following (check below for two worked examples) 1. Look for the only hyphen in the input sentence (the hyphen that we are unsure about), between two words, like so: `verb-pronoun` 2. Output the two following modified sentences: * in the place of the `verb-pronoun`, use `"nao" verbpronoun`, i.e. prepend "nao" and drop the hyphen; * in the place of the `verb-pronoun`, use `"nao" pronoun verbs` where `verbs` is the verb (with an extra "s" if the verb ended in a vowel "aeiou"). ## Worked examples Let `"sei que apanhas-te um susto"` [~I know you were scared] be the input. We find the hyphen and extract `verb = "apanhas"` and `pronoun = "te"`. The `verb` does not end in a vowel, so there will be no need to add an "s" for the second sentence. The two sentences will be of the form `"sei que _ um susto"`. Indeed, they are: 1. `"sei que nao apanhaste um susto"` [~I know you were not scared] 2. `"sei que nao te apanhas um susto"` [~I know were you not scared] So clearly we should go with number 1. Now let us take `"da-me um upvote"` [~give me an upvote]. The hyphen is in `"da-me"` so we take `verb = "da"` and `pronoun = "me"`. The verb ends in a vowel so we will need to use `verbs = "das"` in the second sentence: 1. `"nao dame um upvote"` [~give me an upvote not] 2. `"nao me das um upvote"` [~you don't give me an upvote] So clearly the right Portuguese sentence would be number 2. # Input A string composed of spaces, characters in the range `[a-z]` and a single hyphen surrounded by two words. The input string can be in any sensible format, like a string, a list of words or a list of characters. # Output The two modified sentences, as described above. These can be printed separately, returned in a list, or whatever is sensible in your programming language. * The two sentences can be interchanged, i.e. order doesn't matter. * The two sentences can be in a single string, as long as they are separated by a character that is not in `[a-z \-]`. # Test cases ``` "sei que apanhas-te um susto" -> "sei que nao apanhaste um susto", "sei que nao te apanhas um susto" "da-me um upvote" -> "nao dame um upvote", "nao me das um upvote" "conta-me no que estas a pensar" -> "nao contame no que estas a pensar", "nao me contas no que estas a pensar" "pensei em bater-te" -> "pensei em nao baterte", "pensei em nao te bater" "isto custa-me a crer" -> "isto nao custame a crer", "isto nao me custas a crer" "passeia-te pela rua" -> "nao passeiate pela rua", "nao te passeias pela rua" ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it... And happy golfing! --- This is the third challenge of the [RGS Golfing Showdown](https://codegolf.meta.stackexchange.com/q/18545/75323). If you want to participate in the competition, you have 96 hours to submit your eligible answers. Remember there is still 350 reputation in prizes! (See 6 of [the rules](https://codegolf.meta.stackexchange.com/q/18545/75323)) Also, as per section 4 of the rules in the [linked meta post](https://codegolf.meta.stackexchange.com/q/18545/75323), the "restricted languages" for this third challenge are *only* [Pyth](https://codegolf.stackexchange.com/a/200301/75323), [MATL](https://codegolf.stackexchange.com/a/200264/75323), [Husk](https://codegolf.stackexchange.com/a/200376/75323) and [CJam](https://codegolf.stackexchange.com/a/200333/75323) so submissions in these languages are not eligible for the final prize. But *they can still be posted!!* Otherwise, this is still a regular [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so enjoy! [Answer] # [Python 3](https://docs.python.org/3/), 112 bytes ``` (*a,v),(p,*b)=map(str.split,input().split('-')) a+='nao', print(*a,v+p,*b) print(*a,p,v+'s'*(v[-1]in'aeiou'),*b) ``` [Try it online!](https://tio.run/##RYsxDsIwDAD3viKb7TRBQsx9CWIwVSQs0cRKnEq8PkAZGO90py97lHwZAz2HnQJq8HdaNlZsVk9Nn2JBsnZD@hFCBKKJ5wUyFwiTVsl27PMx/4V@FDTwuF/j@SYZOEnpQN9qDGlW3NqbcdySY7fWVN8 "Python 3 – Try It Online") [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~167~~ \$\cdots\$ ~~143~~ 142 bytes Saved a byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!!! ``` lambda p:((n:=(g:=re.match(r'(.*)\b(\w+)-(\w+)(.*)',p).group)(1)+'nao ')+(v:=g(2))+g(3)+g(4),n+g(3)+' '+v+'s'*(v[-1]in'aeiou')+g(4)) import re ``` [Try it online!](https://tio.run/##fVLLbtswELzrKxa6kIwko25yKAQwx3xBbrYPa4m2BVgky4eDwvDX9FP6YS5J0VZdILkQy5nh7OxK@pc7KPn8Q5vrjq@vRxy3PYJuKZUtp/uWG7EY0XUHaghdPLH1lq4/KtakMwKk1myxN8prRpesIhIVEFbRU8v39Dtj1Z4@x@OF1XKqCZDqVBFLnuhp1Sw3gyQoBuXJJGPFMGplHBhxNfz8brxoy06NqqzhDY823OSf3woSdCmcsA440AJoacUAP70A1CgPaBsnwI9gvXXx8czHjFnzKHlQuLvRLGGsjo16bMb00OuTciKZxyc9/gcnNGD9ZJLx7NIp6ZKRVKlpmCTIwvaFtGjupkn2herWI@nsJ7LcMt7CiGKELTphmpx9hqNXoqb4j0TYSOJubkNYCXRhMWkKhM6IKXYiUvZI/svNVEzsc8hE3iKiDS0xfjwtjgjG430VmXukyhwtk3bmkiMrdsqAqwUMEuLf0hZg@Y46VoA2g3R0R8qzu5TQvEJ5tqtvm0t0DdUyVHA2K8u52FzCSrUw2CvCrn8B "Python 3.8 (pre-release) – Try It Online") Inputs a string and returns a tuple of two strings. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~57~~ ~~55~~ ~~53~~ ~~51~~ ~~41~~ ~~40~~ ~~39~~ 38 bytes *-3 bytes thanks to @KevinCruijssen* *-1 byte thanks to @Grimmy* ``` #ʒa_}н©¡D®'-¡Âðý¤žMså's׫sJ‚vy"nao ÿ"ý ``` [Try it online!](https://tio.run/##AVYAqf9vc2FiaWX//yPKkmFffdC9wqnCoUTCrictwqHDgsOww73CpMW@TXPDpSdzw5fCq3NK4oCadnkibmFvIMO/IsO9//9pc3RvIGN1c3RhLW1lIGEgY3Jlcg "05AB1E – Try It Online") --- ### Explanation ``` # - split input on spaces ʒ'-¢}н© - get the hyphenated word ¡D - split the input on this word (removing it) ®'-¡ - split the hyphenated word into its two parts Âðý - Swap and join with space - (e.g. custa-me -> me custa) ¤žMså's׫ - if the last char is a vowel add an 's' sJ - swap and join the other hyphenated word - (e.g. custa-me -> custame) ‚ - put these in an array so ["custame","me custa"] vy"nao ÿ" - for each of these add nao in front ý - then join the split input with them ``` --- [Answer] # [V (vim)](https://github.com/DJMcMayhem/V), ~~38~~ 37 bytes My first ever V answer I believe ...props to the inventor, [James](https://codegolf.stackexchange.com/users/31716/james) A.K.A. DJMcMayhem! ``` ÄÎf-binao ó¨[aeiou]©-/±s- f-dbeá pí- ``` **[Try it online!](https://tio.run/##AUQAu/92///DhMOOZi1iaW5hbyAKw7PCqFthZWlvdV3CqS0vwrFzLQpmLWRiZcOhIHDDrS3//3BlbnNlaSBlbSBiYXRlci10ZQ "V (vim) – Try It Online")** ### How? ``` ÄÎf-binao <CR>ó¨[aeiou]©-/±s-<CR>f-dbeá pí- | implicit read from STDIN Ä | copy line, paste below Î <CR> | for all lines: f- | find "-" b | back one word i | enter insert mode naoS | "nao " | (<CR>: implicit exit from insert mode) ó / <CR> | single substitution on line: | pattern.../: ¨ © | group (1): [ ] | any of: aeiou | "aeiou" - | + "-" | /...replacement: ± | group (1) s- | + "s-" f- | find "-" db | cut back a word e | move to end of word áS | insert a space character p | paste í | single substitution on every line: | pattern.../: - | "-" | /...replacement: (implicit) | "" | implicit print to STDOUT ``` [Answer] # Java 8, ~~107~~ ~~121~~ ~~119~~ 107 bytes ``` s->s.replaceAll("(.*?)(\\w+)-(\\w+)(.*)","$1nao $2$3$4;$1nao $3 $2"+(s.matches(".*[aeiou]-.*")?"s$4":"$4")) ``` +14 bytes for a bugfix (thanks to *@ovs* for mentioning it) -12 bytes thanks to *@Arnauld*. Now we're back to the initial -bugged- byte-count again. xD Outputs with `;` delimiter between the two sentences. [Try it online.](https://tio.run/##dVHBTsMwDL3zFVbUQ7LRSLCdNsHEkQPjwHHbwcsCy2jTUCdDCO3bi9sVpA24JLHfi9@zvcM95rvNa2MKJIIHdP7zAsD5aOtnNBbmbQjwFGvnX8DI/kFqyvnDBR8UMToDc/BwAw3lt6RrGwr@fFcUUkg9mCm5XL4PVX68OKPEpciuPFaQXWejbDztgxHHYihJlxjN1pIUerBA66q0yvVAqJmgbCwmgg@lmmkrH9K6YPnexb5yGyi5i97oYgWoji1ES1EKsg7ekgUM6LdIebSQSqBEsRJdT9/EDeZlh6Wwr6I9BU3lY4f7qqvGSSRACNYT1qfcNseitoQ18lTz81qOpcGwga4ggqnteQVejXXYeg22QKgTil/z7zrv@D8r6lf3QdGWukpRBwZi4aW49yHFCYNiSL3UX7THFJlHE6Z5bSSp/7m9n0PzBQ) **Explanation:** ``` s-> // Method with String as both parameter and return-type s.replaceAll( // Replace in the input-String: "(.*?)(\\w+)-(\\w+)(.*)", // This regex match "$1nao $2$3$4;$1nao $3 $2" // With this replacement, +( // which is appended with: s.matches(".*[aeiou]-.*")? // If the input-String matches this regex fully: "s$4" // Append "s$4" to the replacement : // Else: "$4")) // Append "$4" to the replacement instead ``` *Regex explanation:* ``` (.*?)(\\w+)-(\\w+)(.*) # MATCH: ( ) # Capture group 1: .* # Any amount of (optional) leading characters ? # Which are optional (to lower their priority in comparison # to the next groups) ( ) # Followed by capture group 2: \w+ # Any amount of alphanumeric characters - # Followed by a literal "-" ( ) # Followed by capture group 3: \w+ # Any amount of alphanumeric characters ( ) # Followed by capture group 4: .* # Any amount of (optional) leading characters $1nao $2$3$4;$1nao $3 $2s$4 # REPLACEMENT: $1 # Content of capture group 1 nao # Followed by a literal "nao " $2$3$4 # Followed by the contents of capture groups 2, 3, and 4 ; # Followed by a literal ";" as separator $1 # Followed by the content of capture group 1 nao # and a literal "nao " again $3 # Followed by the content of capture group 3 # Followed by a literal " " $2 # Followed by the content of capture groups 2 s # Followed by a literal "s", iff the match below is truthy $4 # Followed by the content of capture group 4 .*[aeiou]-.* # Check if the string matches this string: ^ $ # It tries to match the ENTIRE string (which is done # implicitly by the `String#matches` method) .* # Any amount of leading characters [aeiou] # Followed by a single vowel character - # Followed by a literal "-" .* # Followed by any amount of trailing characters ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) + Core utilities, ~~85~~ ~~84~~ ~~82~~ ~~75~~ ~~72~~ 71 bytes ``` p=";s/(\w*)-(\w*)/nao " sed -E "h$p\1\2/p;g;s/([aeiou])-/\1s-/$p\2 \1/" ``` [Try it online!](https://tio.run/##HY0xDsIwDEX3nMKqGAApitq1YuQUhOG3tWglmoQ4geOHNIst2@8/T5C1lHDrRjFn@7tedKvGwVOnhBfSd@rWU7C9HUwYXwf3AG8@Py/a2F60qceBbG@6UoQ3@mQmBLgVohNT3kmyJK8W6L2NOXx9YjV7l9rK@ZZhSRACBXaCqI5WbbzThMSxqtRWNTRXWYuB5siVg1QOx6vAb1DM@AM "Bash – Try It Online") --- 1 byte shorter, thanks to @user41805: Using the `p` flag in the first substitution permits one `;` to be omitted. --- Down to 72 bytes now: Added the `-E` option to sed for extended regexes, eliminating the need to escape the various parentheses. --- *Thanks to @Neil for shaving off 7 bytes, leaving 75 bytes!* Improvements: (1) Eliminating the `\<` and `\>`, which are unnecessary because of sed's greedy regex matching. (2) Appending the `s` (if needed) before reversing the order of the verb and the pronoun, which eliminates the need for adding the identifying `%` character and later deleting it. --- Input is on stdin, and output is on stdout. **How it works:** 1. The value of `p` is essentially the beginning of a sed substitute command that finds the verb-pronoun combination and replaces it with a string starting with `nao` (the command is incomplete -- it will need to filled in with the rest of the desired substitute and then a final `/`). At the very beginning of `p`, preceding the command, is a `;`, which will separate it from the previous sed command. (`p` will be used twice -- once for each output string.) 2. The sed command starts by reading one line of input (one Portuguese sentence) into sed's pattern space. (This is automatic with sed.) 3. The first sed command, `h`, copies the pattern space into the hold space, so we've saved a copy of the input string for use later to compute the 2nd output. 4. Next comes `$p\1\2/`, which expands to `;s/(\w*)-(\w*)/nao \1\2`. The command after the sed command separator (`;`) inserts the `nao` in the right place and removes the `-`. 5. The sed command `p` prints the pattern space. That's the first output string. 6. The sed command `g` copies the hold space to the pattern space. Now the pattern space contains the original input string again. 7. The next sed command, `s/([aeiou])-/\1s-/` appends an `s` to the verb if the verb ends with a vowel. 8. Next comes `$p\2 \1`, which expands to a sed command that inserts `nao`, reverses the order of the verb and the pronoun, and replaces the hyphen with a space. 9. Finally, the pattern space is printed (no command needed -- by default, sed does this automatically at the end). That's the second output string. Note that the sed command is run on each input line separately, so you can process as many sentences as you want in a single run of the program. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 47 bytes ``` (\w*?([aeiou])?)-(\w+) nao $1$3$"nao $3 $1$#2*s ``` [Try it online!](https://tio.run/##K0otycxLNPz/XyOmXMteIzoxNTO/NFbTXlMXKKCtyZWXmK@gYqhirKIEZhmDOMpGWsX//6ck6uamKpTmKpQWlOWXpAIA "Retina – Try It Online") The verb consists of some characters `\w*?` and an optional vowel `([aeiou])?`. The pronoun is just some characters `\w+` after the hyphen. `VERB-PRONOUN` gets replaced by `nao VERBPRONOUN` (`nao $1$3`), `POST_MATCH NEWLINE PRE_MATCH` (`$"`), `nao PRONOUN VERB` (`nao $3 $1`) and, if `([aeiou])?` had a match, a trailing `s` (`$#2*s`). [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 145 bytes ``` W =SPAN(&LCASE) INPUT ARB . L W . V '-' W . P REM . R L =L 'nao ' OUTPUT =L V P R V ANY('aeiou') . E RPOS(0) =E 's' OUTPUT =L P ' ' V R END ``` [Try it online!](https://tio.run/##VYuxCsIwGITn5Clu8m@HioNrh6gZhJiGtE1xrJhBsI1Q4@vH1E0O7o7jvmUOt/Dcp8QG1K0Rutioo2hlydlZm76DsAdsoTBkd6CKfs3AyktOy5lCrUDzGECcNX23Qnlx64czB6GvBY3@ESKVmZCwpmmLXYlagpY/xoCyXOakPqV0H6vJI06Ir094@y8 "SNOBOL4 (CSNOBOL4) – Try It Online") Explanation: ``` W =SPAN(&LCASE) ;* Alias for SPAN(&LCASE), which matches at least one character from &LCASE, ;* the lowercase letters, so I guess it's [a-z]+ INPUT ARB . L W . V '-' W . P REM . R ;* match the input against the following pattern: ;* ARBitrary match, save as L, the Left part of the sentence ;* SPAN(&LCASE) save as V, the verb ;* hyphen ;* SPAN(&LCASE) save as P, the pronoun ;* REMainder of the match, save as R, the Right part of the sentence L =L 'nao ' ;* concatenate 'nao ' to the end of L OUTPUT =L V P R ;* print L V P R V ANY('aeiou') . E RPOS(0) =E 's' ;* if V ends (RPOS(0)) in aeiou, add S to the end OUTPUT =L P ' ' V R ;* and output the new sentence. END ``` [Answer] # Excel, 311 Bytes ``` B2 <- Input B3 =LEN(B2) B4 nao <- Required trailing space B5 aeiou B6 <- Cell contains a single space C3 - C4 '<- Single results in empty (text formatted) cell C5 : D2 =TEXTJOIN(B6,,IF(ISERR(SEARCH(C3,D3#:C3)),D3#:C3,D4#:D5#:C5))<- Output D3 =TRIM(MID(SUBSTITUTE(B2,B6,REPT(B6,B3)),(SEQUENCE(,B3-LEN(SUBSTITUTE(B2,B6,))+1)-1)*B3+1,B3)) D4 =B4&SUBSTITUTE(D3#,C3,) D5 =D6#&IF(ISERR(SEARCH(RIGHT(D6#,1),B5)),"","s") D6 =B4&RIGHT(D3#,LEN(D3#)-D7#)&B6&LEFT(D3#,D7#-1) ``` This answer would be so much shorter if SUBSTITUTE was renamed to SUBS (Microsoft pls fix) ### Sample Image [![sample image](https://i.stack.imgur.com/KHc5D.png)](https://i.stack.imgur.com/KHc5D.png) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 37 bytes ``` e€ØẹṪ”sxṭ ṚKÇ,ṭ€“nao ” ṣÇ¥Wċ?€”-ŒpK€Y ``` [Try it online!](https://tio.run/##HY0xTgMxEEV7n2IKSvYEkcgBcgBEOSwjJdGubXZsRLpAswUdFUKkQjQIGoRWGKQUaziI9yJm4mr@/P/nzZqaZpMzTbdv8SF9hxRep@2Or1N4Vyk8LmJ/LFLSafuk0YCE4j/Hfnw5/b2bl2BX/d3bhciznL4@UtjPpAzVyThINhMr9kcq/XzGXjrr6WY/DuOQM9MKLj0BWtRL5MoR@BbYszPqAqu2rN5eGUeqNtoVS5tyQ@yQAcGSZuzUYQiNWjhHR52g1EowUAusnCHUHUkPWXp4eGWpQeg8/gM "Jelly – Try It Online") A full program that takes a list of words and prints a the output separated by newlines. [Answer] # [Japt](https://github.com/ETHproductions/japt), 41 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` 2ÆË=q-)ÊÉ?X?DÔ¸r"%v$""$&s":Dq)i"nao ":D}S ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=MsbLPXEtKcrJP1g/RNS4ciIldiQiIiQmcyI6RHEpaSJuYW8gIjpEfVM&input=ImRhLW1lIHVtIHVwdm90ZSI) Alternative, with output being list of words: # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 40 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` 2ÆË=q-)ÊÉ?X?DÔ¸r"%v$"_+'s:Dq)i"nao " ¸:D ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&header=cVM&code=MsbLPXEtKcrJP1g/RNS4ciIldiQiXysnczpEcSlpIm5hbyAiILg6RA&input=ImRhLW1lIHVtIHVwdm90ZSI) [Answer] # JavaScript (ES6), ~~81 80~~ 79 bytes Returns a single string with the two sentences separated by a `/`. ``` s=>s.replace(/(\w+)-(\w+)/,"nao $1$2$'/$`nao $2 $"+(/[aeiou]-/.test(s)?'1s':1)) ``` [Try it online!](https://tio.run/##dZLRboMwDEXf9xUWQgJUIGofJ3X7kG3SPHA3JkpYnHSfzxJDC6VrHpBiH/nkWnzjCbkyTW@LTtc0HPYD75@4NNS3WFGq0tffTVbIV@VRhxribbyLExW/y2UHcbRJ1QtSo91boUpLbFPOnpMtJ4/bLBsq3bFuqWz1Z3pII6YGfhwB9th9IReWwB2BHVsdZRmEoxRcsCCZ0CWZXxP2Mm9GHlbiGoujTHD9SVs6y5YniMO4Gq/IfKz6Wj0Kpvra4K9WJJ2Wl/lNeB6hp47RiPBsEPQuOQuF4zvY2h/Kfil0hA@0ZIp/Qgb/jAWJoGPI64bfqfRuNI3fLlR@x5IVoTJkVqKgEUyyBnQm80UrJHRTKGneREL2T8Lwl/TUIhiH60znlU7okpz2GEpjk@fe8Ac "JavaScript (Node.js) – Try It Online") ### Commented ``` s => // s = input string s.replace( // replace in s /(\w+)-(\w+)/, // (verb)-(pronoun) with "nao $1$2$'" + // 1st sentence: // implicit left context // + "nao verbPronoun" // + explicit right context ($') "/" + // append our separator "$`nao $2 $" + ( // 2nd sentence: // explicit left context ($`) // + "nao pronoun verb", // where 'verb' is built as follows: /[aeiou]-/.test(s) ? // if there's a vowel before the '-' in s, // i.e. if the verb ends with a vowel: '1s' // append '1s' (which gives "$1s") : // else: 1 // just append '1' (which gives "$1") ) // + implicit right context ) // end of replace() ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~94 87 83~~ 81 bytes ``` ->s{['\1\2','\2 \1'+"#{s=~/[aeiou]-/&&?s}"].map{|r|s.sub /(\w+)-(\w+)/,'nao '+r}} ``` [Try it online!](https://tio.run/##NY7RasMwDEV/RXhQbyRuaN/bfkicByVVWWCxXcvaOpLs11PXsBchLudcKUr/u91Omznz3Gp7sEdda3sEe9CVepv59Ne0SKOXzjS73YVX1e0nDPMSF96z9NC825/qw5TZ1NqhB13Fdd2CJIZWMY1wFwIM6D6RTSKQCVg4eVWrK5qpBBK@faKcDN6lEjpfPOKEDAiBHGPMwGvJnTRBj4miKdaY62DIpUVFGCIVFjmz@Doa6AshCv7//1hu7aNbtyc "Ruby – Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), ~~121~~ ~~118~~ 116 bytes ``` s->((x=(r=match(r"(.*)\b(\w+)-(\w+)(.*)",s))[1]*"nao ")*(y=r[2])*r[3]*r[4],x*r[3]*" "*y*"s"^(y[end]∈"aeiou")*r[4]) ``` [Try it online!](https://tio.run/##fVLLboMwELzzFSufbAqV0vZK1Y/ojVBpA05DFAz1o03@IN/ZH6H24oRQqeVg2TPj2fGye3docXUct8Vo8mfOjwXXRYe23nHN@H0q1hu@/roTOa0BYJkRolxVKVPYAxMpPxW6fKhEqsvHyi9PVXac9gxYekqZYW/8VErVVN/nM0PZ9o4JEooxsdJYAwXwBDgzsoUPJwEHVDs0uZXgOjDO2J5lN3yoHDVLyUJhr0azRIgsFGow7@iiGz57K8k8XGnwF0yox5rJJOLRpe6VJSPVU1H/FC9DGKQyqK@mJPtHdalBOvOHLJYMJ/9E2cEGrdR5zD7DwYuoKf6S8B0h7uLW@pZA7RtDr0CotZxiE0HZA3nLzVRI7GJIIi8R0fiSGH7eIA8I2uG1FZFbUixGi6SZOXIUiTOteodX35Fk22uw0CqguUnAfy9hC1tu/VAKKAqwfhoTP27jDw "Julia 1.0 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-p`, ~~67~~ 58 bytes ``` s%(\w*)-(\w+)%"nao $1$2$' $`nao $2 $1"=~s/[aeiou]\K$/s/r%e ``` [Try it online!](https://tio.run/##K0gtyjH9/79YVSOmXEtTF0hqa6oq5SXmK6gYqhipqHOpJIA5RkC@km1dsX50YmpmfmlsjLeKfrF@kWrq//8pibq5qQqluQqlBWX5Jan/8gtKMvPziv/r@prqGRga/NctAAA "Perl 5 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 42 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` 2Ær7î"%w+-" _X?Zq- Ô¸r"%v$"_+'s:Zr-)i"nao ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=MsZyN%2b4iJXcrLSIgX1g/WnEtINS4ciIldiQiXysnczpaci0paSJuYW8g&input=ImRhLW1lIHVtIHVwdm90ZSIKLVI) [Answer] # [Python 3](https://docs.python.org/3/), 111 bytes ``` (*a,v),(p,*b)=map(str.split,input().split('-')) for c in[v+p,p+' '+v+'s'*(v[-1]in'aeiou')]:print(*a,"nao",c,*b) ``` [Try it online!](https://tio.run/##Jc1NCsMgEEDhfU8h2YzjT6F0V@hJQhZWLB1odNBRyOktocu3@R4f8in5Pqc2wQ10mp154XMPrJvUa@MviaPMXTT@S4MHxMu7VBUV5XVYdmxBgR0WGhg9Vn/bKENIVDrg9uBKWU5/yaEsLp6HOalJUbE3CX5PKqhYU/0B "Python 3 – Try It Online") Method of taking input thanks to @ovs. I felt that this is a big enough change to warrant its own answer, however. [Answer] # [R](https://www.r-project.org/), 111 bytes ``` cat(sub(r<-"(\\w+)-(\\w+)","nao \\1\\2",s<-scan(,"")),1,sub(r,paste0("nao \\2 \\1","s"[grep("[aeiou]-",s)]),s)) ``` [Try it online!](https://tio.run/##LcsxDoMwDIXhq0SebNWRCjM3wQwuRFUHSBQn7fFDWrq8t/xfbm3VglYfmCcPKPK5kb8OGA6NTmQQGYFt8rbqgQxAxAP/DCe1Eu74L8dv3Z3B/MwhIcwaXrEuvnNaqA@1Tf0eXN1dTe9YQjsB "R – Try It Online") I am pretty bad at regexing, so there is probably inspiration for something better to be found in other answers. Note that `scan(,"")` splits words on spaces, making it easier to manipulate the strings. In the output, the two sentences are separated by a `1`. More readable : ``` r <- "(\\w+)-(\\w+)" # regex to match the word with a dash s <- scan(, "") # stdin cat(sub(r, "nao \\1\\2", s), 1, sub(r, paste0("nao \\2 \\1", "s"[grep("[aeiou]-", s)]) # add an s or NULL, depending on whether the letter before the dash is a vowel or not , s)) ``` [Answer] # [sed 4.2.2](https://www.gnu.org/software/sed/) `-E`, 72 bytes ``` h;s/(\w*)-(\w*)/nao \1\2/p;g;s/([aeiou])-/\1s-/;s/(\w*)-(\w*)/nao \2 \1/ ``` Port of [Mitchell Spector](https://codegolf.stackexchange.com/users/59825/mitchell-spector)'s [Bash answer](https://codegolf.stackexchange.com/a/200490/89298). [Try it online!](https://tio.run/##bYsxDoMwDAC/4hEqWRZZM/MK0sESVslAnMqJ@ntMYWa55e5MVvctGg3p9xrxJhVWSFMKVOPnUgtL1v4ekdJkSE91@A/kbpLh2wW4ctnYsAn0Haxb00Nry1rMcT4B "sed 4.2.2 – Try It Online") [Answer] # [PHP](https://php.net/), 159 bytes ``` for($t=2;$t--;)echo preg_replace_callback('#(\w+?)([aeiou]?)-(\w+)#',fn($m)=>'nao '.$m[$t*2+1].($t?' ':'').$m[2-$t].$m[3-$t].($t&&$m[3-$t]?'s':''),$argn),"\n"; ``` [Try it online!](https://tio.run/##NY3LTsMwEEX3@YpRa9UxjSsRdoSSHT/RRtXUnTYRiW38gL8n2JbYzOPOvWfsaNe33qZ6N65m4dh2LEjZCVKjAevocXFkZ1R0UTjPV1SfNd/W5599L@oT0mTi0AuZBbHlzV3XbBHHd67RAD@w5cTCU7t/Hg6J3XPgr5yLLLeShSEPL2VI193uf@u5L76GoXto0WzOetOtq6cJviIBWtQjehkI4gI@@mCqG8qlrNF@m0CVMjoUSZuSIR/QA4Il7dFVuSUaLXDFQC6hqilhQCVYiSEoR8mHPvkwv7I0I7iIv8aGyWi/yo8/ "PHP – Try It Online") The array numbering is messy, there's more juice to be squeezed there. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes ``` ≔⊟Φ⪪θ №ι-η≔⪪η-ζE⟦⪫ζω⁺⪫⮌ζ ×s№aeiou§§ζ⁰±¹⟧⪫⪪θη⁺nao ι ``` [Try it online!](https://tio.run/##PU5Li8IwEL77K4acJpCCnj2JsLALSlFv4iHoYAfSpDZJlf75OD66cxnme865sf05WFfKKka@eqxDhz/sEvW47xwnvBlQoLSBdcg@IctZKa0FaPRy9nV9pM2HMzAKU/cs8o3t8PgX2ONo4C5U7XLEN7CjgfpIOOqp4cAtRVRRTWXKEocs5yr9@gs9cNoSNhfDlq42ES70a04G3rn/bzdTnfI2gKTwS7Ys5WKrliC3kLshJJqVanBP "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⊟Φ⪪θ №ι-η ``` Split the input on spaces and extract the word that contains a `-`. ``` ≔⪪η-ζ ``` Split that word on its `-`. ``` ⪫ζω ``` Join the parts together. ``` ⁺⪫⮌ζ ×s№aeiou§§ζ⁰±¹ ``` Reverse the parts and join them with a space, then append as many `s`s as there are vowels in the last letter of the first word. ``` E⟦...⟧⪫⪪θη⁺nao ι ``` Prefix `nao` to each of the two above values and substitute them for the original word. [Answer] # Pure [Bash](https://www.gnu.org/software/bash/), ~~118~~ 117 bytes ``` a=${1%-*} b=${1#*-} v=${a##* } u=${v#${v%[aeiou]}} h=${a%$v}nao p=${b%% *} t=${b#$p} echo $h $v$p$t,$h $p $v${u:+s}$t ``` [Try it online!](https://tio.run/##HY1NbsQgDEb3PoU1wCZtFrMdqSepunASS0SaAMVARxpx9tRkgfw@/zwWEn/@@f3JmJk2fMEWQbjgzb5uJ33Z993NU4dlkJnmDk2JjJmwQ1VsRp/7Jt5j/ekd/Bg723qgCEnD4hyqoAw0NnXg1Ue0Hm2zyZbPQWmEd318SLfl3GLgU3jH38pIiYInmQtjPVCqlAgbzccVa2qxMKwxlKsV4nXDUkiQMHEQyjCK2vjAhQpnVcGuGlxVdp0Rrpl1j0T3aHyV@EmYK/0D "Bash – Try It Online") I decided to see what I could do with pure bash (no Unix utilities), and this is what I came up with. It can probably be golfed some more. Input is passed as an argument. The output is a comma-separated string containing the two desired results. [Answer] ## Batch, 265 bytes ``` @echo off set m= set n= for %%w in (%*) do set w=%%w&call:w echo%m% echo%n% exit/b :w if %w:-=%==%w% set m=%m% %w%&set n=%n% %w%&exit/b set m=%m% nao %w:-=% set v=%w:-=^&rem % set n=%n% nao %w:*-=% %v% for %%v in (a e i o u)do if %n:~-1%==%%v set n=%n%s ``` Takes input as command-line parameters. Explanation: The main work is done by the `:w` subroutine, which receives each word in turn passed in a variable so that substitutions can be performed on it. The first substitution is simply deleting the `-`; if this doesn't change the word then we're not interested in the word and we just concatenate it to the outputs. Otherwise, for the first output, we just add `nao` and the substituted word. For the second output things get a little more complicated. Although we can substitute all characters up to and including the `-` with the empty string to give us the pronoun, the verb is a bit tricker. Fortunately due to a quirk of Batch processing we effectively get to `exec` the result of the substitution, turning the pronoun into a comment. (This behaviour also eats the leading space in the output when we `echo` it.) It then remains to see whether the verb ended in a vowel and if so suffix an `s`. Example: ``` set m= nao dame `m` becomes ` nao dame` set v=da^&rem me `v` becomes `da&rem me` set n= nao me da&rem me `n` becomes ` nao me da`, as the `rem me` is now a comment. ``` [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 62 bytes ``` "-"/~2/(:f;:e;" ":s/.)" nao ":w\f\s\e++++\s*\+p~w\f e++++s\++p ``` *Boy* do I hate string parsing. This is nowhere near optimised and can very easily be brought down below 50 bytes, I just don't have the bother right now. Ugh. TLDR of the process Split along the hyphen. Remove the next two letters on the right side. Split the left half by spaces and duplicate it. Shove the "nao" and the two letters where they belong and print. [Try it online!](https://tio.run/##HYixDoQgEAV/ZbOVSpTkSvyVbYhZ1OQU7h7Ezl9H4lQzs8ZvwPLfU64M3elXlHzy5@YxZqVyEApy5Moj2/tjOxdmpzMTO9ipZzp9bH5JEIiahmAQk@526G2IManWBw "GolfScript – Try It Online") [Answer] ## vi, 48 bytes ``` yyPf-xbinao ␛bj.:s/\([aeiou]\)-/\1s-/e␍f-r ldbwP ``` `␍` means the Enter key and `␛` means the Escape key. Explanation: ``` yyP ``` Duplicate the input line. ``` f-x ``` Delete the `-` on the first line. ``` binao ␛bj. ``` Insert the `nao` on both lines. ``` :s/\([aeiou]\)-/\1s-/e␍ ``` Append an `s` to the vowel if necessary. ``` f-r l ``` Change the `-` to a space. ``` dbwP ``` Swap the verb and pronoun. [Answer] # T-SQL, 304 bytes I added some linebreaks to make it readable ``` SELECT stuff(replace(@,d+w,iif('eioua'like'%'+right(w,1)+'%',w,p)),z,0,f), stuff(replace(@,d+w,iif(substring(@,q-2,1)=p,'',p)),z,0,f+w+y)FROM( SELECT substring(@,q,charindex(y,@+y,q-1)-q)w,len(@) -charindex(y,s,charindex(d,s)+1)+2z,* FROM(SELECT-~charindex('-', @)q,'nao 'f,' 'y,'-'d,'s'p,reverse(' '+@)S)Q)L ``` **[Try it online](https://data.stackexchange.com/stackoverflow/query/1205983/help-me-write-portuguese)**(ungolfed) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~41 38 37~~ 36 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṚKµe€ØẹṪ”sxṭÑ “nao ”; ṣ”-⁹Ŀ¹Ḋ?¥þ2K€Y ``` A full program accepting a single argument, a list of words, which prints to STDOUT. **[Try it online!](https://tio.run/##y0rNyan8///hzlneh7amPmpac3jGw107H@5c9ahhbnHFw51rD0/ketQwJy8xXwEoYs31cOdiIK37qHHnkf2Hdj7c0WV/aOnhfUbeQJ2R////j1bPLC7JV9dRUE8uLS5J1M1NBbETwQJFqUXqsQA "Jelly – Try It Online")** ### How? ``` ṚKµe€ØẹṪ”sxṭÑ - Link 1: list of lists of characters, Parts Ṛ - reverse K - join with space characters, call this R µ - start a new monadic chain Øẹ - lower-case vowels € - for each character, C, in R: e - (C) exists in (vowels)? Ṫ - tail (i.e. is the last character a vowel?) ”s - 's' character x - times (i.e. X = ['s'] or []) ṭ - tack (X) to (R) Ñ - call the next link (Link 2) as a monad “nao ”; - Link 2: list, V “nao ” - list of characters "nao " ; - concatenate ("nao " with V) ṣ”-⁹Ŀ¹Ḋ?¥þ2K€Y - Main Link: list of lists of characters, words 2 - literal two þ - outer-product (W in words)*(N in implicit range of 2 = [1,2]) with: ¥ - last two links as a dyad - i.e. f(W, N): ṣ - split (W) at any: ”- - hyphen character ? - if... Ḋ - ...condition: dequeue (empty is falsey) Ŀ - ...then: call Link at line number: ⁹ - chain's right argument (N) ¹ - ...else: identity - do nothing K€ - join each with space characters Y - join with newline characters - implicit print ``` ]
[Question] [ According to <http://en.cppreference.com/w/cpp/language/integer_literal>, integer literals consist of a decimal/hex/octal/binary literal and a optional integer suffix, that is obviously completely unnecessary, wastes precious bytes and is not used in this challenge. A decimal literal is `a non-zero decimal digit (1, 2, 3, 4, 5, 6, 7, 8, 9), followed by zero or more decimal digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)`. A octal literal is `the digit zero (0) followed by zero or more octal digits (0, 1, 2, 3, 4, 5, 6, 7)`. A hexadecimal literal is `the character sequence 0x or the character sequence 0X followed by one or more hexadecimal digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, A, b, B, c, C, d, D, e, E, f, F)` (note the case-insensitivity of `abcdefx`). A binary literal is `the character sequence 0b or the character sequence 0B followed by one or more binary digits (0, 1)`. Additionally, there may optionally be some `'`s as a digit separator. They have no meaning and can be ignored. ## Input A string that represents a C++14 integer literal or an array of its charcodes. ## Output The number represented by the input string in base 10, with an optional trailing newline. The correct output never will exceed 2\*10^9 ## Winning criteria [The GCC contributors need over 500 lines of code to do this,](https://github.com/gcc-mirror/gcc/blob/master/libcpp/expr.c#L506-L1011) therefore our code must be as short as possible! ## Test cases: ``` 0 -> 0 1 -> 1 12345 -> 12345 12345'67890 -> 1234567890 0xFF -> 255 0XfF -> 255 0xAbCdEf -> 11259375 0xa'bCd'eF -> 11259375 0b1111'0000 -> 240 0b0 -> 0 0B1'0 -> 2 0b1 -> 1 00 -> 0 01 -> 1 012345 -> 5349 0'123'4'5 -> 5349 ``` [Answer] # x86 (32-bit) machine code, ~~59~~ 57 bytes This function takes `esi` as a pointer to a null-terminated string and returns the value in `edx`. (Listing below is GAS input in AT&T syntax.) ``` .globl parse_cxx14_int .text parse_cxx14_int: push $10 pop %ecx # store 10 as base xor %eax,%eax # initialize high bits of digit reader cdq # also initialize result accumulator edx to 0 lodsb # fetch first character cmp $'0', %al jne .Lparseloop2 lodsb and $~32, %al # uppercase letters (and as side effect, # digits are translated to N+16) jz .Lend # "0" string cmp $'B', %al # after '0' have either digit, apostrophe, # 'b'/'B' or 'x'/'X' je .Lbin jg .Lhex dec %ecx dec %ecx # update base to 8 jmp .Lprocessdigit # process octal digit that we just read (or # skip ' if that is what we just read) .Lbin: sub $14, %ecx # with below will update base to 2 .Lhex: add $6, %ecx # update base to 16 .Lparseloop: lodsb # fetch next character .Lparseloop2: and $~32, %al # uppercase letters (and as side effect, # digits are translated to N+16) jz .Lend .Lprocessdigit: cmp $7, %al # skip ' (ASCII 39 which would have been # translated to 7 above) je .Lparseloop test $64, %al # distinguish letters and numbers jz .Lnum sub $39, %al # with below will subtract 55 so e.g. 'A'==65 # will become 10 .Lnum: sub $16, %al # translate digits to numerical value imul %ecx, %edx # movzbl %al, %eax add %eax, %edx # accum = accum * base + newdigit jmp .Lparseloop .Lend: ret ``` And a disassembly with byte counts - in Intel format this time, in case you prefer that one. ``` Disassembly of section .text: 00000000 <parse_cxx14_int>: 0: 6a 0a push 0xa 2: 59 pop ecx 3: 31 c0 xor eax,eax 5: 99 cdq 6: ac lods al,BYTE PTR ds:[esi] 7: 3c 30 cmp al,0x30 9: 75 16 jne 21 <parse_cxx14_int+0x21> b: ac lods al,BYTE PTR ds:[esi] c: 24 df and al,0xdf e: 74 28 je 38 <parse_cxx14_int+0x38> 10: 3c 42 cmp al,0x42 12: 74 06 je 1a <parse_cxx14_int+0x1a> 14: 7f 07 jg 1d <parse_cxx14_int+0x1d> 16: 49 dec ecx 17: 49 dec ecx 18: eb 0b jmp 25 <parse_cxx14_int+0x25> 1a: 83 e9 0e sub ecx,0xe 1d: 83 c1 06 add ecx,0x6 20: ac lods al,BYTE PTR ds:[esi] 21: 24 df and al,0xdf 23: 74 13 je 38 <parse_cxx14_int+0x38> 25: 3c 07 cmp al,0x7 27: 74 f7 je 20 <parse_cxx14_int+0x20> 29: a8 40 test al,0x40 2b: 74 02 je 2f <parse_cxx14_int+0x2f> 2d: 2c 27 sub al,0x27 2f: 2c 10 sub al,0x10 31: 0f af d1 imul edx,ecx 34: 01 c2 add edx,eax 36: eb e8 jmp 20 <parse_cxx14_int+0x20> 38: c3 ret ``` And in case you want to try it, here is the C++ test driver code that I linked with it (including the calling convention specification in GCC asm syntax): ``` #include <cstdio> #include <string> #include <iostream> inline int parse_cxx14_int_wrap(const char *s) { int result; const char* end; __asm__("call parse_cxx14_int" : "=d"(result), "=S"(end) : "1"(s) : "eax", "ecx", "cc"); return result; } int main(int argc, char* argv[]) { std::string s; while (std::getline(std::cin, s)) std::printf("%-16s -> %d\n", s.c_str(), parse_cxx14_int_wrap(s.c_str())); return 0; } ``` --- -1 byte due to comment by Peter Cordes -1 byte from updating to use two decrements to change 10 to 8 [Answer] # [JavaScript (Babel Node)](https://babeljs.io/), 26 bytes lol x2 ``` _=>eval(_.split`'`.join``) ``` [Try it online!](https://tio.run/##ndJBD4IgGAbge7/CeUEPKqBmHmyrVr@hm4Ji0zFp2Zr/3qiDLYHc@k4cePa@46MlD9KXt@Z69yihjHudqNhYZ2OebdmDcCf3@ytv7gUo/FY0XVG4Yym6XnDmc3FxasdGtuta@gkCy9u@Dmg1RziMYj38oNcdLQTrZJPCOf@G7ytzDYfTyVB30jhWQuG5/osNO3qojrWGfroiHKdhorEESAyYGrxsKZIDoBzjG@FIfRwKTaucmIr2MmhhkVhTcDFJ@TLQ2O5XPbSM1CTz75xQHEap4oCEIAIa@uXGJw "JavaScript (Babel Node) – Try It Online") [Answer] # C++ (gcc), ~~141~~ ~~138~~ ~~134~~ 120 bytes This is a function that takes an array of characters (specified as a pair of pointers to the start and end - using the pair of iterators idiom) and returns the number. Note that the function mutates the input array. (This does rely on the behavior of gcc/libstdc++ that `#include<cstdlib>` also places the functions in global scope. For strictly standard compliant code, replace with `#include<stdlib.h>` for a cost of one more character.) Brief description: The code first uses `std::remove` to filter out `'` characters (ASCII 39). Then, `strtol` with a base of 0 will already handle the decimal, octal, and hexadecimal cases, so the only other case to check for is a leading `0b` or `0B` and if so, set the base for `strtol` to 2 and start parsing after the leading 2 characters. ``` #import<algorithm> #import<cstdlib> int f(char*s,char*e){e=s[*std::remove(s,e,39)=1]&31^2?s:s+2;return strtol(e,0,e-s);} ``` [Try it online.](https://tio.run/##VU9/b4IwEP2/n6JxUairBtC5KeqyLfMzLHHOQCnQBApp64/E@NndFTRzl/T67vXu3Sur60HG2OXyIMq6UmYeFVmlhMnLJbpRTJukEPESCWlw6rI8Un1Nm4uTE1/odR86ZjPFy2rPXU05HU3Jwt/0Rv5P8Kpn@jEIFTc7JbE2ylSFy6lH@UCT8AyLJSt2CcdzEBHVMLeL/yglZHbPiAo4HpVXN9uDimq3Wd/2Yk3wCV@3pW6vr4cxz4R0CcW24DJxCQnxuZkvI3ixIFIZo7j5k8X79QZkEIb4px021CEXBcft1oybQkjeFkxICgZI02WjhjGTup3uwJ9oPFjibvItO9AzZFvQtKZuXwBTzdjVuheiM7r4yA9G46c2O5Pnl6mHvONqhbyvFNLxLf5IPtN7EDmAHA6PsQ/heBCA4bxDYVlkCcitsufA7YwdQIEP7C8) --- Saved 3 bytes due to suggestion by ceilingcat and some more golfing that followed. Saved 4 bytes due to suggestions by grastropner. -2 bytes by Lucas -12 bytes by l4m2 [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 bytes ``` OxUr"' ``` --- ``` OxUr"' Full Program. Implicit Input U Ur"' Remove ' from U Ox Eval as javascript ``` [Try it online!](https://tio.run/##y0osKPn/378itEhJ/f//aCVDJR0uJUMjYxNTOEPdzNzC0gDENahwcwPTEWkQusIxyTnFNQ3CTlQHctRTITJJhkCgbgAEEC6EcgIKQaXBFIQDYcMtNVAHMtVN1E2VYhV0c4MA "Japt – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 32 bytes ``` lambda a:eval(a.replace("'","")) ``` [Try it online!](https://tio.run/##hZHNasMwDMfP9VMIX@xAGuwkXpdCCttYnmCHHQbDXh0aSDPjuGv39JnSXutMYCP7/9MHkvsNh@8hn9r6Y@r10ew16K390T3Xmbeu11@WU0ZTSpNkOh@63sKbP9ktWekUDNRw1I6PwWd4OpeC1@fPbnCnwJNsdH0XOF3vMJasvA2It1yj73w3BMAfzIGZxtH66xPqGlDhJpkk3Lf1br4lkXlRqrg@qzeGPWweKxFjriIRl6aJF8uVIuK9/Y@4PJmX/WsbaUjmqio2M6YZcsw2y5iRaEyg3atXYs9GLAwI9WcMj3c8V1gcsBCwnF8uL0hENnTTVVFWRDBkWMlUFPkD "Python 2 – Try It Online") lol (needs Python 2 because Python 3 changed octal literals to `0o(...)`). [Answer] # Perl 5 (-p), 14 bytes ``` y/'/_/;$_=eval ``` [TIO](https://tio.run/##K0gtyjH9/79SX10/Xt9aJd42tSwx5/9/Qy5DI2MTUwipbmZuYWnAZVDh5sZlEJEGJCock5xTXNOAjER1IEs9FSiWZAgE6gZAAGQDsROQAxLlAgkASYiBBupAWt1E3fRffkFJZn5e8X/dnAIA) [Answer] # [R](https://www.r-project.org/), ~~79~~ ~~71~~ 69 bytes ``` `+`=strtoi;s=gsub("'","",scan(,""));na.omit(c(+s,sub("..",0,s)+2))[1] ``` [Try it online!](https://tio.run/##K/r/P0E7wba4pKgkP9O62Da9uDRJQ0ldSUdJSac4OTFPA8jQ1LTOS9TLz80s0UjW0C7WASvR01PSMdAp1tQ20tSMNoz9b5BkaGD4HwA "R – Try It Online") `strtoi` does everything except for the base 2 conversions and ignoring the `'`, so there's quite a lot of bytes just to fix those things. *Thanks to [Aaron Hayman](https://codegolf.stackexchange.com/users/85453/aaron-hayman) for -6 bytes, and inspiring -4 more bytes (and counting!)* [Verify all test cases (old version)](https://tio.run/##NYzBCsIwEETv@YxcNgtRNrW1inqwYr/Ba6KNFKRCt0IO/nvcUpzD7NuBmTFnPj35E4wGbbW2fPeDEUA89LF7cWd6Xg/epOOKp3F694YR7R/nHoVvs1TRFmgTZqdcsSmrxWFb7/akKLWtolsUS@dweVyjgAch6CQLTgQkUtQIzImaH/FljEAulFDlHw) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ 14 bytes Saved 2 bytes thanks to *Grimy* ``` ''KlÐïK>i8ö}.E ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fXd075/CEw@u97TItDm@r1XP9/9@gIlE9yTlFPdUNAA "05AB1E – Try It Online") or as a [Test Suite](https://tio.run/##yy9OTMpM/V/jouekpKBrp6B0aHXxua3/1dW9cw5POLze2y7T4vC2Wj3X/7WPGmYd3uF1aPd/Qy5DI2MTUwipbmZuYWnAZVDh5sZlEJEGJCock5xTXNOAjER1IEs9FSiWZAgE6gZAAGQDsROQAxLlAgkASYiBBupAWt1E3RQA) **Explanation** ``` ''K # remove "'" from input l # and convert to lower-case Ð # triplicate ï # convert one copy to integer K # and remove it from the second copy >i } # if the result is 0 8ö # convert from base-8 to base-10 .E # eval ``` [Answer] # Excel, 115 bytes ``` =DECIMAL(SUBSTITUTE(REPLACE(A1,2,1,IFERROR(VALUE(MID(A1,2,1)),)),"'",),VLOOKUP(A1,{"0",8;"0B",2;"0X",16;"1",10},2)) ``` Input from A1, output to wherever you put this formula. Array formula, so use `Ctrl`+`Shift`+`Enter` to enter it. I added a couple test cases you can see in the image - some early attempts handled all given test cases correctly but got rows 16 and/or 17 wrong. [![enter image description here](https://i.stack.imgur.com/h7QwM.png)](https://i.stack.imgur.com/h7QwM.png) [Answer] # x86-64 machine code, 44 bytes (The same machine code works in 32-bit mode as well.) [@Daniel Schepler's answer](https://codegolf.stackexchange.com/questions/185642/parse-a-c14-integer-literal/185698#185698) was a starting point for this, but this has at least one new algorithmic idea (not just better golfing of the same idea): **The ASCII codes for `'B'` (`1000010`) and `'X'` (`1011000`) give 16 and 2 after masking with `0b0010010`**. So after excluding decimal (non-zero leading digit) and octal (char after `'0'` is less than `'B'`), we can just set base = `c & 0b0010010` and jump into the digit loop. Callable with x86-64 System V as `unsigned __int128 parse_cxx14_int(int dummy, const char*rsi);` Extract the EDX return value from the high half of the `unsigned __int128` result with `tmp>>64`. ``` .globl parse_cxx14_int ## Input: pointer to 0-terminated string in RSI ## output: integer in EDX ## clobbers: RAX, RCX (base), RSI (points to terminator on return) parse_cxx14_int: xor %eax,%eax # initialize high bits of digit reader cdq # also initialize result accumulator edx to 0 lea 10(%rax), %ecx # base 10 default lodsb # fetch first character cmp $'0', %al jne .Lentry2 # leading zero. Legal 2nd characters are b/B (base 2), x/X (base 16) # Or NUL terminator = 0 in base 10 # or any digit or ' separator (octal). These have ASCII codes below the alphabetic ranges lodsb mov $8, %cl # after '0' have either digit, apostrophe, or terminator, cmp $'B', %al # or 'b'/'B' or 'x'/'X' (set a new base) jb .Lentry2 # enter the parse loop with base=8 and an already-loaded character # else hex or binary. The bit patterns for those letters are very convenient and $0b0010010, %al # b/B -> 2, x/X -> 16 xchg %eax, %ecx jmp .Lentry .Lprocessdigit: sub $'0' & (~32), %al jb .Lentry # chars below '0' are treated as a separator, including ' cmp $10, %al jb .Lnum add $('0'&~32) - 'A' + 10, %al # digit value = c-'A' + 10. we have al = c - '0'&~32. # c = al + '0'&~32. val = m+'0'&~32 - 'A' + 10 .Lnum: imul %ecx, %edx add %eax, %edx # accum = accum * base + newdigit .Lentry: lodsb # fetch next character .Lentry2: and $~32, %al # uppercase letters (and as side effect, # digits are translated to N+16) jnz .Lprocessdigit # space also counts as a terminator .Lend: ret ``` The changed blocks vs. Daniel's version are (mostly) indented less than other instruction. Also the main loop has its conditional branch at the bottom. This turned out to be a neutral change because neither path could fall into the top of it, and the `dec ecx / loop .Lentry` idea for entering the loop turned out not to be a win after handling octal differently. But it has fewer instructions inside the loop with the loop in idiomatic form do{}while structure, so I kept it. Daniel's C++ test harness works unchanged in 64-bit mode with this code, which uses the same calling convention as his 32-bit answer. ``` g++ -Og parse-cxx14.cpp parse-cxx14.s && ./a.out < tests | diff -u -w - tests.good ``` Disassembly, including the machine code bytes that are the actual answer ``` 0000000000000000 <parse_cxx14_int>: 0: 31 c0 xor %eax,%eax 2: 99 cltd 3: 8d 48 0a lea 0xa(%rax),%ecx 6: ac lods %ds:(%rsi),%al 7: 3c 30 cmp $0x30,%al 9: 75 1c jne 27 <parse_cxx14_int+0x27> b: ac lods %ds:(%rsi),%al c: b1 08 mov $0x8,%cl e: 3c 42 cmp $0x42,%al 10: 72 15 jb 27 <parse_cxx14_int+0x27> 12: 24 12 and $0x12,%al 14: 91 xchg %eax,%ecx 15: eb 0f jmp 26 <parse_cxx14_int+0x26> 17: 2c 10 sub $0x10,%al 19: 72 0b jb 26 <parse_cxx14_int+0x26> 1b: 3c 0a cmp $0xa,%al 1d: 72 02 jb 21 <parse_cxx14_int+0x21> 1f: 04 d9 add $0xd9,%al 21: 0f af d1 imul %ecx,%edx 24: 01 c2 add %eax,%edx 26: ac lods %ds:(%rsi),%al 27: 24 df and $0xdf,%al 29: 75 ec jne 17 <parse_cxx14_int+0x17> 2b: c3 retq ``` Other changes from Daniel's version include saving the `sub $16, %al` from inside the digit-loop, by using more `sub` instead of `test` as part of detecting separators, and digits vs. alphabetic characters. Unlike Daniel's *every* character below `'0'` is treated as a separator, not just `'\''`. (Except `' '`: `and $~32, %al` / `jnz` in both our loops treats space as a terminator, which is possibly convenient for testing with an integer at the start of a line.) Every operation that modifies `%al` inside the loop has a branch consuming flags set by the result, and each branch goes (or falls through) to a different location. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 96 bytes ``` T`'L`_l \B : ^ a; a;0:x: g; a;0:b: 2; a;0: 8; [a-g] 1$& T`l`d +`;(\d+):(\d+) ;$.($`*$1*_$2* .+; ``` [Try it online!](https://tio.run/##JYw9D4IwEIb393dUixBJi6DYTmLExdHBRJSW8BET4mAc@Pf1sJe75557h/t039fbSrcIzsZdDb@YekRVQOEJq6mFmhQGb41C4g25xt2uhwckW@JqRtMiMjqo2mil/oRmccBMyGRYsyREHGk4JyGTTZp58u0u3wuIqSwhbj1hOjTH9tSTWE7GO8oaScUFFTlNQcecYg6I/qHgtHnKsx8 "Retina – Try It Online") Link includes test suite. Explanation: ``` T`'L`_l ``` Delete `'`s and convert everything to lower case. ``` \B : ``` Separate the digits, as any hex digits need to be converted into decimal. ``` ^ a; a;0:x: g; a;0:b: 2; a;0: 8; ``` Identify the base of the number. ``` [a-g] 1$& T`l`d ``` Convert the characters `a-g` into numbers `10-16`. ``` +`;(\d+):(\d+) ;$.($`*$1*_$2* ``` Perform base conversion on the list of digits. `$.($`*$1*_*$2*` is short for `$.($`*$1*_*$2*_)` which multiplies `$`` and `$1` together and adds `$2`. (`$`` is the part of the string before the `;` i.e. the base.) ``` .+; ``` Delete the base. [Answer] # [J](http://jsoftware.com/), 48 bytes ``` cut@'0x 16b +0b 2b +0 8b0 '''do@rplc~'+',tolower ``` [Try it online!](https://tio.run/##JYxBC4JAEIXv@ysGL5O4yKypmWBYkad@QOfVXSKEDbGyQ/31bcwH8703M/BuvnOAtopRwqckKMm3j7FGmkDlGiLSkMwGhSZAxM7Vw71vvxihHF3vXmbwoTDt1a12MkZgVYAyUBCUtQXzNMM7BODOcwNzvVBCJes0W4j5ptiSoKlpBF0sY9rrY3eyHEgTf7RiIdE/8xx4ma@CyVi6CNkxxUyE/gc) Eval after string substitution. ``` 0XfF -> +16bff -> 255 0xa'bCd'eF -> +16babcdef -> 11259375 0B1'0 -> +2b10 -> 2 0 -> 8b0 -> 0 01 -> 8b01 -> 1 0'123'4'5 -> 8b012345 -> 5349 ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 29 bytes ``` {+lc S/^0)>\d/0o/}o{S:g/\'//} ``` [Try it online!](https://tio.run/##hZGxCsIwGIRn8xSZjEU0f9pGrWBBxb6Ai2AVrG1EqEbaQaX02WOiaxNvyHJfuOO/R1GVE3V7477AC9UMyzPe0iN4cZpTkLSVzXZ@oSmhtFVCVri83os6jsdPWeU1blCvPr2xGIz3cPBQqwB3axSbFxBz@gwxPwi53TfujyGT6SwCG/M1EbySxB7mc45gJ/4Rr2W2zjfCUoj5PAqmBjsRzZEicWMZ0yKg1ZUX6s4ZOA8IK/3d3tgkOA8M4B4ImHsgsCz083kQRgiIZkhIuBX5AA "Perl 6 – Try It Online") Perl 6 requires an explicit `0o` prefix for octal and doesn't support uppercase prefixes like `0X`. ### Explanation ``` {S:g/\'//} # remove apostrophes { }o # combine with function S/^0)>\d/0o/ # 0o prefix for octal lc # lowercase + # convert to number ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~29~~ ~~21~~ 20 bytes ``` @(x)str2num(x(x>39)) ``` [Try it online!](https://tio.run/##y08uSSxL/Z@mYKugp6f330GjQrO4pMgorzRXo0Kjws7YUlPzf5qGkkGFemKiqZLmfwA "Octave – Try It Online") -8 bytes thanks to @TomCarpenter [Answer] # Bash, 33 bytes ``` x=${1//\'};echo $[${x/#0[Bb]/2#}] ``` [TIO](https://tio.run/##JYzNCsIwEITveYqFBlZPSWrrD8WDFfsMQuyhsQkVggU9GEj77HFLB3bm2zmM6b5DcpttTOHMoxLigXNln8MIXPMYRCZ1bVqRZ3ObZvYbXt7Cx3Y9eJgmDdxDW/UjOCLKt02KqXxXlKvj/nA8SSZD0zB5d2ThYq79zRF0SISWOqNIKEnEdDU9S8uWgnwdlEiJBZZ/) # Zsh, ~~29~~ 27 bytes -2 bytes thanks to @GammaFunction ``` <<<$[${${1//\'}/#0[Bb]/2#}] ``` [TIO](https://tio.run/##JYxBCsIwFET3OUWgga@rJLW1it1YsWcQYhctSahQFHRhMe3Z45QO/Jn3ZzG/Tx/9ZhtiWZbCiCCClvJOs0yUqbpGpsncxJl9@8fg@Nu1lg98mgwXA29O9sU9CPl0UTOd7rJ8ddoXh6Niaqxrpm4eNp67i716QEsgcug6DZGCwLgKz9KypYCvg4qQlFH@Bw) [Answer] # Go, 75 ``` import "strconv" func(i string)int64{n,_:=strconv.ParseInt(i,0,0);return n} ``` [Answer] # JavaScript (ES6), 112 bytes ``` n=>+(n=n.toLowerCase().replace(/'/g,""))?n[1]=="b"?parseInt(n.substr(2),2):parseInt(n,+n[0]?10:n[1]=="x"?16:8):0 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 27 bytes ``` ØDiⱮḢ=1aƲȦ ṣ”';/Ḋ⁾0o;Ɗ¹Ç?ŒV ``` [Try it online!](https://tio.run/##y0rNyan8///wDJfMRxvXPdyxyNYw8dimE8u4Hu5c/Khhrrq1/sMdXY8a9xnkWx/rOrTzcLv90Ulh/60fNcxR0LVTAKqwPtzO9XD3lsPtj5rWRP7/b8hlaGRsYgoh1c3MLSwNuAwq3Ny4DCLSgESFY5JzimsakJGoDmSppwLFkgyBQN0ACIBsIHYCckCiXCABIAkx0EAdSKubqJsCAA "Jelly – Try It Online") Almost all of this is handling octal. Feels like it could be better golfed. [Answer] # [Ruby](https://www.ruby-lang.org/) with `-n`, 17 bytes Just jumping on the `eval` train, really. ``` p eval gsub(?'){} ``` [Try it online!](https://tio.run/##KypNqvz/v0AhtSwxRyG9uDRJw15ds7r2/38DQyNjLhA2qACS//ILSjLz84r/6@YBAA "Ruby – Try It Online") [Answer] # [Java (JDK)](http://jdk.java.net/), 101 bytes ``` n->{n=n.replace("'","");return n.matches("0[bB].+")?Long.parseLong(n.substring(2),2):Long.decode(n);} ``` [Try it online!](https://tio.run/##LY8xa8MwEIV3/wqhpRJNhOylIJOWBOqpWzoUQoaLLDVybMlIciAY/3ZVMb3pwb373rsO7rDt2lsyNiqvQSrUzEXv7C/S5Bi9ycLSuggRopHo7kyLBjD2f3c6A52LBuldstv32e4s82rsM4bgF7zBmNZexclbZNkAUV5VIJifLocze8X04yvnsBF8UE9FLAvTJaxgUtFNRcVqaJV0rSK5xpLqosuN2RRNz/bewyOwfKBgIEBzwvjtVpIWQlOmnf8EeSXHR4hqYG6KQoyZHvvnS8uSEj@UeVJZvSVe8sR/dPMH "Java (JDK) – Try It Online") [`Long.decode`](https://docs.oracle.com/javase/7/docs/api/java/lang/Long.html#decode(java.lang.String)) deals with all kinds of literals except the binary ones. Template borrowed from [Benjamin's answer](https://codegolf.stackexchange.com/a/185699/71546) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~120~~ 118 bytes -1 byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) ``` f(char*s){int r=0,c=s[1]&31,b=10;for(s+=2*(*s<49&&(b=c^24?c^2?8:2:16)-8);c=*s++;)r=c^39?r*b+(c>57?c%32+9:c-48):r;c=r;} ``` [Try it online!](https://tio.run/##VU7baoMwGL6eTxEETeIBkpi2HpbKVtZnGOwAGhfnxexIxigUn92lXpj1uwjfKfyfTHsp51kh@dnoyODLMP4ALUgihXmhb2FGk1ZQUqmTRiYWLEKRuedFGKJWyHfGa/vUeclKusVpjispIhPHFdY2zYpaR22M5H6zq2WQsbgoZcpzXGrb09U0/56GDvTLbWCPexfv7lvbBQr5Qcq4SffAIuheRz8BJgEKGYwrb/K868yvZhjR8qlHPvFtcCV0JSzjmxsBt7u8WIvkfDyu/Fk5fn5oD92TcrqB1oAfrtFSC0gsnOXoo43@VVfqTOfdjCTQSsjhYkzzHw "C (gcc) – Try It Online") [Answer] ## C (gcc), ~~101~~ ~~97~~ 83 bytes ``` *d;*s;n;f(int*i){for(s=d=i;*d=*s;d+=*s++>39);i=wcstol(i+n,0,n=!i[1]||i[1]&29?0:2);} ``` [Try it online](https://tio.run/##ZZHRToMwFIav5SkqyWxLWdKyTcWmGmfkag9gMrnYqJgmk5HBosm2Z8dTAobif3Gg3/nPn8LJpp9Z1jSBlkElC5kTU9SBoad8fyCV0srIQCtoaQaVscdZTKVR31lV73fEsCLkYaGuzVqk57OtN1H8xB8iKi/N18YUhKKTh0A2Fkp5rNcpUh20WvnCD9FAAKLZfNHD7ohv7@5j3sGVz3@SxA8HIfwtTwY51vG8fdGveQtHxz/LBgPEH6OopQBhDrJuAFvujC2h6dzZWoSb8c8g3Ns539gxDBDP8cJNisRodDjFW@dFtg/YGbL7Q0Zx2f1sk8IbY9S7Kg/Qyok/mYpoV8EOJvq9gKzeF6KcwF71sSQ9opRK79L8Ag) [Answer] **PHP - 43 Byte** ``` eval("return ".str_replace($a,"'","").";"); ``` Same method as <https://codegolf.stackexchange.com/a/185644/45489> [Answer] # C++, G++, 189 bytes ``` #include<fstream> #include<string> void v(std::string s){{std::ofstream a("a.cpp");a<<"#include<iostream>\nint main(){std::cout<<"<<s<<";}";}system("g++ -std=c++14 a.cpp");system("a.exe");} ``` No need for tests Requires installation of `g++` with C++14 support Now, explanations : > > It writes a file called `a.cpp`, uses GCC to compile it and gives a file that output the number > > > [Answer] # [Pyth](https://github.com/isaacg1/pyth), 27 bytes ``` Jscz\'?&qhJ\0}@J1r\0\7iJ8vJ ``` [Try it online!](http://pythtemp.herokuapp.com/?code=Jscz%5C%27%3F%26qhJ%5C0%7D%40J1r%5C0%5C7iJ8vJ&input=123&debug=0) Unlike the previous (now deleted) Pyth answer, this one passes all test cases in the question, though it is 3 bytes longer. [Answer] # C (gcc) / Bash / C++, 118 bytes ``` f(i){asprintf(&i,"echo \"#import<iostream>\nmain(){std::cout<<%s;}\">i.C;g++ i.C;./a.out",i);fgets(i,i,popen(i,"r"));} ``` [Try it online!](https://tio.run/##LU5BboMwELz7FZYrahwIBQJpiWmkJmreUKn04DiY@ABGmKJIiLfTJelIOzM7ttcr15WU86xczUZh2043vXKftU9KeTW4IE@6bk3X59rYvitFvS@aWujGZaPtL7udNL99njuWTwXZ6@DIK8/DiwYvIoAz4mvGVVX21tW@9lvTlg040hHG@DTLq@jw8J1lPxzBz/gxGo8IA5TpXH5/OjDO7hHgf0XirKPY4nfs2KIh/uAruMU4muYIRfEmSR9Mt69vWYjC2@mEwi8FdPs4Hy@fCoyg4GgJ2TkC0BAAHuoAzZKiJQB@DAwpKE1oijZesopRnG5XUH8 "C (gcc) – Try It Online") [Answer] # Java, ~~158~~ 154 bytes This just waiting to be outgolfed. Just tries regexes until something works and default to hex. -4 bytes thanks to @ValueInk ``` n->{n=n.replace("'","");var s=n.split("[bBxX]");return Long.parseLong(s[s.length-1],n.matches("0[bB].+")?2:n.matches("0\\d+")?8:n.matches("\\d+")?10:16);} ``` [Try it online](https://tio.run/##TZAxa8MwEIV3/wqhpRJNhJShLTZpaaCZuqVDIPFwdaRYri0b6Rwagn@7qpQMuenxHe8e7xo4wbw5/ETrUHsDlSbrS9b27kgM26C3STheZAEBbUVOvT2QDqy77XYl8Eu2JmYZ3fz14pZOeD206QyjD3RGKS9O4ElIPAytRUZ336vfbZm41zh6Rz5TlBjAB31VLOyCaLU7Yj1X5cyJDrCqdWBUJmMpHil/W@T3eL8/XOHLPbwxJXP1xIspFlmTaooRbSvevYdzEAG9ho4BT67hq//PNnluuDC9/4CqZptzQN2JfsQ8H1JXbK9/mKYY5UqliWrxHKWSUW7N@g8) # Using ScriptEngine, ~~92~~ 87 bytes Eval train coming through. Technically this is passing the torch to JS, so it's not my main submission. ``` n->new javax.script.ScriptEngineManager().getEngineByName("js").eval(n.replace("'","")) ``` [TIO](https://tio.run/##XY4xa8MwEEZ3/YpDSyRIRHfTDoV4azt4LBkuysmRap@NdHEcQn67a0qmTh98PHgv4YS7dPpZIgvlgJ6gvquvYyIvEEwjOXILxYKc83AtsJ89jRIHrlQRlOhhGuIJeoz8hL8PaP/DcFc1hNeFd29MV0irdHbF5ziKa/5mz21k@kDGlrKxrqXn9X77xJ6MTkVbRxN2hl2msVtLjd7ordbWLpVqbkWod8NF3LhWSMcmuGD0y1yHlajU47H8Ag) ]
[Question] [ *(Essentially the inverse of [Find the needle in the haystack](https://codegolf.stackexchange.com/q/179351/42963))* Given two tuples, `(w, h)` and `(x, y)`, generate a haystack composed of a single random [printable ASCII character](https://codegolf.meta.stackexchange.com/a/5869/42963) of `w` width and `h` height with a needle made of a different random printable ASCII character at `(x, y)` when measured from the upper-left. For example, when given `(5,4)` for the width and height, and `(3,1)` (zero-indexed) for the location of the needle, a possible haystack could be the following: ``` ##### ###N# ##### ##### ``` Another possibility could be ``` ***** ***$* ***** ***** ``` among hundreds of others. ### Rules and Clarifications * Input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). This means you can take input as a list of list of integers, as a single string, as two integers via command-line and a tuple via function argument, etc. * You can print the result to STDOUT or return it as a function result. * Either a full program or a function are acceptable. * You can choose whether the `(x, y)` tuple is zero-indexed or one-indexed, but please specify in your solution which you're using. * You do *not* get to pick which characters to use. That's part of the challenge - randomly selecting the characters. * Every possible output for a given input must have a non-zero chance of appearing, but the randomness doesn't need to be uniform. * The haystack is guaranteed to be at least 2x2 in size, so it's unambiguous which is the needle and which is the hay. * There is only ever one needle, and it's only ever one character in size, and it's guaranteed to be within the boundaries of the haystack. * [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 (Node.js)](https://nodejs.org), ~~122 120 106~~ 103 bytes Recursively builds the output character by character. The coordinates are 0-indexed. ``` (w,h,x,y)=>(s=new Date%9023,g=X=>Y<h?Buffer([X-w?(x-X|y-Y?s+1:s%96)%95+32:13])+g(X<w?X+1:!++Y):'')(Y=0) ``` [Try it online!](https://tio.run/##DcndCoIwGADQV6kL8fvYFv5koDgH0UNsRBdimxbiwllT6N1X5/Y820/ruvnxWthk7zoYHsDTga50Q96A45P2u0u76KhMspz2XPJG1YM4v43RM1wl8wJWJr8bU8KRtHJRecKoLEieVWl@Q9KDrL2Q/9oTorCKYwTFEwydnZwd9WG0PRgo6JHmNEUMPw "JavaScript (Node.js) – Try It Online") ## How? ### Problem To generate the haystack and the needle, we could either: * generate a random haystack and process some loop to generate a random needle until it's different from the haystack * shuffle the whole range of printable characters and pick the first 2 of them Unfortunately, both approaches are rather lengthy in JS. ### Solution We use instead a method that guarantees to generate 2 distinct characters with a single random number and without any loop. We pick a random seed \$s\$ in \$[0..9022]\$ and define the haystack \$h\$ and needle \$n\$ as: $$\begin{align}&h=(s+1)\bmod 95\\ &n=(s\bmod 96)\bmod 95\end{align}$$ (we then need to add \$32\$ to turn them into printable ASCII codes) Basically, \$h\$ follows the pattern: $$1,2,3,...,94,0,1,2,3,...$$ while \$n\$ follows the pattern: $$0,1,2,3,...,94,\color{red}0,0,1,2,3,...$$ The sequences are progressively shifted relative to each other because of the extra \$0\$ in the needle pattern. [This code](https://tio.run/##TY7BTgMhFEX3fMVNEwM4SmprTaajcdFP6FJdkIHp0Eyh4WGbaPz28ZG4cAWcx7n3He3FUp/DudzH5Pw8ky94QfRX7H3phBhSVsRk2YHwjHa5WvOtaTS@BTDyhMcNHjRu0G46ZpEZ1dfTH2IWBsVfOVejjDldsQjxYqfgcLYhL6rGxcY6p/Ylh3gwQ06n3Wjzjrdit8F6dcfR9dS6Ez@iT5HS5M2UDqq6FL58rWg3uEX7iFdI@ux7TySxhRxsmLyTrP4X5XuUnPlmjOGMD3NMISoJyRXz/As) shows that it does eventually lead to all possible pairs \$(h,n)\$ with \$h\neq n\$ (there are \$95\times 94=8930\$ of them). And because we need only one random number, we can afford to use the current timestamp in milliseconds as our entropy source with `new Date%9023` instead of the longer `Math.random()*9023`. ## Commented ``` (w, h, x, y) => ( // w = width, h = height, (x, y) = coordinates s = new Date % 9023, // s = random seed in [0..9022] g = X => // g = recursive function taking X Y < h ? // if we've not reached the end of the grid: Buffer([ // append the next character: X - w ? // if we haven't reached the end of the line: ( x - X | // if this is not the position of the needle: y - Y ? // s + 1 // append the haystack character : // else: s % 96 // append the needle character ) % 95 + 32 // : // else: 13 // append a linefeed ]) + // g(X < w ? X + 1 // append the result of a recursive call : !++Y) // with either (X+1, Y) or (0, Y+1) : // else: '' // stop recursion )(Y = 0) // initial call to g with X = Y = 0 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 13 bytes ``` p/⁼€ịØṖẊ¤s⁸Ḣ¤ ``` [Try it online!](https://tio.run/##y0rNyan8/79A/1HjnkdNax7u7j484@HOaQ93dR1aUvyoccfDHYsOLfl/eLnSoa2RQPmsRw1zDm07tO1Rw9z//6OjTXUUzGN1FEC0KYi21FEwio0FShjqKBiDBIC0IZQGSgAA "Jelly – Try It Online") -1 byte thanks to [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string) Returns a list of lines. The last line in the Footer section displays it as a square. Takes input as `[w, h]` and `[y, x]`, where `x` and `y` are 0-indexed. ## How it works ``` p/⁼€ịØṖẊ¤s⁸Ḣ¤ - Main link. Takes [w, h] on the left and [y, x] on the right p/ - Reduce Cartesian product over the arguments. This yields a list of co-ordinates from (1, 1) to (h, w) € - Over each list: ⁼ - Is it equal to [x, y]? - This yields a list where every element except 1 is 0 ¤ - Create a nilad: ØṖ - Printable ASCII characters Ẋ - Shuffled ị - Index into the shuffled characters, replacing 1 with the first char in the shuffled list and 0 with the last. Therefore, the two characters will be distinct ¤ - Create a nilad: ⁸ - Yield [w, h] Ḣ - Extract w s - Split the list of characters into rows of length w - Implicitly output ``` [Answer] # Excel VBA, ~~128~~ ~~118~~ ~~106~~ ~~94~~ 96 bytes *-12 bytes inspired by agtoever* *-12 bytes thanks to Taylor Scott, VBA extraordinaire* *+2 bytes and -1 bug thanks to Taylor's unnecessary, intimidating, and [much appreciated work](https://pastebin.com/ftBs4Dn3)* ``` Sub n(w,h,x,y) a=94*Rnd [A1].Resize(h,w)=Chr(a+32) Cells(y,x)=Chr(32+(a+93*Rnd+1)Mod 95) End Sub ``` Input and output are one-indexed. Output is to the top left cell range of the active sheet. `a=94*Rnd+32`: `(126-32)*Rnd+32` gives a number between 32 and 126, inclusive. `Range(~)=Chr(a)`: Fills all the cells with the ASCII character. `Cells(y,x)=Chr(~)`: Fills just that one cell with the other ASCII character. `(a+62*Rnd)Mod 95+32`: `{(a+[94-32]*Rnd) Mod (126-32+1)}+32` gives a random number between 32 and 126 inclusive that is *not* the same as `a`. (I can't prove that mathematically but 100 million tests showed no collisions.) Example output: [![enter image description here](https://i.stack.imgur.com/FrCfb.png)](https://i.stack.imgur.com/FrCfb.png) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) v6, ~~102~~ 96 bytes ``` param($x,$y,$a,$b)$j,$k=' '..'~'|random -C 2 -join((,$j*$x+++' ')*$y|%{"$_$k"[$i++-eq$b*$x+$a]}) ``` [Try it online!](https://tio.run/##HclLDoIwGEXheVfxh1wt0EIIjyEjl2GMKREib6wDIYBbr5WcyZecafyU@v0su86gylczKa16F7PEIqEkCg@NRJtz4mHIv3zTaniMPQUXilnQjPXguhKNj1kIwRn3fCzbaXVwR@tcUQsRlC8U/w912z2zM3ZGRbEtouhwShkllB7ObPaZHw "PowerShell – Try It Online") This answer, thanks to mazzy, uses the character range feature added in v6 to save several bytes over the more flexible answer below. # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~119~~..~~105~~ 102 bytes -16 bytes thanks to mazzy -1 byte thanks to AdmBorkBork ``` param($x,$y,$a,$b)$j,$k=32..126|random -C 2 -join((,$j*$x+++' ')*$y|%{[char]($_,$k)[$i++-eq$b*$x+$a]}) ``` [Try it online!](https://tio.run/##HYtLDoIwAAX3PUUXT6G0ECzgjpXHIMQUhQDysy6EAGevlcxmkjdvGr@l/tRl1xlU6WompVXvYhZYBJRAwdAKvNJIBsFFXjethufYU/9GJfHbsRlcV6D1MHPOHeIwD8t2WrNHrXTu4m6vLEPDuV@@UfwzqHxnZifkjIpKS0jDw2Oa0IjGhycWu5kf "PowerShell – Try It Online") Gets two ints in the range of [32,126]. We first make a 1D array out of the first value, appending a new line after every `$x`chars. Doing this means we also have to increment `$x` so that our index math isn't affected. We then iterate through the array, and either yield a char-ified first value or the needle. Finally, we join all the yielded values and output it. Answer is 0-indexed by the way. [Answer] # [Python 2](https://docs.python.org/2/), ~~134~~ ~~133~~ ~~120~~ ~~112~~ 111 bytes ``` lambda w,h,x,y:zip(*[iter(chr(r[x+y*w==i]+32)for i in range(w*h))]*w) from random import* r=sample(range(95),2) ``` [Try it online!](https://tio.run/##JYpLDoIwFAD3nKI7@kpjIshCk54EWFSh9hn6ybNJwctXDauZTCbuyQbfFqPGsmp3nzXL0spN7rcPRi4GTAvxhyVOw9bsIiuFU9O1YAIxZOgZaf9ceBYWYBIZKkPB/eP8A7oYKImK1Fu7uC78mK89yBZKJPSJ1aOvT6@AnjsdeX24NLyXF9nJMwCULw "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` QŒṬƤSḂịØṖẊ¤ ``` A monadic Link accepting a list of lists, `[[height, width], [row, column]]` (1-indexed), which yields a list of lists of characters. **[Try it online!](https://tio.run/##ATMAzP9qZWxsef//UcWS4bmsxqRT4biC4buLw5jhuZbhuorCpP/Dh1n//1tbNSw3XSxbMywyXV0 "Jelly – Try It Online")** (The footer calls the link and joins with newlines.) ### How? ``` QŒṬƤSḂịØṖẊ¤ - Link: [[h, w], [r, c]] Q - de-duplicate (i.e. [[h, w]] if [r, c] == [h, w] else [[h, w], [r, c]]) Ƥ - for prefixes (of that list): ŒṬ - get a 2D array with ones at the coordinates specified S - sum (vectorises) (giving us an h*w matrix with zeros almost everywhere, except a 1 at our needle and, if [h, w] != [r,c], a 2 at the bottom-right) Ḃ - modulo two (replacing the 2 with a zero if it exists) ¤ - nilad followed by link(s) as a nilad: ØṖ - list of printable characters Ẋ - shuffled ị - (left) index into (right) (vectorises) ``` [Answer] # Dyalog APL, ~~24~~ ~~23~~ 21 bytes ``` ⎕UCS(32+2?95)[⎕∘≡¨⍳⎕] ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862hXSQPxQ52ANYyNtI3tLU81oIP9Rx4xHnQsPrXjUuxnIi/0PVPg/jctEwZTLUMEYAA "APL (Dyalog Unicode) – Try It Online") 0-indexed. -1 thanks to ngn, -2 thanks to Adám suggesting to use a different I/O format. [Answer] # [Python 2](https://docs.python.org/2/), 133 bytes ``` from random import* r=range def f(h,w,x,y): p=sample(r(32,127),2) for i in r(h): print ''.join(chr(p[i==y and j==x])for j in r(w)) ``` [Try it online!](https://tio.run/##JY3BCsIwEETP5iv21l1ZxKaIIORLxEOxjUmxSVgDbb4@RoSBgeE9JpXsYtC1WokryBimVn5NUfJRiWnDa1bTbMGi4413LnRTkMxnXNN7RsFBc6@vxJoU2CjgwQcQdA07JPEhQ9edlugDPp1guntjCrQbWIzZH/RTlr@yEVWL/ZlbLjxQ/QI "Python 2 – Try It Online") -12 thanks to Value Ink for suggesting using a loop comprehension. -2 thanks to Unrelated String for suggesting python 2 instead of python 3 to get rid of parenthesis in the print function! [Answer] # [Python 2](https://docs.python.org/2/), 110 bytes ``` from random import* w,h,x,y=input() m,n=sample(map(chr,range(32,127)),2) l=eval(`[[m]*w]*h`) l[x][y]=n print l ``` [Try it online!](https://tio.run/##DctBCsMgEEDRvafIUmU2MS1deRIRIq2tgo6DNU08vXX14cGn3kJBNca7lrxUh6@ZmKnUJtkJAS7oOiIdjQuWAfXXZUqeZ0f8GSrM4@P5pmBVDyFACZa0/7nEd2OylaeVYZ9mLmu61cioRmxLGuMON9hg/QM "Python 2 – Try It Online") I copied [TFeld's solution](https://codegolf.stackexchange.com/a/194356/20260) and managed to golf a char using list assignment. The `eval()` trick is used to [make a mutable matrix](https://codegolf.stackexchange.com/a/51022/20260) to avoid the list mutation applying to every row. **111 bytes** ``` lambda w,h,x,y:[[chr(r[x^i<1>y^j]+32)for i in R(w)]for j in R(h)] from random import* R=range r=sample(R(95),2) ``` [Try it online!](https://tio.run/##JYhJDoIwFED3nKI7@vXHBJCFRjwEW4akCrVt6JAvCXD6imH1hrDNyrs8yqqNk7CvQbAFFa643ZvmrYhTs/b6kT233nTnIgfpiWmmHav5At2/zFEKukSSt4yEG3ZoGzzNp6Su9vEZE6q@woZp5DW/lYA5xEDazSxtXXoxXjtuReDp4Sh5iVcsMAOA@AM "Python 2 – Try It Online") A smaller change that only tied. Calling the function multiple times always give the same random choices, which I hope is OK. **109 bytes** ``` lambda w,h,x,y:[m*w]*y+[m*x+n+m*(w+~x)]+[m*w]*(h+~y) from random import* m,n=sample(map(chr,range(32,127)),2) ``` [Try it online!](https://tio.run/##JcqxDoMgEIDh3adwvINbxDZNmvgk1oFWKSQeEkqDLL46Nen0Df8fSrKbV9UMj7pqfs66zWRpp3IfWeRJFHm6Sy9ZQJbHjpP8B7DyKNiYuHEbtZ9PHIctJtEw@eGjOawLsA7wspHO471Ar6hTN0RSWEN0PrUGhPPhmwCxXulCPXU/ "Python 2 – Try It Online") A shorter function making the list of lines via multiplication. Also generates the characters just once. [Answer] # [Perl 5](https://www.perl.org/), 86 bytes ``` ($,,$b)=keys%{{map{chr,1}33..126}};$_=($,x$F[0].$/)x$F[1];s;(.* ){$F[3]}.{$F[2]}\K.;$b ``` [Try it online!](https://tio.run/##K0gtyjH9/19DRUdHJUnTNju1sli1ujo3saA6OaNIx7DW2FhPz9DIrLbWWiXeFqiqQsUt2iBWT0VfE8QyjLUuttbQ0@LSrAbyjGNr9UC0UWxtjLeetUrS//@mCiYKxgqG//ILSjLz84r/6/qa6hkY/tdNLAAA "Perl 5 – Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), 71 bytes ``` f(w,h,x,y)=(z=unique(rand(' ':'~',9));g=fill(z[1],(h,w));g[y,x]=z[2];g) ``` `x,y` are one indexed. Returns a 2d array of characters, I spent the extra bytes to make sure the default printing has the right orientation (`'` for transpose no longer works because they stick to a strict mathematical meaning). Getting two distinct randoms is surprisingly verbose, this has about a 1e-18 chance of failing to do so, one more byte could make it 1e-196. [Try it online!](https://tio.run/##FchLCoAgEADQq7RzBmaj1KLCk4gLwSxDog@SuujqVrzdW2PwhqdaHdy0UKKMEoqMmz/iBKfZLLCGDexh1COOs3Q@BCiKa4KF7r9UpqRlUUKPM1brrz2YDA46aj8Csb4 "Julia 1.0 – Try It Online") [Answer] # [J](http://jsoftware.com/), 21 bytes ``` u:@(32+2?95){~#.=i.@[ ``` [Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/S60cNIyNtI3sLU01q@uU9Wwz9Ryi/2tycaUmZ@QrGANhmoKhgiGECzQJTBsaKBgZACWA0v8B "J – Try It Online") Inspired by dzaima's APL answer. Thanks to Galen and Adam for the randomize fix. [Answer] # [Octave](https://www.gnu.org/software/octave/) with Statistics Package, 45 bytes ``` @(x)randsample(' ':'~',2)(sparse(x{:},0:1)+1) ``` The input is a cell array of 2 numeric vectors of length 2: `{[h y] [w x]}`, with `x`,`y` 1-based. [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzKDEvpTgxtyAnVUNdQd1KvU5dx0hTo7ggsag4VaOi2qpWx8DKUFPbUPN/mkZ1tJmCUaxCtLmCcWyt5n8A) [Answer] # [Ruby](https://www.ruby-lang.org/), 62 bytes ``` ->w,h,x,y{a,b=[*?\s..?~].sample 2;r=[a*w]*h*$/;r[y*-~w+x]=b;r} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf165cJ0OnQqeyOlEnyTZayz6mWE/Pvi5WrzgxtyAnVcHIusg2OlGrPFYrQ0tF37ooulJLt65cuyLWNsm6qPZ/QWlJsUJatKmOMRAaxv4HAA "Ruby – Try It Online") [Answer] # Pyth, 56 50 48 41 bytes ``` JEKE=TE=Yrd\~=Zh.SYVJVQ ?qHK?qNTpeYpZpZ)d ``` I'm somewhat struggling to golf Pyth, but posting this to force myself to learn. Edit 1: Golfed it down a bit, and made it an actual solution -6 bytes Edit 2: Looked at it after posting it and realized a few bytes save by ignoring space. -2 bytes Edit 3: Today I learned about character ranges, which shortens things significantly. -7 bytes [Answer] # Excel + CSV, 104 bytes ``` ,,,,=94*RAND()+32,=REPLACE(REPT(REPT(CHAR(E1),A1)&" ",B1),D1*A1+D1+C1+1,1,CHAR(MOD(E1+62*RAND(),95)+32)) ``` Save as CSV, add input as `A1` - `D1`. Output will be in `F1`. Using @Engineer Toast's solutoin for generating 2 unique characters. Needle position is 0-indexed, which is curious, as Excel itself if 1-indexed. Changing to 1-indexed input adds 3 bytes (`(D2-1)*(A2+1)+C2` instead of `D1*A1+D1+C1+1`). [Answer] # [SOGL](https://github.com/dzaima/SOGLOnline), 18 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ~Δψ] ~Δψ⁴⁴=}A*∙až ``` [Try it here!](https://dzaima.github.io/SOGLOnline/?code=JTIwJTdFJXUwMzk0JXUwM0M4JTVEJTIwJTdFJXUwMzk0JXUwM0M4JXUyMDc0JXUyMDc0JTNEJTdEQSoldTIyMTlhJXUwMTdF,inputs=NSUwQTQlMEEyJTBBNA__,v=0.12) 1-indexed. [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 65 bytes ``` D,g,?!, L,c95Rdb[€BXd¦=BFV#@G+b[95€Ω%31€+€CA€RbU‽g$€=$€Ω:A$pbUp$T ``` [Try it online!](https://tio.run/##S0xJKSj4/99FJ13HXlGHy0cn2dI0KCUp@lHTGqeIlEPLbJ3cwpQd3LWToi1NgWLnVqoaGwJpbSB2dgQSQUmhjxr2pqsAmbYqYAVWjioFSaEFKiH/VXISc5NSEhUM7ezt7Lm4XHSy8jPzdLg4HeqAhBdIoKAotaQkM60SJGgFJIAGVIMU1SaF5nFxqcCk7Sr@/482VDCM/R9trGAcCwA "Add++ – Try It Online") Takes input as `[y x]` and `[w h]`. `x` and `y` are 1-indexed. Outputs a list of lines. Added 17 bytes to make sure the needle is distinct. ## How it works We start by generating two ranges from \$1\$ to \$95\$ inclusive, before choosing a random value from each. If the two values are equal, we add one to the one of them. We then add \$31\$ to each, yielding two characters ord points in the ASCII range. Finally, we convert them to characters. Next, we generate a list of all co-ordinates in the grid, and compare them with `[y x]`. If the co-ordinates match, we yield \$1\$, otherwise \$0\$. Next, we index each of these \$1\$s and \$0\$s into the two characters, creating a grid of \$0\$ characters with 1 \$1\$ character in it at `[y x]`. Finally, we retrieve the width and split the grid into that many rows. [Answer] # [PHP](https://php.net/), ~~113~~ 109 bytes ``` for([,$w,$h,$x,$y]=$argv,$a=range(' ','~'),shuffle($a);$i++<$h;print" ")for(;$$i++<$w;)echo$a[$i-$y||$$i-$x]; ``` [Try it online!](https://tio.run/##JYzLCoMwEEX3/YoiF5LgdFPaVZR@iLgIkjiBoiF9qCD99VEpF86Bs7iJk1SPtDOMWTeEicCEmbC0NVzuvwRXZzf0XquzIvVThl78CeHpNZyxiGVZgW3KcXgXp8IcPxb/PFnjOx7hGsQLlnXF4bm1InKX277rBg "PHP – Try It Online") Pass inputs as command arguments (`$argv`) in order of `w`, `h`, `x` and `y`. The `x` and `y` are one-indexed. ``` for( [,$w,$h,$x,$y]=$argv, // put inputs from $argv array into 4 short named variables $a=range(' ','~'), // create $a array containing printable ASCII characters shuffle($a); // shuffle the array $i++<$h; // loop $h times (rows) print"\n" // print a newline after every row ) for(;$$i++<$w;) // loop $w times (columns) echo // print $a[ // a character from $a (1st char for needle and 2nd for heystack) $i-$y || // when row and y don't match $$i-$x // or when col and x don't match (will be false only for needle) ]; ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 145 bytes ``` (a,b,c,d)=>{int l=0;for(var j=Enumerable.Range(32,95).OrderBy(k=>Guid.NewGuid()).ToList();l<a*b;)Write((char)j[l==c*a+d?1:0]+(++l%a<1?"\n":""));} ``` [Try it online!](https://tio.run/##NYhBC4IwGEDv/YohBN@XS7LwkHNGQXSJggg6VIc5Z83WhGlFRL/d6tDhvQdP1n1Z63YqG11Zkmjb0D/kq7TgLQiaUUlz5Onru4jhA1ZUDu7CkZLP7e2qnMiMCjbCnhSMhnQcYbB2uXKzJ1x4urjpPFipx6@AGGyrpa4bQGYS0csY7pxuFIA8C4fl3nAue8LPJ2E8OPrg@6YrknDiHawXex4ie7esUxCI6IiGdIis/QA "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Icon](https://github.com/gtownsend/icon), 119 bytes ``` procedure f(w,h,x,y) until m:=char(32+?95)&n:=char(32+?95)&m~==n t:=[];1to h&put(t,repl(m,w))&\z t[y,x]:=n return t end ``` [Try it online!](https://tio.run/##Xc7BTsMwDAbge57CXKpE@MJgQgRFvMDeYOxQpZ4a0TiVcek6BK8@SjcQwrf/s2U7xcKnLvELSM1NyadeSqRmEIK9HbHFA07ODKypg@xDbGuxt6vrp4e1q/hfzp8hsFEftrvHGy3QVv2gVlGo72zG0bnq@Wh0O@Fh5@dJIR2EQQ1x8@durhNbZ2Cu80/pSJe88WFv7xHWCHcIqzPSG8kE4sPVBpoC7wv@epxdvn2UpPRqo/vpL3BZ/LH88AU "Icon – Try It Online") `x`and `y`are 1-indexed [Answer] # [Python 3](https://docs.python.org/3/), 137 bytes ``` lambda w,h,x,y,c=chr:"\n".join([c(a)*w,c(a)*x+c(n)+c(a)*(w-x-1)][r==y]for r in range(h));a,n=__import__("random").sample(range(32,127),2) ``` [Try it online!](https://tio.run/##JYrtCoIwFEBfZezXvXUV1CIo9iQqY01tC/fBEtSnX2G/zoFz4r6Y4Js8iS7Pyj0HxVYytNFOWmiT7rzzvHwH66HVoPC00oHtrMHj@XBYi62osG@TEHs/hcQSs54l5V8jGMSHIi@ktC6GtEgJ/FeG4DiWH@XiPML/bGqq6htSjTkm6xeY4EoXaqhCzF8 "Python 3 – Try It Online") Uses zero-based indexing for the needle position. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 57 bytes ``` {(' '..'~').pick(2)[0 xx$^a*$^b-1,1;*].pick(*).rotor($a)} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WkNdQV1PT71OXVOvIDM5W8NIM9pAoaJCJS5RSyUuSddQx9BaKxYipaWpV5Rfkl@koZKoWftfrzixUiEtv0ghTcNUx0TzPwA "Perl 6 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes ``` UONN‽γJNN‽Φγ¬⁼ιKK ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98/KSc/L13DM6@gtMSvNDcptUhDU0cBjRuUmJeSn6uRrqlpzeVVmlsQko9XA1BVQFFmXokGVJ9bZk4JUDxdR8Evv0TDtbA0MadYI1NHISA1NRuoGgSs//83VTBRMFYw/K9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` UONN‽γ ``` Draw a rectangle of the given width and height using a random printable ASCII character. ``` JNN ``` Jump to the 0-indexed position of the needle. ``` ‽Φγ¬⁼ιKK ``` Print a random printable ASCII character, but filtering out the character under the cursor. [Answer] # [Red](http://www.red-lang.org), 156 bytes ``` func[w h x y][c: :collect p: take/part random c[repeat i 95[keep to sp 32 + i]]2 c[repeat i h[keep/only c[repeat j w[keep pick p i * w + j =(y * w + x)]]]]] ``` [Try it online!](https://tio.run/##Tc69CsMgFIbh3av4xv4MgaQtNNCb6CoOokdikqoYi8nV27QptGf6hveBE0mXO2kuWJRO@0c1EWk4n5lpi3k6xTM6zFgEVy1a5ceRVEJokeRAVZAxYZNQPFIgmWBxPfOBKCB5TAFNjSOsEDX7S7pPUXk3Lj/ZI28wWDUgrNkBecU9u@2W75734n3F@EhSdUgwuOCMExoeonXrP9R765BEeQE "Red – Try It Online") `x` and `y` are 1-indexed. Returns a list of strings. ## Readable: ``` f: func [w h x y] [ c: take/part random collect [ repeat i 95 [ keep to sp 32 + i ] ] 2 collect[ repeat i h [ keep/only collect [ repeat j w [ keep pick c i * w + j = (y * w + x) ] ] ] ] ] ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~144~~ ~~132~~ 131 bytes ``` from random import* i,j,k,l=input() n,h=sample(range(32,127),2) for x in range(j):a=[chr(n)]*i;a[k]=chr((n,h)[x==l]);print`a`[2::5] ``` [Try it online!](https://tio.run/##JYzLCsMgEEX3@QqXTphNTEPB4JeIEGmTah6jGAvp11tLV5fDOdz4yS6QKGVJ4WDJ0rOOP2JIuW08rrjhrjzFd@bQEDp12iPuM6/la@a9wE7cAQU0S0jsYp7Y36wgrdIPlziBaf1o9WbUD3k9AX0ptRsYY/KUJztpIeVgShnwhj12Xw "Python 2 – Try It Online") Corrected the problem with the guaranteed uniqueness of the characters and saved 12 bytes along the way. [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 140 bytes ``` include random.fs : x 95 random 32 + ; : f x -rot 0 do cr dup 0 do 2over i j d= >r over r> if begin x 2dup - until nip then emit loop loop ; ``` [Try it online!](https://tio.run/##LU1bDoMwDPvvKbzviYnH0B5o3GWjKXSCFoUy7fZdCpOjxHYS2XgOQ9abNGK0rhtXTeCn0346mUXd8cWt/huoShzRiGnEztgH5NAeHUOv885L/yGGxRv6gZaxSW5hDV7UWyePZTrOsLpgRzg7IwzkQJMNGL2f99bEgZiwEGkcVAFBnsooSVO5hFWCpFQiZ8EmCtmUgk3UuOCKG0z8AQ "Forth (gforth) – Try It Online") 0-indexed ### Code Explanation ``` include random.fs \ import the random library \ Generate a random number in range 32 to 126 inclusive : x \ start a new word definition 95 random \ generate a random number between 0 and 94 32 + \ add 32 ; \ end word definition : f \ start a new word definition x -rot \ generate a random number for the haystack, then move it 0 do \ loop from 0 to h-1 (inclusive) cr \ output a newline dup 0 do \ loop from 0 to w-1 (inclusive) 2over i j d= \ check if this is the needle square >r over r> \ hide result, grab a copy of the haystack char, then grab result back if \ if it is a needle begin \ begin indefinite loop x 2dup - \ generate a new random number and compare to haystack char until \ only end loop when values differ nip \ drop haystack char then \ end if block emit \ output ascii char for value on top of stack loop \ end row loop loop \ end column loop ; \ end word definition ``` [Answer] # [C (clang)](http://clang.llvm.org/), 87 bytes ``` f(w,h,x,y){x+=y*w;h*=++w;for(y=time(0)%9023;h--;)putchar(h%w?(x--?y+1:y%96)%95+32:10);} ``` [Try it online!](https://tio.run/##DcpBCoQgFADQvadwI3xTwYqJqY90logahckGMUyiszu99ZvV/J38p5QVkrTylJlfpzC5SmgrI0TCdQ@QTXTbApqzXjctWqWQ/4442ymAZWmEU6kxi3rIrO@e9BJtM9Sa412cj3SbnAdOL7LCW3aylQ1HQh9hiUfwVCO5yx8 "C (clang) – Try It Online") Stealing from [@Arnauld answer](https://codegolf.stackexchange.com/a/194361/84844) [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~27~~ 23 bytes -4 bytes thanks to ngn! ``` {`c$(32+-2?95)x#&/y=!x} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qOiFZRcPYSFvXyN7SVLNCWU2/0laxovZ/WrSZgrm1iYJx7H8A "K (oK) – Try It Online") 0-indexed `x` and `y` Similar to Dzaima's APL and Jonah's J solutions. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žQΩIPמQΩIPǝ¹нô ``` Coordinates are 1-indexed. Outputs as a list of lines. [Try it online](https://tio.run/##yy9OTMpM/f//6L7Acys9Aw5PhzKOzz2088Lew1v@H9r9P9pUxySWK9pExygWAA) (`»` in the footer joins the list of strings by newlines to pretty-print, feel free to remove it to see the actual output). **Explanation:** ``` žQ # Push all printable ASCII characters Ω # Pop and push a random character IP # Push the first input (rectangle-size), and take its product × # Repeat the random character that many times as string žQΩ # Push a random character again IP # Push the second input (1-based coordinate), and take its product as well ǝ # Insert the random character at this (0-based) index into the string ¹н # Push the first input again, and only leave its first value (width) ô # Split the string into parts of that size # (after which the resulting list of strings it output implicitly as result) ``` ]
[Question] [ Given a list of unique strings that are anagrams of each other, output an anagram of those words that is different from each word in the list. The strings will be alphanumeric, and there is guaranteed to be a valid anagram. The program or function can, but doesn't have to be non-deterministic, meaning given the same input, multiple running a of the code can yield different outputs, as long as every possible output is a valid one. ### Test Cases ``` [Input] -> Possible output ----------------- [ab] -> ba [aba, aab] -> baa [123, 132, 231, 312, 321] -> 213 [hq999, 9h9q9, 9qh99] -> 999hq [abcde123, ab3e1cd2, 321edbac, bcda1e23] -> ba213ecd ``` [Answer] # [Python 3](https://docs.python.org/3/), 64 bytes ``` lambda a:[*{*permutations(a[0])}-{*a}][0] from itertools import* ``` [Try it online!](https://tio.run/##Pcq5CsMwEATQ3l@hTgcOGNIZ8iWKivUhLLC0Yr0pgvG3Kz5wmmF4M/nLE6Zn8a93mSF2AwhorVlNHil@GDhgWhTYxuntsRrY3F4rTxhF4JEYcV5EiBmJTckUEiuvbKUkyFrI7ohe6vqG/tITzhH@D6d1@QE "Python 3 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` нœ¹мà ``` [Try it online!](https://tio.run/##MzBNTDJM/f//wt6jkw/tvLDn8IL//6PVE5OSU1INjYzVdRSAbONUw@QUIxDb2MgwNSUpMRnEBipJNEwFqokFAA "05AB1E – Try It Online") ### Explanation ``` нœ¹мà н // Get the first element of the input list œ // Generate all permutations ¹ // Push the input again м // In the permutations list, replace all strings that // are in the input list with empty strings à // Pick the string with the greatest lexicographic // index (in this case a non-empty string) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 5 bytes ``` h-.ph ``` [Try it online!](http://pyth.herokuapp.com/?code=h-.ph&test_suite=1&test_suite_input=%5B%22ab%22%5D%0A%5B%22aba%22%2C+%22aab%22%5D+%0A%5B%22123%22%2C+%22132%22%2C+%22231%22%2C+%22312%22%2C+%22321%22%5D%0A%5B%22hq999%22%2C+%229h9q9%22%2C+%229qh99%22%5D%0A%5B%22abcde123%22%2C+%22ab3e1cd2%22%2C+%22321edbac%22%2C+%22bcda1e23%22%5D&debug=0) ### Explanation ``` h-.ph h First string in [the input] .p All permutations - Remove those in [the input] h First element. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` XŒ!ḟµḢ ``` [Try it online!](https://tio.run/##ASMA3P9qZWxsef//WMWSIeG4n8K14bii////WyJhYmEiLCJhYWIiXQ "Jelly – Try It Online") 1 byte more than the 05AB1E and the Pyth answer. Explanation: ``` XŒ!ḟµḢ Main program. Œ! All permutation of... X any element from the word list. ḟ Filter out (remove) all the elements in the original word list. µ With the filtered-out list, Ḣ pick the first element. ``` I chosen `X` because it is the shortest way I know to pick any element from the list without altering the list (`Ḣ` and `Ṫ` doesn't work, `ḷ/` and `ṛ/` is longer), and it happens to cause some randomness. The `µ` here is pretty redundant, but without it, the `Ḣ` would be paired with the `ḟ`, and it is interpreted as "filter out the head of the input", which is not what I need here (what I need is "filter out the input, and get the head"). [Answer] # Javascript, 118 Bytes ``` function f(a){s=a[0];while(a.indexOf(s)!=-1)s=s.split("").sort(function(){return .5-Math.random()).join("")};return s} ``` uses a bad randomizer to iterate over each "random" permutation. Probably provably wrong but afaik the bad randomizer just means we wont get true randomness, but will still get every permutation. Seems to work on all cases in chrome for me but apparently due to undefined behaviour in this sort abuse, it can not work in some browsers. (Probably very ungolfed feel free to improve it in your own solutions) # 80 bytes Thanks to pirateBay's comment -a lot of bytes -4 bytes thanks to Rick ``` f=a=>eval('s=[...a[0]].sort(()=>.5-Math.random()).join``;a.indexOf(s)<0?s:f(a)') ``` [Answer] # [Haskell](https://www.haskell.org/), 58 bytes *-1 byte and a fix thanks to Laikoni.* ``` import Data.List f l=[i|i<-permutations$l!!0,all(/=i)l]!!0 ``` [Try it online!](https://tio.run/##VY0xD4IwFIR3fsWDOGCCaOnURDZHnBxJhweU0FigQNn877VFTfAtd9/lcq/D5SmUslb2epwN3NBgWsjFBC2ovJQveT1pMferQSPHYTmoMLwkqFR8zuVRcUe2RzlADj3qO8R6NQ8zFwOk0B4DcFdCGWEV8Q2SDTBKIMK/kGTUh4RmXjJKvFCyEc3IrtlNjDEfs45NHzN1Ltk/qBvxHcSKClI3vx3RVFh77ypIhOtw4PYN "Haskell – Try It Online") It's probably not worth importing `Data.List` for permutations but eh. [Answer] # [Ruby](https://www.ruby-lang.org/), 46 bytes ``` ->l{(l[0].chars.permutation.map(&:join)-l)[0]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6nWiMn2iBWLzkjsahYryC1KLe0JLEkMz9PLzexQEPNKis/M09TN0cTqKb2f0FpSbFCWnS0UmJSopKOUmJiklJs7P//AA "Ruby – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes ``` hp.¬∈?∧ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P6NA79CaRx0d9o86lv//H21oZKyjYGhspKNgZGyoo2BsCGQZGxnG/o8CAA "Brachylog – Try It Online") ### Explanation ``` hp. The Output is a permutation of the first element of the Input .¬∈? The Output is not a member of the Input ∧ (Disable implicit Input = Output) ``` [Answer] # Mathematica, 57 bytes non-deterministic ``` (While[!FreeQ[#,s=""<>RandomSample@Characters@#&@@#]];s)& ``` [Try it online!](https://tio.run/##ZYq9CsMgFEb3vkUVQgtZ1LFNEQKd@zN0EIer3qAQ06JuJc9u7Vbods53vgjFY4QSLNRpqLuHDzOq7TkhXhXt80DI8XSDxT3jHeJrRjl6SGALpixpJyXV@pD3Xb2ksBQ5qTcBQ1a9@XUgPYH/2TpkXHybEcis4w0FZ@gM2IatA8N2WHX9AA "Wolfram Language (Mathematica) – Try It Online") # Mathematica, 56 bytes deterministic ``` #&@@Complement[""<>#&/@Permutations@Characters@#&@@#,#]& ``` [Try it online!](https://tio.run/##ZYoxCsMwEAT7POMEqgxBUpuEA3/AvVFxks7YENlBvlTBb1fkLpBudmcyycyZZIlUp3tVGrHf8uvJmVcZAW4Ppa84cMlvadW27tjPVCgKlx3PXHXK6zqUZRWcxg9QgMNffjdBB/R/x8TGutMFxyYm29BZwylQbNg8GW7B4esX "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~7~~ 6 bytes *-1 byte thanks to @Shaggy* ``` á kN ö ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=4SBrTiD2&input=ImFiY2RlMTIzIgoiYWIzZTFjZDIiCiIzMjFlZGJhYyIKImJjZGExZTIzIg==) Takes input strings as several inputs instead of as an array. Outputs a random permutation; switch `ö` to `g` to get the first one instead. ## Explanation ``` á kN ö Implicit input: N = array of input strings á Get all permutations of the first input string kN Remove all input strings from those ö Get a random element from the array. Implicit output ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~15~~, ~~13~~, 12 bytes ``` 1X)Y@Z{GX-1) ``` [Try it online!](https://tio.run/##y00syfn/3zBCM9Ihqto9QtdQ8///avXEpGR1HQX1xOQkEJWUCOYlJSeq1wIA "MATL – Try It Online") Saved 2 bytes thanks to Sanchises. `setdiff(...,'rows')` is shorter than negating `ismember(...,'rows')` and it avoids one duplication. Saved another byte thanks to Luis Mendo, by switching to cells instead of arrays. ### Explanation: The MATLAB / Octave equivalents are also included. ``` % Implicitly grab input x containing cells of strings 1X) % Get first cell. Equivalent to x{1} Y@ % All permutations of first row input. Equivalent to p=perms(y) Z{ % Convert the list of permutations to a cell array G % Grab input again X- % setdiff, comparing the input cells with the permutations 1) % The first of the results ``` Input must be one the format `{'abc', 'acb'}`. [Answer] # [Python 3](https://docs.python.org/3/), 78 bytes ``` lambda a:[x for x in permutations(a[0])if~-(x in a)][0] from itertools import* ``` [Try it online!](https://tio.run/##Pcq7CgIxEIXhfp9iuiSygmAn@CQxxewlOLDJhNkR1sZXj25Em1N8/ylPvXM@13i91QXTMCHgxW8QWWADylBmSQ9FJc6rRX8KjuLraFtDFz7QReEEpLMo87ICpcKih1qEstpofWcNmh7MsM9oXP@D8asNWsT/IzhX3w "Python 3 – Try It Online") -1 byte thanks to Mr. Xcoder [Answer] # [Pip](https://github.com/dloscutoff/pip), 11 bytes ``` @:_NIgFIPMa ``` Takes the inputs as command-line arguments. [Try it online!](https://tio.run/##K8gs@P/fwSrezzPdzTPAN/H///@JSYn/ExOTAA "Pip – Try It Online") ### Explanation ``` a 1st cmdline arg PM List of all permutations FI Filter on this function: _NIg Permutation not in cmdline args @: First element of resulting list (with : meta-operator to lower precedence) Autoprint ``` [Answer] # [Python 3](https://docs.python.org/3/), 87 bytes I believe this is the *only* submission so far that uses neither a permutation builtin nor random shuffle/sort. Even though it's longer, I think the algorithm is pretty neat. ``` lambda L:[p for s in L for i,c in enumerate(s)for p in[c+s[:i]+s[i+1:]]if~-(p in L)][0] ``` [Try it online!](https://tio.run/##JYu9CsMgFEZf5eKkJIWGTgodsucN7B1savBCY/zr0CWvbk26fJzvwAnf4jZ/q@P9Ud9mfb4MTEoHWLYEGcjDdCL183Gs/6w2mWJ5FocOTeq5y1oRtqVuUIi07BcezlagvmINiXzhI9fMRSkl64FJJ@MfomsGhag/ "Python 3 – Try It Online") ### Explanation What we're doing is basically this: ``` def unique_anagram(string_list): for string in string_list: for i, char in enumerate(string): # Move the character to the beginning of the string permutation = char + string[:i] + string[i+1:] if permutation not in string_list: return permutation ``` Here's a proof that it works: > > For a string `S`, define `front(S)` as the set of strings obtained by choosing one character from `S` and moving it to the front of `S`. For example, `front(ABCDE)` is `{ABCDE, BACDE, CABDE, DABCE, EABCD}`. > > > Now consider a list of anagrams `L`, such that `L` does not contain every possible anagram (as per the problem description). We wish to show that there exists a string `S` in `L` such that `front(S)` contains at least one anagram `S'` that is not in `L`. > > > Suppose, by way of contradiction, that for every string `S` in `L`, every string in `front(S)` is also in `L`. Observe that we can generate an arbitrary permutation of any string via a series of "fronting" moves. For example, to get > > > > ``` > ABCDE -> BAEDC > > ``` > > we can do > > > > ``` > ABCDE -> CABDE -> DCABE -> EDCAB -> AEDCB -> BAEDC > > ``` > > We have assumed that for each `S` in `L`, every `S'` in `front(S)` is also in `L`. This also means that every `S''` in `front(S')` is in `L`, and so forth. Therefore, if `S` is in `L`, every permutation of `S` is also in `L`. Then `L` must be a complete set of anagrams, a contradiction. > > > So, since we are guaranteed that there is at least one permutation *not* in `L`, there must exist a string `S` in `L` for which some `S'` in `front(S)` is not in `L`. QED. > > > The code iterates over `front(S)` for each `S` in `L` and selects an `S'` which is not in `L`. By the above result, there will be at least one `S'` that qualifies. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~116~~ 96 bytes ``` s=>{for(var g="";;)if(s.All(z=>z!=(g=string.Concat(s[0].OrderBy(t=>Guid.NewGuid())))))return g;} ``` My golfing skills have certainly gotten better since when I first posted this! [Try it online!](https://tio.run/##Nc1RS8MwEADg9/6K2JelkJWmwYdQU1BREUTBCT5se7imaRsYqU1SxZX@9ppteA93B/fdnXRr6fTiPHgt0eNo5I3zVpt2uyfo0pWoEYsT5dT0Fn@DRa2I46JIdINdens44KMoj1cCt@Li0/veSPDYbbN9@mZrZe9@sRfl06jr9FX9nCpOzmGVH61BbTEvRRTOK5Dd@QUgbdCzSd8V1B/9gwkL6ebroD1e7cwqSaIp@rTaqxdtFI6njKyvs1mUOz/ROSZAGgz/ngSeFNG8QBVBBQRCpTkjlOUkZ5QwmhOW06gbOOeEd3wIeeg4D1rW6kShYorK@uxUXYEkYQJU5ewP "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] ## JavaScript (ES7), 172 bytes ``` f=(a,s=a[0],b=[...s],k=b.findIndex((e,i)=>s[i-1]>e))=>a.includes(s)?f(a,(~k?(t=b[k],b[k]=b[l=a.findIndex(e=>e>t)],b[l]=t,b.map((e,i)=>i<k?b[k+~i]:e)):b.reverse()).join``):s ``` Find the first lexicographic permutation of the first element of the array that's not contained in the array. [Answer] # [Kotlin](https://kotlinlang.org), 104 bytes ``` {var r="" do{r=it[0].map{it to Math.random()}.sortedBy{(_,b)->b}.fold("",{a,(f)->a+f})}while(r in it) r} ``` ## Beautified ``` { var r = "" do { r = it[0].map { it to Math.random() } .sortedBy { (_, b) -> b } .fold("", { a, (f) -> a + f }) } while (r in it) r } ``` ## Test ``` var ana: (List<String>) -> String = {var r="" do{r=it[0].map{it to Math.random()}.sortedBy{(_,b)->b}.fold("",{a,(f)->a+f})}while(r in it) r} fun main(args: Array<String>) { println(ana(listOf("ab"))) } ``` [Answer] # C++, 169 bytes ``` #import<set> #import<string> #import<algorithm> using S=std::string;S f(std::set<S>l){S s=*l.begin();for(;l.count(s);)std::next_permutation(s.begin(),s.end());return s;} ``` [Try it online!](https://tio.run/##jVDLboMwELzzFRa94CqJZJwciAk/wbVSZcwGLIEh9iJVivLtqU1evSSNL7tjz87MWo3jslHqfP7Q/ThYzB1gEd0BWm2aB5ZdM1iNbV9Ek/MvpNw5rLfbC0@UZJ9cMGBeFh09lsTtPrtVBY02CRX7wSaiW6lhMpg4KujMNvCD3yPYfkKJejCJuw0s3ApMnVAqLOBkDXHi5JMa1U01kFwP3hikT6MNkl6GkegYEX/uMf7kKwiCQ0Z25BjLKj6JB9MnQpLnPv9MoaGPv0wson/U0quajBckli9V0/dV@azKUh5UGU9DSTkLhbMZ8ZS9sOLvW61nq/aQZVnQzdrscGkOrb95brF@32Jz/SNVw3UlWXFgqr5tAnUlVeg9RTLwnOe@Gyqi0/kX) [Answer] # Scala, 50 bytes ``` (l:Seq[String])=>(l(0).permutations.toSet--l).head ``` [Try it online!](https://scastie.scala-lang.org/t4fIxRUSQ4a5eyXseLkE9Q) ### Explanation ``` l(0) // Take the first anagram permutations // Built-in to get all permutations toSet // Convert to set, required for -- function -- l // Remove the original anagrams head // Take a random element from the set ``` [Answer] # **R, 89 bytes** ``` x=scan(,'');repeat{a=paste(sample(el(strsplit(x[1],''))),collapse='');if(!a%in%x)break};a ``` Repeatedly sample the letters from the first entry (as they should be anagrams of each other) and stop when one of those samples is not in the original list. [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` ←-⁰P←⁰ ``` [Try it online!](https://tio.run/##yygtzv7//1HbBN1HjRsCgDSQ@v//f7RSYlKiko5SYmKSUiwA "Husk – Try It Online") [Answer] # [PHP](https://php.net/), 70 bytes ``` $j=1;while($j){$g=str_shuffle($_GET[0]);$j=in_array($g,$_GET);}echo$g; ``` Run on a webserver, inputting 0 indexed get values or [Try it online!](https://tio.run/##ZcxLCsMgAATQfU4hRYgBF1VXYkMPkpagxk9CyT@UEnJ2q2RVuhuGNzP6Mdzuox8zu/V6bYceWARrZ9ZiD7AriXj79mUQ7IodunJZ53rxm7WpSqq6PgsRXdvXcp7lB0GHz7k4jPYDdCIcmUUVoQwDwigGlBEMGImJURLXiV0e/UUklvuJc55jkHPPpzNMPjZ/UCrdmPiaiFTMEN3QlOOpaZTUKUciiUnmrLWSP0fhCw "PHP – Try It Online") ## Ungolfed ``` $j=1; //set truty value while($j){ $g=str_shuffle($_GET[0]); //shuffle the first anagram of the set $j=in_array($g,$_GET); //see if in the set, if false, the loop ends } echo $g; ``` [Answer] # PHP, ~~58~~ 55 bytes ``` while(in_array($s=str_shuffle($argv[1]),$argv));echo$s; ``` non-deterministic; takes input from command line arguments Run with `php -r <code>` follwed by space separated words or [try it online](http://sandbox.onlinephpfunctions.com/code/8810dfdfbb823935adab14423024736e9a686c3c). [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 16 bytes ``` &\S@{!S@_[0]Ø_} ``` [Try it online!](https://tio.run/##TYy9CsIwFIX3PkUM4tTBJFMEoeAuQt1iKLfJrXGRxmQT38P38cFi4m/vcs79OHwQIxiHaSCrdVoc2uY6a5tOLfXj3t3SFtEGNR9Hc9TV7nI6xz2GuIGAQQ01URXJpyj0VNe/DrQmFKaMcVEYE7wEF6yEYK9PcPYfOi@lLFQ66d/Fu0wmdmPxo4NeIDP2a0Hbgyk9T4Bh3uhK6/QE "Attache – Try It Online") ## Explanation ``` &\S@{!S@_[0]Ø_} { } lambda (input: `_`) _[0] first element of the given array @ pass to: ! on each permutation: S cast to string Ø without any member of _ the input this gives all anagrams not in the input @ then &\S "first string element" & spread input array over each individual arguments \ tale first argument S as a string ``` ## Alternatives **17 bytes**: `{&\S! !S@_[0]Ø_}` **18 bytes**: `{&\S! !Id@_[0]Ø_}` **19 bytes**: `{&\S!(!Id)@_[0]Ø_}` **26 bytes**: `{&\S!Permutations@_[0]Ø_}` **26 bytes**: `{&\S!Permutations[_@0]Ø_}` **26 bytes**: `{(Permutations[_@0]Ø_)@0}` **26 bytes**: `&\S##~`Ø#Permutations@&\S` **27 bytes**: `Last@{Permutations[_@0]Ø_}` **27 bytes**: ``@&0@{Permutations[_@0]Ø_}` **28 bytes**: `Last##~`Ø#Permutations@&{_}` **28 bytes**: `Last##~`Ø#Permutations@Last` **28 bytes**: `First@{Permutations[_@0]Ø_}` **30 bytes**: `{NestWhile[Shuffle,`in&_,_@0]}` **33 bytes**: `{If[(q.=Shuffle[_@0])in _,$@_,q]}` **33 bytes**: `{q.=Shuffle[_@0]If[q in _,$@_,q]}` **34 bytes**: `{If[Has[_,q.=Shuffle[_@0]],$@_,q]}` [Answer] # [J](http://jsoftware.com/), 25 bytes ``` ((A.~i.@!@#)@{.@:>){.@-.> ``` The input is a list of boxed strings - I felt it was fair like this and not to declare the lists of strings explicitly as 4 8$'abcde123', 'ab3e1cd2', '321edbac', 'bcda1e23'. I don't like the @ mess in my code, but there are a lot of serialized verbs this time. How it works: ``` > - unboxes the strings ( ) - left verb of the fork as follows: @{.@:> - unbox and take the first string ( ) - finds all permutations of the first string i.@!@# - a list 0 .. the factorial of the length of the 1st string A.~ - anagram index, all permutations {.@-. - remove the inital strings and take the first of the remaining ``` [Try it online!](https://tio.run/##TYzLCsIwEEX3@YpRF2lAg5Os0mKJn5In0Y2ULsX@epyoxS5m7oPDvdc8w6WHM9DVrrvK5Sbtzh6EfUrbj4L@SY5VsL0EnhvK4QivHvLMWArlARmGhTvP10Te8YFk26HSrUOtmiiNTTR@klb4B8tkjGmtKWb6mqlQs1kPMf3mnNcJQ1xXUvQuNE@Iw0RMfQM "J – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` нœIмà ``` [Try it online!](https://tio.run/##MzBNTDJM/f//wt6jkz0v7Dm84P//aPXEpER1HQX1xMQk9VgA "05AB1E – Try It Online") # Explanation ``` нœIмà full program with implicit input i н push first element of i œ push all permutations I push input i м remove all elements of i from the permutations à extract greatest element and print implicitly ``` Pretty much the same answer that @ThePirateBay found. [Answer] # JavaScript, 87 bytes ``` a=>eval('for(s=[...a[0]];(a+[]).includes(k=s.sort(a=>~-(Math.random``*3)).join``););k') ``` [Try it online!](https://tio.run/##NU/LjsMgDLz3R4DdFpVwQlH6B/sFLBIOECV9QAK0ve2vZ93XxTNje0b2EW5QXJ7muovJh3XoVugO4QZnSoaUaek05xz03piWwrc2jE/Rna8@FHrqCi8pV4qOvx39gTryDNGni7VfkjF@TFO0lrWsPRG2zjm5UNBSfbpWfs9TDVRvNIGemO0TgWwJfKRoJEohG6yNFFileHDZiNfCuCilsKFGtTxxGVG/o5wPrwDoZRDOv53B9@CQ4hxEwAWzMfwC8@OHgcLn6N9o2foP) This answer is based (although heavily modified) on [Imme's answer](https://codegolf.stackexchange.com/a/148019/72349). He suggested in a [comment](https://codegolf.stackexchange.com/questions/147975/output-an-anagram-no-not-that-one#comment361913_148019) that this should be a different answer. The problem with the old approach is because `sort` is completely implementation-dependent. The standard doesn't guarantee the order of calling the sort function, therefore theoretically it may never end for the first or the second test case. This approach is few bytes longer, but it guarantee that it will finish in constrained time, even if `Math.random` never returns `.5`. [Answer] # [CJam](https://sourceforge.net/p/cjam), 11 bytes ``` q~_0=m!\m0= ``` [Try it online!](https://tio.run/##S85KzP3/v7Au3sA2VzEm18D2//9oJUMjYyUFJUNjIyBpZGwIJI0NQWxjI0OlWAA "CJam – Try It Online") ## Explanation ``` q~ e# Read input and evaluate: ["123" "132" "231" "312" "321"] _ e# Duplicate: ["123" "132" "231" "312" "321"] ["123" "132" "231" "312" "321"] 0= e# First: ["123" "132" "231" "312" "321"] "123" m! e# Permutations: ["123" "132" "231" "312" "321"] ["123" "132" "213" "231" "312" "321"] \ e# Swap: ["123" "132" "213" "231" "312" "321"] ["123" "132" "231" "312" "321"] m0 e# Subtract, push 0: ["213"] 0 e# (m is used instead of - when in front of a digit) = e# Get item: "213" ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 42 bytes ``` {(.[0],*.comb.pick(*).join...*∉$_)[*-1]} ``` [Try it online!](https://tio.run/##TYxBCsIwFET3nuIvxLShBn8@CEHtRUqRJE1pq7Wtroq412t6kZgWFDczvBlmenc9b307wqqEg79HItvkCRe2a43oa3uKeCyarr4IIfj7@Voe44yvMX/4mx6hjPbapPFuMQME0KBD8g0yhpJYAgxJTiYJJyOciSSy/LetBqUUqEoNQYdKqfTv1hYuPIE25NAWEsLUFUZbCI1GJyn1Hw "Perl 6 – Try It Online") Randomly shuffles the first string of the input until it is not an element of the input. ### Explanation: ``` {(.[0],*.comb.pick(*).join...*∉$_)[*-1]} { } # Anonymous code block ( ... ) # Create a sequence .[0], # The first element is the first element of the input *.comb.pick(*).join # Each element is the previous one shuffled *∉$_ # Until it is not in the input [*-1] # Return the last element ``` ]
[Question] [ Write the shortest program that prints, in order, a complete list of iPhone iterations, according to [this site](https://www.theiphonewiki.com/wiki/List_of_iPhones): ``` iPhone iPhone 3G iPhone 3GS iPhone 4 iPhone 4S iPhone 5 iPhone 5c iPhone 5s iPhone 6 iPhone 6 Plus iPhone 6s iPhone 6s Plus iPhone SE iPhone 7 iPhone 7 Plus iPhone 8 iPhone 8 Plus iPhone X iPhone XR iPhone XS iPhone XS Max iPhone 11 iPhone 11 Pro iPhone 11 Pro Max ``` Output should be printed exactly as specified, though trailing newlines are allowed (as well as additional whitespace at the end of each line). This is code golf, so the shortest answer in bytes, per language, wins. [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~77~~ ~~76~~ 73 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ¶+∔iF╴qV1┼#│»lN↶:╋KARV/+├6<∔ZK@≠≡Ze3h}s×⁴*⁵GZX─?ep┼Q‟-s{iPhone ×|∙ Plus╋] ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JUI2JXVGRjBCJXUyMjE0JXVGRjQ5JXVGRjI2JXUyNTc0cVYxJXUyNTNDJTIzJXUyNTAyJUJCJXVGRjRDTiV1MjFCNiUzQSV1MjU0QksldUZGMjFSViV1RkYwRiV1RkYwQiV1MjUxQzYlM0MldTIyMTRaSyV1RkYyMCV1MjI2MCV1MjI2MSV1RkYzQSV1RkY0NSV1RkYxMyV1RkY0OCU3RHMlRDcldTIwNzQldUZGMEEldTIwNzVHWlgldTI1MDAlM0ZlcCV1MjUzQ1EldTIwMUYtJXVGRjUzJXVGRjVCaVBob25lJTIwJUQ3JTdDJXUyMjE5JTIwUGx1cyV1MjU0QiV1RkYzRA__,v=8) `-3G-3GS-4-4S-5-5c-5s-6-6|-6s-6s|-SE-7-7|-8-8|-X-XR-XS-XS Max-11-11 Pro-11 Pro Max` compressed, split on `-`, `|` replaced with `' Plus'`, and `'iPhone '` prepended. [Answer] # [Zsh](https://www.zsh.org/), ~~107~~ 105 bytes *-2 bytes due to leniency on trailing spaces* ``` print -l iPhone\ {,{3G,4}{,S},5{,c,s},6{,s}{,\ Plus},SE,{7,8}{,\ Plus},X{,R,S,S\ Max},11{,\ Pro{,\ Max}}} ``` ~~[Try it online!](https://tio.run/##qyrO@P@/oCgzr0RBN0chMyAjPy@1WidGobra2F3HpLZaJ7hWx7RaJ1mnuFbHrBpIgiQDckqB3GBXnWpzHQskkYhqnSCdYJ3gGAXfxIpaHUNDsFRRPogCiQDB//8A "Zsh – Try It Online")~~ [Try it online!](https://tio.run/##qyrO@P@/oCgzr0RBN0chMyAjPy81RqFap9rYXcektlonuFbHtFonWae4VsesGkhW68QoBOSUArnBrjrV5joWSCIR1TpBOsE6wTEKvokVtTqGhmCponwQBRKprf3/HwA "Zsh – Try It Online") A long brace expansion. Bash/sh need `printf %s\\n` instead for 4 extra bytes. [Answer] # JavaScript (ES6), ~~137 136~~ 135 bytes ``` _=>"iPhone3G9GS39S33c9s3303s9s01SE3903301X1XR1XS1XS Max22 Pro2 Pro Max".replace(/\d/g,n=>[" Plus",k=` iPhone `,k+11,k+i][n]||k+i++,i=3) ``` [Try it online!](https://tio.run/##JY2xDoIwFEV3v6LpBKEC5U0dymaYTIhdSJBoUwoipCVUjQP/jlWTm5N7pnOXL@nUMsyPvbGt3jq@XXiOh/JmjYaCFQKYAFDMAaTgmEupOABLvdGKVidaCT90lO8sQ@Vif/gqjhc9T1LpIDm3SU8Mz2uMyunpMBn5dfcvoCsZI0o9hqY2zbr6E0Vk4BBuyhpnJx1Ptg@6IAy3Dw "JavaScript (Node.js) – Try It Online") ### How? The numeric version is stored in a counter \$i\$ initialized to \$3\$. Below are the digits used for the compression: * \$0\$: `" Plus"` * \$1\$: `"\n"` + `"iPhone "` * \$2\$: `"\n"` + `"iPhone 11"` * \$3\$: `"\n"` + `"iPhone "` + \$i\$ * \$9\$: same as \$3\$, but \$i\$ is incremented afterwards Resulting in: ``` "iPhone" --> "iPhone" "3G" --> "iPhone 3G" "9GS" --> "iPhone 3GS" (i++) "3" --> "iPhone 4" "9S" --> "iPhone 4S" (i++) "3" --> "iPhone 5" "3c" --> "iPhone 5c" "9s" --> "iPhone 5s" (i++) "3" --> "iPhone 6" "30" --> "iPhone 6 Plus" "3s" --> "iPhone 6s" "9s0" --> "iPhone 6s Plus" (i++) "1SE" --> "iPhone SE" "3" --> "iPhone 7" "90" --> "iPhone 7 Plus" (i++) "3" --> "iPhone 8" "30" --> "iPhone 8 Plus" "1X" --> "iPhone X" "1XR" --> "iPhone XR" "1XS" --> "iPhone XS" "1XS Max" --> "iPhone XS Max" "2" --> "iPhone 11" "2 Pro" --> "iPhone 11 Pro" "2 Pro Max" --> "iPhone 11 Pro Max" ``` [Answer] # [///](https://esolangs.org/wiki////), 108 bytes Naive compression, simply replacing `#` with `\niPhone`. (Further compression does not work by the way.) ``` /#/ iPhone //@/ Plus/iPhone#3G#3GS#4#4S#5#5c#5s#6#6@#6s#6s@#SE#7#7@#8#8@#X#XR#XS#XS Max#11#11 Pro#11 Pro Max ``` [Try it online!](https://tio.run/##LchBCoMwEEDRfU8R@AcYpCa6nE1xVQjNJlsRwYJUcCj09jFS4cGHb@toy2ylCHJ7x2X7zE5ExcX1a/If3Icq0dImPH7CG4GghFpT0oOOTunplUx@kVPlnuOPpqlc3Lcr5yzlAA "/// – Try It Online") # [///](https://esolangs.org/wiki////), 103 bytes This works only if preceding newlines are allowed. ``` /#/ iPhone //@/ Plus/##3G#3GS#4#4S#5#5c#5s#6#6@#6s#6s@#SE#7#7@#8#8@#X#XR#XS#XS Max#11#11 Pro#11 Pro Max ``` [Try it online!](https://tio.run/##LchBCoMwEEDRfU8R@AcYRBNdzkZcFUKzyVaKoCAKDoXePqZQePDh2z7bulgpgjy2uJ7H4kRUXNw/JtBOVaKjS3j8G28EghJqTUkjPb0yMCiZ/CKnyj3nL01TuXid//xmKTc "/// – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 83 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “Ø^ÞṠṠẠ'Ḣߥ»=⁶œṗ;11;“RcGEs436X578 ”µ“ƈ`¿øÐ⁽ḞÆCḊḋɲÑF×GÇz ⁸¦MƊ‘ד£¿Þ瑦5ŻṃµṚ“®Ɲ,»,K)Y ``` **[Try it online!](https://tio.run/##y0rNyan8//9Rw5zDM@IOz3u4cwEI7Vqg/nDHosPzDy09tNv2UeO2o5Mf7pxubWhoDVQXlOzuWmxibBZham6h8Khh7qGtQMFjHQmH9h/ecXjCo8a9D3fMO9zm/HBH18Md3Sc3HZ7odni6@@H2KoVHjTsOLfM91vWoYcbh6UA9hxYDtcw7vBzIP7TM9OjuhzubD219uHMWSGrdsbk6h3breGtG/v8PAA "Jelly – Try It Online")** ### How? Uses eighteen non-"iPhone " parts and constructs each line from a big-endian number in base eighteen, then prefixes each with "iPhone " and joins with newline characters. The parts used are (comma separated): `Max, Plus, Pro, ,S,R,c,G,E,X,s,3,4,5,6,7,8,11` The mapping to the eighteen digits was chosen so that: 1. the space character is a zero - allowing a single byte prepend-zero to make the first line 2. no two digit "numbers" are greater than 255 - allowing encoding with code-page indices 3. the three digit "numbers" (`S,G,3`; `Plus,s,6`; `Max,S,X`; and `Max, Pro,11`) are all exact multiples of five (and less than 1275) - allowing encoding with code-page indices, with post multiplication to acquire their full value 4. the three words are adjacent and do not occupy digit one - allowing compression with a split-before spaces application One such (1-indexed) ordering is: `S, Max, Plus, Pro,11,R,c,G,E,s,4,3,6,X,5,7,8,` As such the code works like so: ``` “...»=⁶œṗ;11;“...”µ“...‘ד£¿Þ瑦5ŻṃµṚ“®Ɲ,»,K)Y - Main Link: no arguments “...» - string = "S"+" Max"+" Plus"+" Pro" ⁶ - space character = - equals? (vectorises) œṗ - partition before truthy indices ;11 - concatenate 11 “...” - list of characters "RcGEs436X578 " ; - concatenate - giving our "digits" [1,2,...,17,0] µ - start a new monadic chain “...‘ - list of code-page indices = [156, 96, 11, 29, 15, 141, 195, 13, 67, 193, 233, 163, 16, 70, 17, 71, 14, 122, 32, 136, 5, 77, 145] ¦ - sparse application... - ...to indices: “£¿Þç‘ - code-page indices = [2, 11, 20, 23] × 5 - ...do: multiply by five -> [156, 480, 11, 29, 15, 141, 195, 13, 67, 193, 1165, 163, 16, 70, 17, 71, 14, 122, 32, 680, 5, 77, 725] Ż - prepend a zero ṃ - base-decompress (convert to base-18 using the "digits") - e.g. 680 -> [2, 1, 14] -> [" Max",'S','X'] µ ) - for each: Ṛ - reverse it (e.g. [" Max",'S','X'] -> ['X','S'," Max"]) “®Ɲ,» - string = "iPhone" , - pair K - join with a space character Y - join with newline characters - implicit, smashing print ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 81 bytes ``` 11”3G3GS44S55c5s66‰´6s6s‰´SE77‰´88‰´XXRXSXSî£ÿÿˆ×ÿˆ×•ΛΩ&°ŽäÞнã•0šTª£'i”ƒ¿ ”«ì» ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f0PBRw1xjd2P3YBOTYFPTZNNiM7NHDRsObTErNisGM4Jdzc3BDAsLMBURERQRHBF8eN2hxYf3H95/uu3wdCgJFAEa9qhh0bnZ51aqHdpwdO/hJYfnXdh7GCi8yODowpBDqw4tVs8Eqjk26dB@BSB9aPXhNYd2//8PAA "05AB1E – Try It Online") I dom't have time to re-analyze. # Original Solution, 178 bytes ``` 'i”ƒ¿”«D… 3G«D'S«.ÀD.Á„ 4«D'S«.ÀD.Á„ 5«Ð'c«s's«.ÀD.Á„ 6«D" Plus"D.Á«sDŠ's«D.À«.ÀD.Á… SE«.ÀD.Á„ 7«D" Plus"D.Á«.À.ÀD.Á„ 8«DŠs«.ÀD.Á„ X«Ð'R«s'S«D" Max"D.Á«.À.ÀD.Á… 11«DŠ" Pro"«DŠs«» ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fPfNRw9xjkw7tB1KHVrs8alimYOwOZKgHH1qtd7jBRe9w46OGeQommEKmh1YfnqCefGh1sXoxioQZUK2SQkBOabESSAiowOXoApAaIK8BSeUyhWBXFI3m6BqBckjSFkDpowtQ7YoAOyII5IhgsG7fxAosmpcpGBqCdQONL8pXghl0aPf//wA "05AB1E – Try It Online") ## Explanation First, I push the string "iPhone" by using `'i”ƒ¿”«`. I duplicate that, and push " 3G", and concatenate them to get "iPhone 3G". After that, I use `.ÀD.Á` to get "iPhone" at the top of the stack, etc. When I get to iPhone 6, I put " Plus" at the bottom of the stack and save it for iPhone 6S Plus. I don't save it for iPhone 7 and 8 Plus, because I'm not sure if it will golf off some bytes, and I'd already spent enough time figuring it out. I **did** save " Max" though, and I'm pretty sure now that saving " Plus" would've shaved off more bytes. However, now that the program is already completed, it's unclear how I do that. At the end, I concatenate the whole stack together with newline delimiters, and implicit output happens. [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 82 bytes ``` 00000000: cb0c c8c8 cf4b e582 500a c6ee 0856 308c .....K..P....V0. 00000010: 6902 67c0 854c e18c 6438 ab18 c632 8333 i.g..L..d8...2.3 00000020: 1402 724a 11c2 482c 1489 6057 18cb 1cce ..rJ..H,..`W.... 00000030: 4051 6001 67a0 0847 c019 4170 5630 82a5 @Q`.g..G..ApV0.. 00000040: e09b 5801 e319 1a22 580a 0145 f9a8 3c90 ..X...."X..E..<. 00000050: 4a00 J. ``` [Try it online!](https://tio.run/##jc8/S4QxDAbw3U/x4Cwh6d@84qCDKKeDLup4bewdgoII9/lfU7zbzZDSkv76tB96/xz7w9e68rEuYZ0NpqawXeoYWQMyc4OVMcCaCyKrATTrgehpri9MZ3@CuFEWDijVGJqTYYjPlxQVrYu7JQZojBH4oD3RI9G7uhEoHo3ghiQ3akgNIhaQNJif6YLCucLFDjEbM8fPhuj@gmj7OqMcjehG4iw@z95qYw@fKoxlQZLKyCV6wNAycP28nUnuiG6@/SsnI7kxeOnI6saIflNaCHPbwJIydktTRFt45nibz597vyW6Ohl55mjsA/@oDa3rLw "Bubblegum – Try It Online") # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 87 bytes Written by @FryAmTheEggman, so I don't take credit for this. ``` 00000000: e001 0700 4f5d 0034 9409 072b 9ed9 334a ....O].4...+..3J 00000010: 2d4f 957c 30d4 5ae8 8bc7 1c12 f267 7c2c -O.|0.Z......g|, 00000020: 47df 6d0b 6d45 b174 dcab 2da7 e97a ed9f G.m.mE.t..-..z.. 00000030: e772 808d f6c6 d93e c423 2b3c 378e 0a13 .r.....>.#+<7... 00000040: c57b 7a72 436d a362 6818 88d0 a495 4466 .{zrCm.bh.....Df 00000050: e336 dcfb ac00 00 .6..... ``` [Try it online!](https://tio.run/##ddA/T8MwEAXwnU/xJMbS08W@@GKEWAAhsXRHYvCfuB3IUtGl9LuHa4jYeLJiyZJ/fpd8yvlz3J@meeY19xiZO7AyQ1pfwewFUTjamcuIY43wXhJAlt0HiW0bIv928yt0ZrgqDbHXAs9V0KdxwJCLoiudQ3NBocUVYLujC9M7Ldlf7lbDmSFaG0LlbB/pkTsV1JKy4UkxRk2wLg14pYmmF/oi2hKdiVbDX2dRdRh4qGihBNToRxRxHi5766bDCE6dt1mOS4NHut08KP0ZYkbpNUOTQeJDRfLBIQydDTRURpLYQyQEM77Px6eJ8mGhnttq9Nce3tvrpWWkYj/W1j@hsFye5x8 "Bubblegum – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), ~~118~~ 114 bytes ``` $_="3G3GS44S55c5s66-6s6s-SE77-88-XXRXSXS Max99Pro9Pro Max";s/-/ Plus/g;s/^|(\d|X|SE)/\niPhone $1/g;s/9/11 /g;print ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lbJ2N3YPdjEJNjUNNm02MxM16zYrFg32NXcXNfCQjciIigiOCJYwTexwtIyoCgfhEEcJetifV19hYCc0mL9dCA7rkYjJqUmoibYVVM/Ji8zICM/L1VBxRAsZ6lvaKgAZBUUZeaV/P8PAA "Perl 5 – Try It Online") This code is rather simple: in the string `$_`, it replaces "-" with " Plus". Then it cuts the string at every digit, "X" or "SE" and prefixes the matching part with a line break and "iPhone ". Finally, it replaces "9" by "11 ". Attempting to replace " Max" or " Pro" with shorter symbols would not bring any benefits because the substitution would cost more characters. Thanks to Weizel who allowed me to save 4 bytes by replacing the first "iPhone" in the string. I assumed that the final newline was not necessary. [Answer] # [Keg](https://github.com/JonoCode9374/Keg), ~~129~~ 127 bytes ``` ‘1⊙‘®p`iPhone `:& ⑻3G ⑻3GS ⑻4 ⑻4S ⑻5 ⑻5c ⑻5s ⑻6 ⑻6 ©p ⑻6s ⑻6s ©p ⑻SE ⑻7 ⑻7 ©p ⑻8 ⑻8 ©p ⑻X ⑻XR ⑻XS ⑻XS Max ⑻11 ⑻11 Pro ⑻11 “∂⬭q≥ ``` [Try it online!](https://tio.run/##y05N////UcMMw0ddM4HUoXUFCZkBGfl5qQoJVmpcjybuNnaHkMEgygRMgJmmYCIZTBaDSDMwoXBoZQGYARErhvGDXUGkOZiAiVmACRgvAkwEgclgCKngm1gBYhkaQkiFgKJ8KOtRw5xHHU2P1qwtfNS59P9/AA "Keg – Try It Online") How's that for a submission! Simply using the register and a little bit of string compression + variables gives a kind of competitive answer. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 91 bytes ``` ¶3G¶3GS¶4¶4S¶5¶5c¶5s¶6=¶6s=¶SE¶7=¶8=¶X¶XR¶XS!¶11¶11 Pro! %(`^ iPhone ! ¶$` Max = ¶$` Plus ``` [Try it online!](https://tio.run/##K0otycxL/P@f69A2Y3cQDj60zQSIgJQpECUDcfGhbWa2QFwMJIJdD20zB9IWQBwBREFAHKx4aJuhIQgrBBTlK3KpaiTEcWUGZOTnpSpwKQINVklQ8E2s4LKFMANySov//wcA "Retina 0.8.2 – Try It Online") Includes additional whitespace on the first line Explanation: ``` ¶3G¶3GS¶4¶4S¶5¶5c¶5s¶6=¶6s=¶SE¶7=¶8=¶X¶XR¶XS!¶11¶11 Pro! ``` Insert the names of the models, but without `iPhone`, `Max` or `Plus`, which get added later. ``` %(` ``` Operate on each line individually. ``` ^ iPhone ``` Prefix `iPhone` to the line. ``` ! ¶$` Max ``` If the line has a `!`, then duplicate it and append `Max` to the duplicate. ``` = ¶$` Plus ``` If the line has a `=`, then duplicate it and append `Plus` to the duplicate. [Answer] # [Bash](https://www.gnu.org/software/bash/), 109 bytes ``` printf %s\\n iPhone\ {,{3G,4}{,S},5{,c,s},6{,s}{,\ Plus},SE,{7,8}{,\ Plus},X{,R,S,S\ Max},11{,\ Pro{,\ Max}}} ``` Similar to the Zsh solution but some slight changes and some output leniency. [Try it online!](https://tio.run/##S0oszvj/v6AoM68kTUG1OCYmTyEzICM/LzVGoVqn2thdx6S2Wie4Vse0WidZp7hWx6waSFbrxCgE5JQCucGuOtXmOhZIIhHVOkE6wTrBMQq@iRW1OoaGYKmifBAFEqmt/f8fAA "Bash – Try It Online") [Answer] # Swift, 152 bytes ``` ",3G,3GS,4,4S,5,5c,5s,6,6 Plus,6s,6s Plus,SE,7,7 Plus,8,8 Plus,X,XR,XS,XS Max,11,11 Pro,11 Pro Max".split(separator: ",").forEach{print("iPhone \($0)")} ``` Being related to iPhones, this needs an answer in Swift. Unfortunately Swift is woooordy. The most boring route is the shortest :/ [Try it online](https://repl.it/repls/WeirdTurbulentData) [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 5007 bytes ``` ((((((<(((((((((<((((((((((<((((((((<(((((((((<((((((((<(((((((((<(((((((<(<((((((((<((((((((<((((<(((((((<(<(((((((<(<((((<((((((<((<((((((<(<((((((<(<(((<<((<((<((<(((((<((<((((<((((((<(<(<((((<((<((((((<((<((<((<(((((<(<(<(((((((((((((<((<(<(<<((((((<((<(((<((((((()(()(()()()){}){}){}){}){})[()(()(()()()()[]){}){}])[((()()()[]){}){}])>((((()[]){}){}){})()(()(()(()([]){}){}){}){})()()())[(()(()()[]){}){}])>(((()[]){}){})()([]){}))>(()()([])({}){})(()([]){})({}){})()(()()()()){})())[()(()()()){}])[(((()()()){}){}){}])()()()()()()()()()[])>((()()()()()){})>((()([]){})({}){})()()())>((([]){}){})[(()()()[]){}])>(()(()()[]){}))[()((()()()()){}){}])>(()(([]){}){})()(()()()()){})())[()(()()()){}])[(((()()()){}){}){}])()(((()()()){}){}){})[()()([])({}){}])()()()()()()()[]))[()((()()()()){}){}])()((()((()()()()){}){}){}){})()(()()()()){})())[()(()()()){}])>((()[]){})()(((()()()){}){}){})>((()()()()()){})(()()()()()()()()()()()()()[]){})>(()(()()()()()[]){})[((()()()()()){}){}])[[]])()()()()()[])()()()()())[()()()()()()()()[]])>(()(()[]){})()(()()()()){})())>(([]){})[(((()()()){}){}){}])()(((()()()){}){}){})>((()()()()()){})()(((()(()()()()){}){}){}){})()()()()())>((((()()()()){}){}){})()()()()()()()()()()[])()(()()()()){})())[()(()()()){}])[(((()()()){}){}){}])()(((()()()){}){}){})>((()()()()()){})()()()()()()[])(()()()){})>((((()()()()){}){}){})[])()(()()()()){})())[()(()()()){}])>(()()()()()()()[])()(((()()()){}){}){})>((()()()()()){})()()[])>((((()()()()){}){}){})()((()((()()()()){}){}){}){})()(()()()()){})())[()(()()()){}])[(((()()()){}){}){}])()(((()()()){}){}){})>((()()()()()){})()(((()((()()()){}){}){}){}){})()())[()(()()()()){}])[((()(()()()){}){}){}])>((((()()()()){}){}){})(((()()()){}){}){})[(((()()()){}){}){}])>(()()()()()()()()()[])()(()()()()){})())[()(()()()){}])[(((()()()){}){}){}])()(((()()()){}){}){})>((()()()()()){})(()(()(()()()()()){}){}){})[(((()()()){}){}){}])>([])()(()()()()){})())>([])[(((()()()){}){}){}])()(((()()()){}){}){})>((()()()()()){})>(()()()()()()()[])()())[()(()()()()){}])[((()(()()()){}){}){}])>((((()()()()){}){}){})()(()(()()()()()){}){})>((((()()()()){}){}){})()((()((()()()()){}){}){}){})()(()()()()){})())[()(()()()){}])[(((()()()){}){}){}])()(((()()()){}){}){})>((()()()()()){})()((()(()()()()()){}){}){})>((((()()()()){}){}){})()((()((()()()()){}){}){}){})()(()()()()){})())[()(()()()){}])[(((()()()){}){}){}])()(((()()()){}){}){})>((()()()()()){})()(()((()(()()()){}){}){}){})(()(()()()){}){})>((((()()()()){}){}){})()((()((()()()()){}){}){}){})()(()()()()){})())[()(()()()){}])[(((()()()){}){}){}])()(((()()()){}){}){})>((()()()()()){})()(((()((()()()){}){}){}){}){})()())[()(()()()()){}])[((()(()()()){}){}){}])>((((()()()()){}){}){})()(()(((()()()()()){}){}){}){})>((()(()((()()()){}){}){}){})[(()(()()()()()){}){}])()((()((()()()()){}){}){}){})()(()()()()){})())[()(()()()){}])[(((()()()){}){}){}])()(((()()()){}){}){})>((()()()()()){})()(((()((()()()){}){}){}){}){})>((()(()((()()()){}){}){}){})[(()(()()()()()){}){}])()((()((()()()()){}){}){}){})()(()()()()){})())[()(()()()){}])[(((()()()){}){}){}])()(((()()()){}){}){})>((()()()()()){})()(((()((()()()){}){}){}){}){})()())[()(()()()()){}])[((()(()()()){}){}){}])>((((()()()()){}){}){})(()(()()()()()){}){})[(()(()()()()()){}){}])()((()((()()()()){}){}){}){})()(()()()()){})())[()(()()()){}])[(((()()()){}){}){}])()(((()()()){}){}){})>((()()()()()){})((()(()()()()()){}){}){})[(()(()()()()()){}){}])()((()((()()()()){}){}){}){})()(()()()()){})())[()(()()()){}])[(((()()()){}){}){}])()(((()()()){}){}){})>((()()()()()){})()(((()((()()()){}){}){}){}){})>(()((()((()()()){}){}){}){})[()((()()()()()){}){}])()((()((()()()()){}){}){}){})()(()()()()){})())[()(()()()){}])[(((()()()){}){}){}])()(((()()()){}){}){})>((()()()()()){})()(((()(()()()()()){}){}){}){})[(()(()(()()()()()){}){}){}])[()((()()()()()){}){}])()((()((()()()()){}){}){}){})()(()()()()){})())[()(()()()){}])[(((()()()){}){}){}])()(((()()()){}){}){})>((()()()()()){})()(()((()()()()()){}){}){})[()((()()()()()){}){}])()((()((()()()()){}){}){}){})()(()()()()){})())[()(()()()){}])[(((()()()){}){}){}])()(((()()()){}){}){})>((()()()()()){})()(((()(()()()()){}){}){}){})[()(()(()(()()()){}){}){}])[((()()()()()){}){}])()((()((()()()()){}){}){}){})()(()()()()){})())[()(()()()){}])[(((()()()){}){}){}])()(((()()()){}){}){})>((()()()()()){})(()((()()()()()){}){}){})[((()()()()()){}){}])()((()((()()()()){}){}){}){})()(()()()()){})())[()(()()()){}])[(((()()()){}){}){}])()(((()()()){}){}){})>((()()()()()){})()(((()(()()()()){}){}){}){})[((()()()){}){}])[((()()()()()){}){}])[()(()(()()()()){}){}])()((()((()()()()){}){}){}){})()(()()()()){})())[()(()()()){}])[(((()()()){}){}){}])()(((()()()){}){}){})>((()()()()()){})()((()(()(()()()){}){}){}){})[((()()()()()){}){}])[()(()(()()()()){}){}])()((()((()()()()){}){}){}){})()(()()()()){})())[()(()()()){}])[(((()()()){}){}){}])()(((()()()){}){}){})>((()()()()()){})()(()((()(()()()()()){}){}){}){})()(()()()()){})())[()(()()()){}])[(((()()()){}){}){}])()(((()()()){}){}){}) ``` [Try it online!](https://tio.run/##5VhBTsQwDLzzEvuwP7Aq8Q4rh@WAhEAcuCLeXtqkSZzEriJaoRS2PWRtx56ZOOl2nz7uL@@357f76zyD/xDETx7lIfWYSHGSHkCFg8SoGBBFJxWBIojqBNUEknxiAPnMYmaMwe1eLvz8Km6WTkB2we4WB9SmKSSLhvVOs5db2oNrrccxfZUnp0lTV8f2DTZX8oGsl5j4/IJagF0xdQjNxQEFymTBUJdbnasnwWWpiwuYM7@AR6bNQZLxz1g0Vj9RKOZanjqizVbZe/FNeQFVVI22AGhdIc0kuzAauU7jtWHnyukihtvsaYky3pLbFFemX/WWH6Z9psopO0kJMnQ5sU80xEWpch8oGHvwTKBy6EPDbkeeA816xrLqhyeU1UQ9bCta3LQ9Der0X2@R8tnQAVEF5M0HYOhNdVx4ndyQLagvwohQEYzfGo35P@71TSBtMRMkAwJrXeCGlesvcTnnmFf28HA67Bz3F2s@BLv5EIbkoh8KbD@F3ZBcEIwWGlt2461YkXysHWvKfSGxoXrDU1/7ym0wBiXrj5XLMMC9o@fE4g/zPN8evwE "Brain-Flak – Try It Online") Created using [this](https://tio.run/##7VTfa@NGEH7O/hWDSsjunXKXpLQPJhc4KL36Cu1DH0oxpqyssbWxtGt2VzEi5G9PZ1ayY/mSPLXQow2xLc2Pb775ZnY3Xayc/fbRNBvnI4QuCPq8Cxg9LlofjLO1aUyUlxfpTz0u9KJC@AD3D0KUuIQVWvQ64p@2bQr0kn5yqNCsqphDjXdYU/BFDq6NmzbS84@6Dqgm8A1MS9QQHbQB4beoF2v4KeWBsWFjPJZQdPDZwc/GrsSJWQ4YE9h4Y6PMIIM3Q4m3EGKqreiRHb2h56FUyj6kpqgGpFYm4DG2fnibjYLmKY8s8IF62Edm2d5@fWiecdljPc6fEeQtXO4ESXzn2WGhPvYAlt13um5Z9sZYKWdse6YWA5zva71ccw5UrXfDTSr7Bq5A2xJ0EUYoijrkd6SZwWzObGeZVC8Xv3y9bko/Deo03D9kcAryOZT378G8BpNDJu8fFE9fGqp5pRQsnQfDQ/XarlBe5ZCWYVD1lHw8wnkOa@xIxhotLcVzIydn0lqcDPr3b@KY6NV33@e81/Tfb/TRcaD1o7WV2nvdqYk46d8Jnben1oGPwoU4Yd67TpkpdYD0mzCekp@yef6ZHPabTS8Ngks8bTstmcpIt@tRZnbDrz3cK@d4n36o3a4HittL1QMLoTlKN0WpIUy@kKQ2IcpGb6TzZQ5B0fEUNB5IF08sjX3nUZdSiVsymtlkcn45F6I/89y@lre0AlqaxOueVuH6Rl3f0PeIonp8/B3PPIJ1TIzXwge@bmp3h@IP18Laui1Eus18W2NI@x8clA6m4iMs27qGhWvo8mvQxrMA20pHmJ41lGLsmhV0y4SzdW1d2rNInUZ2Blh61xBeB47gPazaTkzhtiXBttpauvSQwDtKrYgBQy4Ra5buk4tRQ6PXmNytLYl0JGZC/ELngKAc56/M3RCwGdlrIsDm0m3tyOFbC9q7lo84fUoM6FPoKGpfd@G7kSPojp5cWXQ4sqc@qKzBBFu1A6gg5YkhC0z7TKdsEIK3PfAEqFVSjldfe9a2QCSCi4pVLdrITh5ddDS7quOpMQUTxdQGUyJsEQqC7EfIg9lhrFwajCUGT/Nd6aYnuE0L0XPf1D3iR7LTNcFt67AGijweyg@Oh5t6bZI@O2oFuctEDvErG9BXRVb@6qr8kKZ6yaS@aIyu1SOLkJ/@hrSDFf@3b/h/7O75n@w/Q/Yv) program [Answer] # Deadfish, 2374 bytes ``` {{i}}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}i}dc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}dc{i}{i}c{{d}iiii}dc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}dc{i}{i}c{i}iic{{d}iii}dddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}c{{d}iiiiii}ddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}c{i}{i}{i}ic{{d}iii}dddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}ic{{d}iiiiii}dddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}ic{{i}dddddd}iiiiiic{{d}i}ic{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}ic{{i}dddd}iic{{d}}dddddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}iic{{d}iiiiii}ddddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}iic{d}{d}ddc{{i}ddddd}ddc{i}{i}{i}ddc{i}dcddc{{d}}dddddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}iic{{i}dddd}ic{{d}}dddddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}iic{{i}dddd}ic{{d}ii}dddc{{i}ddddd}ddc{i}{i}{i}ddc{i}dcddc{{d}}dddddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{{i}ddddd}ic{d}ddddc{{d}iiii}ic{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}iiic{{d}iiiiii}dddddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}iiic{d}{d}dddc{{i}ddddd}ddc{i}{i}{i}ddc{i}dcddc{{d}}dddddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}iiiic{{d}iiiiii}ddddddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}iiiic{d}{d}ddddc{{i}ddddd}ddc{i}{i}{i}ddc{i}dcddc{{d}}dddddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{{i}ddddd}iiiiiic{{d}ii}iic{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{{i}ddddd}iiiiiicddddddc{{d}iii}ddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{{i}ddddd}iiiiiicdddddc{{d}iii}dddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{{i}ddddd}iiiiiicdddddc{{d}iiiii}dc{{i}dddddd}iiiiic{i}{i}c{i}{i}iiic{{d}}{d}c{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}dddcc{{d}iiiiii}ic{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}dddcc{d}{d}iiic{{i}ddddd}ddc{i}{i}{i}iiiicdddc{{d}}dc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}dddcc{d}{d}iiic{{i}ddddd}ddc{i}{i}{i}iiiicdddc{{d}ii}ic{{i}dddddd}iiiiic{i}{i}c{i}{i}iiic ``` Umm... [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `jr`, ~~96~~ 93 bytes ``` ` «₍ `\Y` 3G 3GS 4 4S 5 5c 5s 6 6Y6s 6sYSE 7 7Y8 8YX XR XS XS ½… 11 11 ×Ǐ 11 ×Ǐ ½…`V↵ƛ`i¬Ẋ `+ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=jr&code=%60%20%C2%AB%E2%82%8D%0A%60%5CY%60%0A3G%0A3GS%0A4%0A4S%0A5%0A5c%0A5s%0A6%0A6Y6s%0A6sYSE%0A7%0A7Y8%0A8YX%0AXR%0AXS%0AXS%20%C2%BD%E2%80%A6%0A11%0A11%20%C3%97%C7%8F%0A11%20%C3%97%C7%8F%20%C2%BD%E2%80%A6%60V%E2%86%B5%C6%9B%60i%C2%AC%E1%BA%8A%20%60%2B&inputs=iPhone%20SE%0AiPhone%207%0AiPhone%207%20Plus%0AiPhone%208%0AiPhone%208%20Plus%0AiPhone%20X%0AiPhone%20XR%0AiPhone%20XS%0AiPhone%20XS%20Max%0AiPhone%2011%0AiPhone%2011%20Pro%0AiPhone%2011%20Pro%20Max&header=&footer=) Compressed `Plus` with a newline a bit. [Answer] # [Python 3](https://docs.python.org/3/), 136 bytes ``` for i in",3G,3GS,4,4S,5,5c,5s,6,6 Plus,6s,6s Plus,SE,7,7 Plus,8,8 Plus,X,XR,XS,XS Max,11,11 Pro,11 Pro Max".split(","):print("iPhone",i) ``` [Try it online!](https://tio.run/##Lc7BCsIwEEXRXxlmZeEhlDZtcS9dCcFsshVRHChJSCvo18cpES7M4a0mfbdXDF0pz5hJSAKjmzWHHr2DgbnDrBgwkF3eir1Kd8aIsXrCVOHhr/BOo8vtg7bVyOb4P/vIxzUtsh0Y3JxSlqAUq188GNKU8gM "Python 3 – Try It Online") [Answer] # [APL (dzaima/APL)](https://github.com/dzaima/APL), 139 bytes ``` ⎕←↑('iPhone ',)¨" ""3G""3GS""4""4S""5""5c""5s""6""6 Plus""6s""6s Plus""SE""7""7 Plus""8""8 Plus""X""XR""XS""XS Max""11""11 Pro""11 Pro Max" ``` I do not think there is a way to "bond" similar to J's `n&u`. That would be an obvious way to save some bytes. This is my first APL answer. I probably should've gone with something a little less trivial. [Attempt This Online!](https://ato.pxeger.com/run?1=m70qsSAnPqUqMTM3ccGCpaUlaboWNyc96pv6qG3Co7aJGuqZARn5eakK6jqah1YoKSgpGbuDcLCSkgkQASlTIEoG4mIlJTMgUgjIKQUxwRjKCXZVUjIHIijXAoigzAggCgLiYBBW8E2sUFIyNARhhYCifBgNFl9SnJRcDHUfzJ0A) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `jr`, 88 bytes ``` `3G3GS44S55c5s66 «₍6s6s «₍SE77 «₍88 «₍XXRXSXS ½…1111 ×Ǐ11 ×Ǐ ½…`»∵Te§ḋƒꜝL⁼»f₀pẇ¤J`i¬Ẋ `+ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJqciIsIiIsImAzRzNHUzQ0UzU1YzVzNjYgwqvigo02czZzIMKr4oKNU0U3NyDCq+KCjTg4IMKr4oKNWFhSWFNYUyDCveKApjExMTEgw5fHjzExIMOXx48gwr3igKZgwrviiLVUZcKn4biLxpLqnJ1M4oG8wrtm4oKAcOG6h8KkSmBpwqzhuoogYCsiLCIiLCIiXQ==) [Answer] # [Stax](https://github.com/tomtheisen/stax), 100 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) Yay, I (finally) beat Zsh! ``` ┌W○εRKW>◙≡D↨u^╬=Θs╜i^░δ#(\D╘i╗◄⌠╜`┌!║Æ♂∞╦J╘^╙üܰ¢╠╣⌂ƒ♣↨←Bµ☻òK$▲,0fε▄PÉ↔ΓÅ▲s2îùvπ↑╛!╢╠♣=·F┴²C6µób└╢íf ``` [Run and debug it](https://staxlang.xyz/#p=da5709ee524b573e0af04417755ece3de973bd695eb0eb23285c44d469bb11f4bd60da21ba920beccb4ad45ed3819af89bccb97f9f05171b42e602954b241e2c3066eedc50901de28f1e73328c9776e318be21b6cc053dfa46c1fd4336e6a262c0b6a166&i=) ## Explanation 1. Repace all `A`'s in the compressed string with `""`. 2. Surround it with `"`. 3. Evaluate the string. 4. Wrap the output in a list. 5. Map every item with a preceding `iPhone`. Print with a newline. [Answer] # [R](https://www.r-project.org/), ~~175~~ 178 bytes ``` cat(paste('iPhone',c('','3G','3GS','4','4S','5','5c','5s','6','6 Plus','6s','6s Plus','SE','7','7 Plus','8','8 Plus','X','XR','XS','XS Max','11','11 Pro','11 Pro Max')),sep='\n') ``` [Try it online!](https://tio.run/##K/r/PzmxRKMgsbgkVUM9MyAjPy9VXSdZQ11dR93YHUwEA0kTEAYxTEE4GUQUAwkzEFYIyCkFcyAEjBvsCiTMQRgmYgHCME4ECAeBiGAwoeCbWAFkGBqCCYWAonw4AyylqalTnFpgqx6Tp675/z8A "R – Try It Online") Manual is shorter than this programmatic take: # [R](https://www.r-project.org/), 231 bytes ``` r=rep;b='';m='Plus';cat(paste("iPhone",paste0(r(c(b,3:6,'SE',7:8,'X',11),c(1,2,2,3,3,1,2,2,4,3)),c(b,'G','GS',b,'S',b,'c','s',b,'s','s',r(b,6),'R','S','S',r(b,3))),c(r(b,9),m,b,m,b,b,m,b,m,r(b,3),'Max',b,'Pro','Pro Max')),sep='\n') ``` [Try it online!](https://tio.run/##LYzNCsIwEIRfRXqZBPZgrVRtyVE8CcVePHhpQkDB/pBU8O3jJpFllm@H2XEhOOXs0moFtKNC9/54tGZYxTL41Yri1T3nyRaUzq1wwghNVVMT@jPo0BwJd1BZSjKipB1PxZNpT5WMviZcwOpBjHkbNnwin8lxrJaEG1IkKlrcECsiniSN/BCl/5QThOvwTV2dm5H2Jjr86e2i8JggQ/gB "R – Try It Online") [Answer] # T-SQL, 145 bytes: ``` SELECT'iPhone '+value FROM string_split(' -3G-3GS-4-4S-5-5c-5s-6-6 Plus-6s-6s Plus-SE-7-7 Plus-8-8 Plus-X-XR-XS-XS Max-11-11 Pro-11 Pro Max','-') ``` I did find a shorter version using a simple string replacement (**128 bytes**), but it's not quite as interesting, and it's not clear whether the preceding line break is allowed: ``` PRINT REPLACE('223G23GS2424S2525c25s2626 Plus26s26s Plus2SE2727 Plus2828 Plus2X2XR2XS2XS Max211211 Pro211 Pro Max',2,' iPhone ') ``` I used the numeral (`2`) as the replacement character so I don't have to include another set of quotes. [Answer] # [Ruby](https://www.ruby-lang.org/), 129 bytes ``` $><<"iPhone:3G:3GS:4:4S:5:5c:5s:6:6 Plus:6s:6s Plus:SE:7:7 Plus:8:8 Plus:X:XR:XS:XS Max:11:11 Pro:11 Pro Max".gsub(?:," iPhone ") ``` [Try it online!](https://tio.run/##KypNqvz/X8XOxkYpMyAjPy/VytgdiIKtTKxMgq1MrUyTrUyLrcyszBQCckqBDBCCMINdrcytzCFsCysLCCPCKiLIKiIYiBR8EyusDA2BSCGgKB9KgQSV9NKLS5M07K10lLggViooaf7/DwA "Ruby – Try It Online") Uses the fact that strings can have newlines in (one byte), rather than `\n` (two bytes). Otherwise this is a simple replacement of a single-character string into `iPhone` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 108 bytes ``` '3G,3GS,4,4S,5,5c,6,6 Plus,SE,7,7 Plus,8,8 Plus,X,XR,XS,XS Max,11,11 Pro,11 Pro Max'-split','|%{"iPhone $_"} ``` [Try it online!](https://tio.run/##LYjdCkAwAEZfZYl287mQ3xfQrtSym91JWlHLZETh2YeoU@d0JrOp2fZKa@dozBAzgQSJQIq0Q4aMcL1aiBI58q8LFF9IyBpSPJCq3RFFD4TP5tc7aWgnPSwU9AwOb@C9GRXxG@9y7gY "PowerShell – Try It Online") -30 bytes for mazzy [Answer] # [Stax](https://github.com/tomtheisen/stax), 92 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Ωî♂∞¥■J⌡┤≥♦C♀ç¿kë▀/∞♥╧0î·Φ│∟/╢ì☼αuèôΩY?╘÷▄òà╣○╢{⌂P○å§o\τ+ mδ↓ê☻.═+Ä{╜A2jJü7πP|è╡╖Rä►┴Luƒ☺/¬& ``` [Run and debug it](https://staxlang.xyz/#p=ea8c0bec9dfe4af5b4f204430c87a86b89df2fec03cf308cfae8b31c2fb68d0fe0758a93ea593fd4f6dc9585b909b67b7f500986156f5ce72b206deb1988022ecd2b8e7bbd41326a4a8137e3507c8ab5b7528410c14c759f012faa26&i=) simplifying the existing answer was enough for 92. there's probably a way to compress the intial over-big string. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 132 bytes ``` _=>'iPhone,3G,3GS,4,4S,5,5c,5s,6,6 Plus,6s,6s Plus,SE,7,7 Plus,8,8 Plus,X,XR,XS,XS Max,11,11 Pro,11 Pro Max'.split`,`.join` iPhone ` ``` [Try it online!](https://tio.run/##Lc09C4MwFIXhvb8imwqngtSvxW6lU0GaJVsjVm0k5Iqxpf8@jaTwwH05y527T2f7VS3b0dBzcGPjHs05Uu2LzIDT1ePIkXMUKHoUFiVK1uq3j11IfkGFKnSNOoSAuENwj926L7LMY@1K/7OPUWoXrTYJmc6kjDyEv0y6nowlPaSapniMk8T9AA "JavaScript (Node.js) – Try It Online") -5 bytes thanks to @cairdcoinheringaahing and @RedwolfPrograms [Answer] # Batch, 156 Bytes ``` @ECHO(iPhone&For %%A In (3G 3GS 4 4S 5 5c 5s 6 6s "6 Plus" "6s Plus" SE 7 "7 Plus" 8 "8 Plus" X XR XS "XS Max" 11 "11 Pro" "11 Pro Max")do @Echo(iPhone %%~A ``` [Answer] # [Sequences](https://github.com/nayakrujul/sequences), \$118 \log\_{256}(96) \approx 97.1\$ bytes ``` ",3G,3GS,4,4S,5,5c,5s,6,6 Plus,6s,6s Plus,SE,7,7 Plus,8,8 Plus,X,XR,XS,XS Max,11,11 Pro,11 Pro Max"","p{H"iPhone "fhF} ``` ### Explanation ``` "..."","p{H"iPhone "fhF} "..." // Push a string of suffixes of the models of iPhones ","p // Split by commas { } // For each model: H"iPhone "f // Print "iPhone " with no trailing newline hF // And print the suffix with a trailing newline ``` ### Screenshot [![Screenshot](https://i.stack.imgur.com/XNWv5.png)](https://i.stack.imgur.com/XNWv5.png) [Answer] # [C (gcc)](https://gcc.gnu.org/), 162 bytes ``` f(i,n){n="3G3GS44S55c5s66 Plus6s6s PlusSE77 Plus88 plusXXRXSXS Max1111 Pro11 Pro Max";for(i=24;i--;)printf("iPhone %s\n",n+=strlen(n++));} ``` *-1 byte thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)!* *-45 bytes thanks to [dzaima](https://codegolf.stackexchange.com/users/59183/dzaima)!* [Try it online!](https://tio.run/##Lco/C4MwEIfhm/0UR6CQoA62/oPgWDoVpFkcuog0bcCeEi0UxM@eRiw8cC8/roufXeec5iYisVDFAE4XT0EKqYIMsg6yCXLIse4/PjZ7qjMUUOxdQonjFg00N2iUh9f2C0niYW2H/9lGJvVguamOqTRxLMVoDc2aM1O/BnrgYboTiyisptn2D@IUhkLI1fknfLeGuMAlQNRcyGB1Pw "C (gcc) – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 123 bytes ``` Write("iPhone,3G,3GS,4,4S,5,5c,6,6 Plus,SE,7,7 Plus,8,8 Plus,X,XR,XS,XS Max,11,11 Pro,11 Pro Max".Replace(",","\niPhone ")) ``` [Try it online!](https://tio.run/##Sy7WTS7O/P8/vCizJFVDKTMgIz8vVcfYHYiCdUx0TIJ1THVMk3XMdMwUAnJKi3WCXXXMdcwhbAsdCwgjQiciSCciGIgUfBMrdAwNgUghoCgfSoEElfSCUgtyEpOBdugAYUwexCYFJU3N//8B "C# (Visual C# Interactive Compiler) – Try It Online") # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 131 chars, 154 bytes ``` foreach(var x in"ȔДȥ͖˶ଇ˷೷աଈ ଉ\0΀Ƞਠ ࡼၼ")WriteLine($"iPhone {x%16-1:0;X;.}"+" GS Max Pro Maxs PluscSER".Substring(x/16%32,x>>9)); ``` Though it isn't the shortest, I invested quite a lot of effort and it would be a shame to just toss it all away. Note: There is a null byte in the string, but I can't copy-paste it so it's represented by `\0` in the code. [Try it online!](https://tio.run/##AaUAWv9jcy1jc2n//2ZvcmVhY2godmFyIHggaW4iAciU0JQFyKUGzZbLtgfgrIfLt@Czt9WhCOCsiAngrIlcMM6AyKDgqKAM4KG84YG8IilXcml0ZUxpbmUoJCJpUGhvbmUge3glMTYtMTowO1g7Ln0iKyIgR1MgTWF4IFBybyBNYXhzIFBsdXNjU0VSIi5TdWJzdHJpbmcoeC8xNiUzMix4Pj45KSk7//8 "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 103 bytes ``` j" iPhone "[kk"3G""3GS"4"4S"5"5s""5c"6+6J" Plus"="6s"+GJ"SE"7+7J8+8~J" Max"\X"XR"K"XS"+KJ11="11 Pro"+bJ ``` Today I learned about the `~`. [Try it online!](https://tio.run/##Dcm7CsIwAEDR3a8Idw0OwSbt0lEKKUIwS0AXX9BaaYqpoIufbuxwpjN95i7nO6vedXG8CQ7DwKZh4SkoPBqdQF8w0liEe7wSNSYhG4vfUsrSVrL6Lrc7vTkGwp6W4JGtVapGKeGeEXm2Of/iNPdxTHl9/QM "Pyth – Try It Online") ]
[Question] [ **This is a simple one:** Take a matrix of integers as input, and output the index of the row with the most non-zero elements. You may assume that there will only be one row with the most non-zero elements. ### Test cases: These are 1-indexed, you may choose if you want 0 or 1-indexed. ``` 1 0 row = 1 --- 0 -1 0 0 row = 1 --- 1 1 0 0 0 0 0 5 0 0 2 3 0 0 0 0 5 6 2 2 row = 4 --- 0 4 1 0 0 0 -6 0 0 1 4 -3 2 0 0 8 0 0 0 0 row = 3 ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 6 bytes ``` !gs&X> ``` Input is a matrix, with `;` as row separator. [Try it online!](https://tio.run/##y00syfn/XzG9WC3C7v//aEMFQwUDELQGU6YQppGCMULUVMEMKGAUCwA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8F8xvVgtwu6/S8j/aENrBYNYrmgDBV0QC8w2VDAEsRQMwAIKphCmkYIxQtRUwQwoYATWaAJSDlGqawZhGQIFdY1BekCiFhBJkOEA). ### Explanation ``` ! % Transpose g % Logical: convert non-zeros to 1 s % Sum of each column, or sum of row if there's a single row &X> % Arg max. Implicitly display ``` [Answer] # Mathematica, 23 bytes ``` Ordering[Count@0/@#,1]& ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 6 bytes ``` ΣĀO}θk ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3OIjDf6153Zk//8fHW2oowBEBhAUq6MQDWGaIgSMdBSM0VUApc10FIAyRrGxAA/f3S0oY4CEBlAUKyOQjSEaYoQMNJRMEZXAZQ201EAyhjFxgIA "05AB1E – Try It Online") -2 Bytes thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) ### Explanation ``` ΣĀO}θk Σ } # Sort input by following code Ā # Is element not 0? (vectorized) O # Sum θk # Get index of "largest" element # Implicit print ``` [Answer] # [R](https://www.r-project.org/), 31 bytes ``` pryr::f(which.min(rowSums(!m))) ``` returns an anonymous function which takes a matrix: ``` function(m)which.min(rowSums(!m)) ``` `rowSums` sums the rows, with `!m` transforming 0 to 1 and everything else to 0. `which.min` returns the 1-based index of the first row which contains the min sum (i.e., which row has the fewest zeros). [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jV7M8IzM5Qy83M0@jKL88uDS3WEMxV1Pzf5pGbmJJUWaFRrKGgY6Bjq6hjoGmjpGOEVAKAA "R – Try It Online") [Answer] ## Haskell, ~~46~~ ~~42~~ 41 bytes ``` snd.minimum.(`zip`[1..]).map(filter(==0)) ``` [Try it online!](https://tio.run/##LcnLCsMgEIXhV5lFFgqTQZtQuvFJRIjQSIc4Irls@vLWQjibj/984rGtObeW3FHeJFxYLiG1fLku3hIFTRKrSpzPdVfOGa2bRC7goO5cThgggfcGZ7RoAnYZHJ83bc/j1PnAf3/df18I0H4 "Haskell – Try It Online") How it works ``` map -- for each row (filter(==0)) -- collect the 0s (`zip`[1..]) -- pair with row index (<#0s>, <index>) minimum -- find the minimum snd -- extract index from pair ``` [Answer] # C#, 69 bytes ``` using System.Linq;m=>m.IndexOf(m.OrderBy(r=>r.Count(n=>n!=0)).Last()) ``` Takes a `List<int[]>` as input and returns the 0-indexed result. [Answer] # [Actually](https://github.com/Mego/Seriously), 9 bytes ``` 0@♀cñ♂RmN ``` [Try it online!](https://tio.run/##S0wuKU3Myan8/9/A4dHMhuTDGx/NbArK9fv/P9pQx1DHAARjdaJBtCmUbaRjjCRuqmOmY6RjFAsA "Actually – Try It Online") Explanation: ``` 0@♀cñ♂RmN 0@♀c count zeroes in each row ñ♂R enumerate and reverse each row (each row becomes [count, index] pair) m minimum N last element (the index) ``` [Answer] ## Python 3, ~~54~~ 48 bytes ``` lambda a:a.index(min(a,key=lambda r:r.count(0))) ``` Shaved off 6 bytes. Old solution: ``` lambda a:min(range(len(a)),key=lambda i:a[i].count(0)) ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 11 bytes ``` (⊢⍳⌈/)+/0≠⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdN7@45L/Go65Fj3o3P@rp0NfU1jd41LngUd9UkOx/BTAAKeJ61LvKUMGAC1mkbaKGgYLCofWGmiBawUATXdYQyAFhAxiGKgRiU4SQEZAyxlQFUmEGxCBpI00sFiuYwIyHG3tovRmCbwhRcmi9McQOmPkWCFdArAMA "APL (Dyalog Unicode) – Try It Online") `0≠⎕` Boolean matrix where non-zero `+/` sum rows `(` apply the following tacit function to the list of sums  `⌈/` the maximum's  `⍳` index  `⊢` in the argument list `)` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 17 bytes ``` {{∋0}ᶜ}ᵐA;.∋₎~⌋A∧ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v7r6UUe3Qe3DbXNqH26d4GitB@Q@auqre9TT7fioY/n//9HRhjqGOgYgGKsTDaJNoWwjHWMkcVMdMx0jHaPY2P9RAA "Brachylog – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` €ĀOZk ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UdOaIw3@Udn//0dHG@oY6hiAYKxONIg2hbKNdIyRxE11zHSMdIxiYwE "05AB1E – Try It Online") 0-indexed. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` TL$€M ``` [Try it online!](https://tio.run/##y0rNyan8/z/ER@VR0xrf////R0cb6hjqGIBgrE40iDaFso10jJHETXXMdIx0jGJjAQ "Jelly – Try It Online") 1-indexed. So many 5-byte versions... `TL$€M`, `T€L€M`, `TJ$€M`, `T€J€M`, `¬¬Ṣ€M`, `ṠAṢ€M`, `ṠAS€M`, `AṠṢ€M`, `AṠS€M`, `¬ċ€0M`, ... [Answer] # Haskell - ~~69~~ 68 Bytes *Saved one byte thanks to Siracusa!* Rows are zero indexed ``` g=filter m y=head$g((==maximum y).(y!!))[0..] f=m.map(length.g(0/=)) ``` ## Usage ``` f [[1,1,0,0,0],[2,3,0,0,0],[0,5,6,2,2],[1,1,1,1,1]] ``` [Try it online!](https://tio.run/##bY1BDoMgEEX3noImLiAZKWg13XASwoJERFKwRm3i7WmxLJq2mc3Pe/l/Rr3ejPcxWjE4v5mlCGhfxWh0X1qMhQh6d@GRIKF4X08nQiSjVBWDCDToGXsz2W2kFrOzICQG7SYkUH8vEJoXN22oRAOSkiuQTKkvyqA6BPwqDhxYureHNucamg/eQgc11H@GL6mfu1WXI3/hqjlWEr9mf/yPTw) [Answer] ## Clojure, 64 bytes This one works also with negative numbers in the input, luckily the same length as the original: ``` #(nth(sort-by(fn[i](count(filter #{0}(% i))))(range(count %)))0) ``` Original: ``` #(last(sort-by(fn[i](count(filter pos?(% i))))(range(count %)))) ``` [Answer] # q/kdb+, ~~25~~ ~~17~~ 16 bytes **Solution:** ``` (*)(<)sum(+)0=/: ``` **Example:** ``` q)(*)(<)sum(+)0=/:enlist(1;0) 0 q)(*)(<)sum(+)0=/:(0 -1;0 0) 0 q)(*)(<)sum(+)0=/:(1 1 0 0 0;0 0 5 0 0;2 3 0 0 0;0 5 6 2 2) 3 q)(*)(<)sum(+)0=/:(0 4 1 0;0 0 -6 0;0 1 4 -3;2 0 0 8;0 0 0 0) 2 ``` **Explanation:** ``` first iasc sum flip 0=/: / ungolfed /: / each right, apply a function to each item to the right 0= / returns boolean 1b or 0b if item in each list is equal to zero flip / flip (rotate) the output sum / sum these up iasc / return indices if we were to sort ascending first / take the first one ``` **Notes:** ~~The problem is fairly straightforward, this solution feels overly complicated.~~ As soon as I hit submit I realised the error of my ways. **Bonus:** Here's a k solution that weights in at ~~16~~ ~~10~~ 9 bytes - almost exactly the same but 7 bytes shorter due to the fact we don't need brackets when using the k built-ins, and as a result some become shorter than the q keywords (e.g. `+/` for `sum` (would be `(+/)` in q)). ``` *<+/+0=/: ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 11 bytes ``` {0fe=_:e<#} ``` [Try it online!](https://tio.run/##S85KzP1fWPe/2iAt1TbeKtVGufZ/XWpKrPX/6GhDBUMFAxCMVYgG0aZQtpGCMZK4qYKZgpGCUWwsAA "CJam – Try It Online") -2 thanks to [Challenger5](https://codegolf.stackexchange.com/users/61384/challenger5). [Answer] # [Python 2](https://docs.python.org/2/), 62 bytes ``` lambda m:max(range(len(m)),key=lambda n:len(filter(abs,m[n]))) ``` [Try it online!](https://tio.run/##LclBCoAgEEDRq7ScAYNqGXQSczGRluRMYi7y9FbQ6sP7seT9lKG6aa6BeFmp4ZHphkSyWQhWgBHVYcv0bxk/dD5km4CWS7EWg4g1Ji@5caB1p9reqDedMVgf "Python 2 – Try It Online") [Answer] # [PHP](https://php.net/), 58 bytes 0-Indexed ``` <?=array_search(max($a=array_map(array_filter,$_GET)),$a); ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwKUS7@4aYhsdbahjqGMAgrE6XNEghimMY6RjjCxjqmOmY6RjFBtrzWVvBzTENrGoKLEyvjg1sSg5QyM3sUJDJREqlptYoAFhpWXmlKQW6YAt09TUUUnUtP7/HwA "PHP – Try It Online") [Answer] # [V](https://github.com/DJMcMayhem/V), 18 bytes ``` òø0 jòÚDuu/" dGؾ ``` [Try it online!](https://tio.run/##K/v///CmwzsMuLKA1CyX0lJ9ISWuFPfDMw7t@//fQEFBwQSIDYHYgAvEA2JdMzjPECKva8xlBJEDYwuYSggGAA "V – Try It Online") Unlike most V answers, this is 0-indexed. ``` 00000000: f2f8 300a 6af2 da44 7575 2f12 220a 6447 ..0.j..Duu/.".dG 00000010: d8be .. ``` Not bad for a language with no numeric support! `;P` I also have discovered that the uppercase variant of the *count* command, that is `Ø`, is horribly broken. [Answer] # [Python 3](https://docs.python.org/3/), 92 bytes ``` def f(x): for e in x: e.sort() y=x[:] y.sort() return x.index(y[-1]) ``` First sort each row such that the entrys are `[0,0,..,0,x,x,x]` then sort the whole matrix, so that the last entry in `y` is the row we are looking for. The copy `y=x[:]` is necessary, since `.sort()` works inplace, hence we don't know the original index after sorting. I appreciate any help how to golf this solution further. Most bytes are lost because of the whitespaces in each line. The code itself is only 68 bytes long. [Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNo0LTiksBCNLyixRSFTLzFCogfBBI1SvOLyrR0AQLVNpWRFvFQpjI4kWpJaVFQG16mXkpqRUaldG6hrGa//8DAA "Python 3 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~64 55 52~~ 48 bytes * **Thanks to @Rod for shaving 9 bytes!!**: count `0`s and use `min()` instead of `max()` * @Rod saved yet another 3 bytes: use `input()` instead of `def` * **@ovs saved 4 bytes**: use of `lambda` and hash-map ``` lambda x:x.index(min(x,key=lambda n:n.count(0))) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCqkIvMy8ltUIjNzNPo0InO7XSFiqVZ5Wnl5xfmleiYaCpqfm/oCgzr0QhTSMzr6C0RAMoEB1tqKOgoGCAQhjE6kQjREyRhY1AHGPsqnXBKs1g4kaxsQA "Python 2 – Try It Online") [Answer] # JavaScript (ES6), 62 bytes 0-indexed. Takes a 2D array as input. ``` a=>(a=a.map(x=>x.filter(y=>y).length)).indexOf(Math.max(...a)) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ċ0$ÞḢi@ ``` [Try it online!](https://tio.run/##y0rNyan8//9It4HK4XkPdyzKdPj//390tIGOQawOkDQEkoZAMhYA "Jelly – Try It Online") ``` ċ0$ÞḢi@ Main link Þ Sort by ċ0$ the number of occurences of 0 Ḣ Take the first element i@ Index in the original array ``` [Answer] # Pyth, 6 bytes ``` xQh/D0 ``` [Demonstration](https://pyth.herokuapp.com/?code=xQh%2FD0&input=%5B%5B0%2C+4%2C+1%2C+0%5D%2C+%5B0%2C+0%2C+-6%2C+0%5D%2C+%5B0%2C+1%2C+4%2C+-3%5D%2C+%5B2%2C+0%2C+0%2C+8%5D%2C+%5B0%2C+0%2C+0%2C+0%5D%5D&debug=0) Instead of finding the row with the most non-zero elements, I find the row with the least zero elements. `/D0`: Order (`D`) by count (`/`) of zeros (`0`). Implicitly applied to `Q`, the input. `h`: Take the first, and minimum, element. `xQ`: Find the index (`x`) in the input (`Q`) of that element. [Answer] # [Retina](https://github.com/m-ender/retina), 46 bytes ``` %M`\b0 m`(?<=(¶.+)*)$ ;$#1 O#`.+ !`(?<=^.+;).+ ``` [Try it online!](https://tio.run/##K0otycxL/P9f1TchJsmAKzdBw97GVuPQNj1tTS1NFS5rFWVDLn/lBD1tLkWwVJyetrWmnvb//wYKCgomQGwIxAZcIB4Q65rBeYYQeV1jLiOIHBhbwFRCMAA "Retina – Try It Online") 0-indexed. Works with positive and negative integers (and 0). Assumes no leading zeros. [Answer] # [J](http://jsoftware.com/), 16 bytes ``` 0{[:/:@:+/@|:0=] ``` [Try it online!](https://tio.run/##y/r/P83WyqA62krfysFKW9@hxsrANvZ/SWpxiYKtlYKpgomCioIBkDQEkiAYbwamDIFC8cYKRmCOBVTOgCs1OSNfAaQZwkoDs/8DAA "J – Try It Online") [Answer] # Java 8, 145 bytes ``` import java.util.*;m->{int t=0,s=0,i=0,r=0;for(;i<m.size();i++){List l=(List)m.get(i);for(;l.remove(0L););s=l.size();if(s>t){t=s;r=i;}}return r;} ``` Ugly, but it works.. **Explanation:** [Try it here.](https://tio.run/##vVPRboIwFH3nK@5jOweCbr50mOzdmSU@LnuoUFwdFNJeXBzh21lBtphFkyUTGy43nJZzz2lvt3zH3bwQahu/NzIrco2wtZhXoky9GwYA4zE8cwvnCeCbgPUehRvlpULHiVJuDDxxqSoHQCoUOuGRgGX72QEQkYU0CBllFqrBvuxjkKOMYAkKwiZz51W7EkP/1tiQNnTosyTXhMmHzDPyUxDK5GhEq44sDTtSmnkbgUTSw9LU0yLLd4L4C8ooM2H682dCzBxphaFhOpSsrrXAUivQrG7YQVJRrlMrqVe2y2UMmfVFVqil2ry8AqcHU6u9QZF5eYleYacwVUR5EVHiAx615vtWGaFVxeP4NBhYeXXd7cffx1k2v2ez0VP@W2BL2Wb38koHUhz01MFRiVMlL2@kzfeDVpv0rNOrevv2NOvz5CgP1G53Jw5xuENzZ4OWCX6ZcqeDNMV1G/3cDa6duvkC) ``` import java.util.*; // Required import for List m->{ // Method with List parameter and integer return-type int t=0,s=0,i=0, // Temp integers r=0; // Result integer for(;i<m.size();i++){ // Loop over the List of Lists List l=(List)m.get(i); // Get the inner List for(;l.remove(0L);); // Remove all zeros s=l.size(); // Get the size of the List if(s>t){ // If this size is larger than the previous t=s; // Set `t` to this size r=i; // And set the result to the index of this row } } // End of loop return r; // Return result-integer } // End of method ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~119~~ 101 bytes ``` m->{int i=m.length,M=0,I=0,c;for(;i-->0;){c=0;for(int x:m[i])if(x!=0)c++;if(c>M){M=c;I=i;}}return I;} ``` [Try it online!](https://tio.run/##lZLPT8IwFMfv/BVPE5JNu2WAGmMtiRcTDpz0RjjU0mFx7Zb2TSHL/nYsGyoyTbRpt9fv@9FPm7firzzKC2lWi5et0kVuEVZei0tUWXxGex0tLY1AlZsfnQ6t5HrnKsqnTAkQGXcOplwZqHoAe9UhR/97zdUCtPcFD2iVWc7mwO3ShbtIgMd8YvB@f9qtMjibz@ZjSIHBVkfjyiugmI4zaZb4TKYsIRO/BE1zG1AVReOEhpVgSSPsotc3eqbmoUqD9QlLQnF@Tr0txtOwmjJBJ0zRurYSS2tgQustNIM2NCgdBikBI99gz9Ji7kY1qMnXJqn3dk0gCf@SnhCIvpfwmf@uMiDgZ9LO42oELruOIYHRbxk@/IqAjxgegIz@ep2LlqVLEV115UETH42O0NqE626No9cZNlB1z38OG6th/K2JyAc26MYEuS6kQLkIob3Iw8ah1HFeYlz43sQ0OO27G@i7vjkld9byjYsXUhaPedu7gQ4JpDEvimxz5/yhXmDss2pLWG/fAQ "Java (OpenJDK 8) – Try It Online") Java, that sweet verbose language :) Thanks for saving 18 bytes, @KevinCruijssen ;) [Answer] # JavaScript (ES6), 51 Bytes ``` m=>m.reduce((a,e,i)=>e.filter(x=>x).length>a?i:a,0) ``` where `m` is a 2D array and the index returned is 0-indexed **Test cases:** ``` f= m=>m.reduce((a,e,i)=>e.filter(x=>x).length>a?i:a,0) console.log(f([[1], [0]])) console.log(f([[0,-1], [0,0]])) console.log(f([[1,1,0,0,0], [0,0,5,0,0], [2,3,0,0,0], [0,5,6,2,2]])) console.log(f([[0,4,1,0], [0,0,-6,0], [0,1,4,-3], [2,0,0,8], [0,0,0,0]])) ``` [Answer] # Java 8, 100 bytes ``` m->m.indexOf(m.stream().map(z->{z.removeIf(x->x==0);return z;}).max((q,r)->q.size()-r.size()).get()) ``` ## Explanation The power of Lists and Streams! (and without the imports, to boot!) Let's break this little lambda down into chunks: ``` m.stream().map(z->{z.removeIf(x->x==0);return z;} ``` We turn our List of Lists (the matrix in the question) into a Stream and go through each element, removing all of those pesky zeroes from each sub-List. We need to explicitly return the sublist each time here, because `Stream.map()` converts each object in the Stream to whatever the mapping returns, and we don't want to change them. ``` .max((q,r)->q.size()-r.size()).get() ``` We go through our newly de-zeroed sublists, and simply check how big they are next to each other, getting us the biggest sublist. The `.get()` is because the `Stream.max()` returns an Optional, requiring that extra function call. ``` m.indexOf() ``` We take that biggest sublist, and find where it is in the main List, giving us our result! ## Notes This breaks if the outer list is empty, but I'm taking > > You may assume that there will only be one row with the most non-zero elements. > > > to imply that there will always be at least one row. Correct me if I'm wrong. ]
[Question] [ Consider the infinite string of all nonnegative decimal integers concatenated together in order (akin to [Champernowne's constant](https://en.m.wikipedia.org/wiki/Champernowne_constant)): ``` 0123456789101112131415161718192021222324252627282930...979899100101102103... ``` Write a program or function that takes in a nonnegative integer that indexes (0-based) into this infinite string. Output a [truthy](https://codegolf.meta.stackexchange.com/a/2194/26997) value if the digit indexed is 0, otherwise output a [falsy](https://codegolf.meta.stackexchange.com/a/2194/26997) value if the digit is 1-9. The shortest code in bytes wins. The first 25 truthy-producing inputs are: ``` 0 11 31 51 71 91 111 131 151 171 191 192 194 197 200 203 206 209 212 215 218 222 252 282 312 ``` Kudos if your program is memory effecient, but this is not a requirement. [Answer] ## Haskell, 25 bytes ``` (<'1').((show=<<[0..])!!) ``` Usage example: `(<'1').((show=<<[0..])!!) 312` -> `True` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 5 bytes Code: ``` ÝJ¹è_ ``` Explanation: ``` Ý # Get the list [0 .. input]. J # Join the list. ¹ # Get the first input again. è # Get the character on that index. _ # Logical negate (0 -> 1, everything else -> 0). ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=w51KwrnDqF8&input=MjE4) [Answer] # Mathematica, ~~42~~ 40 bytes ``` (0@@Join@@IntegerDigits@Range@#)[[#]]<1& ``` Anonymous function. Takes a number as input and returns either `True` or `False` as output. A longer, yet more efficient(?) solution: ``` RealDigits[ChampernowneNumber[],10,1,-#][[1,1]]<1& ``` [Answer] ## CJam, 9 bytes ``` {_),s=~!} ``` This is an unnamed block (function) which takes in an integer and returns 0 or 1 accordingly. Explanation: ``` { } Defines a block _ Copy input n ), Increment n and take range s Convert to string - for a list of numbers this concatenates the digits = Index, getting nth digit ~ Evaluate the digit character into a number ! Logical negation ``` [Online interpreter](http://cjam.aditsu.net/#code=11%20%7B_%29%2Cs%3D~!%7D%20~). Note that `~` evaluates a block. Alternative, you can run this [test suite](http://cjam.aditsu.net/#code=1000%20%7B_%29%2Cs%3D~!%7D%2C%20p) which uses `,` to filter the first 1000 numbers for truthy values. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` RDF⁸ị¬ ``` [Try it online!](http://jelly.tryitonline.net/#code=UkRG4oG44buLwqw&input=&args=MTEx) or [verify all test cases](http://jelly.tryitonline.net/#code=UkRG4oG44buLwqwKMzEz4bi2w4fDkGY&input=). ### How it works ``` RDF⁸ị¬ Main link. Argument: n R Range; yield [1, ..., n]. D Decimal; convert all integers in that range to base 10 arrays. F Flatten the result. ⁸ị Extract the digit at index n (1-based). This returns 0 if the array is empty (n = 0). ¬ Logical NOT; return 1 if the digit is 0, 0 if not. ``` [Answer] # MATL, 11 bytes ``` Qt:qVXzw)U~ ``` [**Try it Online!**](http://matl.tryitonline.net/#code=UXQ6cVZYencpVX4&input=MTE) **Explanation**: ``` % Implicitly grab input as an integer (N) Qt % Add 1 and duplicate :q % Create an array from [0 ... N] V % Convert each entry to a string (places spaces between each number) Xz % Remove all whitespace w) % Get the N+1 element of the string (since MATL uses 1-based indexing natively) U~ % Convert the result back to a number and negate which yields TRUE if it was '0' and % FALSE otherwise ``` [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), ~~10~~ 8 bytes **2 bytes thanks to Fatalize.** ``` y@ec:?m0 ``` [Try it online!](http://brachylog.tryitonline.net/#code=eUBlYzo_bTA&input=MzEy) ``` y@ec:?m0 y range from 0 to Input, inclusive, @e the digits of every number in that range, c concatenated :?m the Input-th digit 0 is zero. ``` [Answer] # [Perl 6](http://perl6.org/), ~~26~~ 25 bytes ``` {!+map(|*.comb,0..*)[$_]} ``` A lambda that takes a number as input and returns a `True` or `False`. Memory-efficient. **How it works** 1. `0..*` – Construct the range from 0 to infinity. 2. `map(|*.comb, )` – Lazily iterate the range, replacing each number with the characters of its string representation, and returning a new lazy sequence. The `|` keeps the new sequence flattened. 3. `[$_]` – Take the element at the index defined by the (implicitly declared) lambda parameter `$_`. 4. `+` – Coerce it to a number. *(This step is needed because coercing a string directly to a boolean always gives True unless the string is empty.)* 5. `!` – Coerce it to a boolean and negate it. ([try it online](https://glot.io/snippets/ehx8swz0lk)) *EDIT: -1 byte thanks to b2gills.* [Answer] # Python 3.5, 40 bytes ``` lambda n:('%d'*-~n%(*range(n),n))[n]<'1' ``` Test it on [repl.it](https://repl.it/CxxI). ### How it works For input **n**, `'%d'*-~n` repeats the format string **n + 1** times. `(*range(n),n)` unpacks the range **[0, ..., n - 1]** and yields the tuple **(0, ..., n)**. `...%...` replaces each occurrence of **%d** with the corresponding integer in the range, yielding the string **01234567891011...n**. `(...)[n]<'1'` selects the character at index **n** and tests if it is less than the character **1**. [Answer] # Python 3, 44 bytes ``` lambda n:''.join(map(str,range(n+1)))[n]<'1' ``` An anonymous function that takes input via argument and returns `True` or `False` as appropriate. **How it works** ``` lambda n Anonymous function with input n range(n+1) Yield the range [0, n]... map(str,...) ...convert all elements to string... ''.join(..) ...concatenate... ...[n] ...yield nth character... :...<'1' ...return True if int(character)==0 else return False ``` [Try it on Ideone](https://ideone.com/YqPZNg) [Answer] # Pyth, ~~8~~ 7 bytes *Thanks to @LeakyNun for -1 byte* ``` !s@jkUh ``` This is my first attempt at golfing in Pyth. A full program that prints `True` or `False` as appropriate. [Try it online](https://pyth.herokuapp.com/?code=%21s%40jkUh&debug=0) [First 25 truthy inputs](https://pyth.herokuapp.com/?code=FNr0+313I%21s%40jkUhNNN&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11&debug=0) **How it works** ``` !s@jkUh Program. Input: Q hQ Head. Yield Q+1 U Unary range. Yield [0, Q] jk Join. Join on empty string @ Q Index. Yield string[Q] s Integer. Convert to integer ! Logical negation. 0 -> True, all other digits -> False Print. Print result implicitly ``` [Answer] # [S.I.L.O.S](http://github.com/rjhunjhunwala/S.I.L.O.S), 141 bytes ``` readIO i+1 lblL c=C p=1 lblc p*10 c/10 if c c p/10 lbln m=C m/p m%10 p/10 i-1 if i C GOTO H lblC if p n C+1 GOTO L lblH m/m m-1 m| printInt m ``` [Try it online!](http://silos.tryitonline.net/#code=cmVhZElPCmkrMQpsYmxMCmM9QwpwPTEKbGJsYwpwKjEwCmMvMTAKaWYgYyBjCnAvMTAKbGJsbgptPUMKbS9wCm0lMTAKcC8xMAppLTEKaWYgaSBDCkdPVE8gSApsYmxDCmlmIHAgbgpDKzEKR09UTyBMCmxibEgKbS9tCm0tMQptfApwcmludEludCBt&input=&args=MzEy) Uses only 5 integers, maximum memory efficiency \o/ ### Explanation We generate as many digits as the input in the Champernowne's constant. In the main loop, we do the following: * Find the length of the current number by floor\_dividing it by 10 repeatedly until it reaches 0, and then count the number of divisions used. * Instead of storing the number of divisions, we store 10 to that number power instead. * Iterate through each digit as such: the `100`s digit of `1234` is obtained by `(1234/10)%10` where `/` is floor division. * For each digit generated, take 1 from the input, while checking if the input reached zero. * If the input reaches zero, check if the current digit is 0 and then halts. [Answer] ## JavaScript (ES6), 45 bytes + Kudos ``` f=(n,s='0')=>s[n]?!+s[n]:f(n-s.length,-~s+'') ``` My best non-Kudos version was 34 bytes: ``` n=>!+(g=s=>s[n]||g(s+i++))('',i=0) ``` [Answer] # JavaScript (ES6), 47 bytes `n=>[...Array(n+1)].reduce((a,_,i)=>a+i,'')[n]<1` [Answer] ## Javascript (ES6), ~~42~~ 33 bytes ``` n=>!+(r=i=>i>n?'':i+r(i+1))(0)[n] ``` Example: ``` let f = n=>!+(r=i=>i>n?'':i+r(i+1))(0)[n] // test all integers in [0, 312] for(var n = 0, list = []; n <= 312; n++) { f(n) && list.push(n); } console.log(list.join(',')); ``` [Answer] # Groovy, 56 bytes ``` def f(n){def s=''<<'';(0..n).each{s<<it};!(s[n] as int)} ``` Nothing fancy, but I'm trying out some new things. ``` def f(n) { def s = ''<<'' // declare a StringBuffer (0..n).each { s << it } !(s[n] as int) // Groovy considers a non-null char truthy, so we have to cast } ``` [Answer] # Perl, 24 bytes Includes +1 for `-p` Run with input on STDIN: ``` zero.pl <<< 31 ``` print 1 for zero, nothing otherwise `zero.pl` ``` $_=!(map/./g,0..$_)[$_] ``` [Answer] # zsh, 31 bytes ``` exit ${${(j..):-{0..$1}}[$1+1]} ``` `exit 0` is true in zsh [Answer] # PHP, 36 bytes ``` <?=!join(range(0,$a=$argv[1]))[$a]; ``` Print `1` if Champernowne argument-th decimal is `0`, else print '' (empty string). [Answer] # Ruby, ~~35~~ 23 bytes This is an anonymous function that concatenates `[0..n]`, takes the `n`th index and checks if that char is `"0"` (less than `"1"`). Golfing suggestions welcome. ``` ->n{([*0..n]*'')[n]<?1} ``` **Ungolfing** ``` ->n{...} # Create an anonymous function with parameter n. [*0..n] # Create an array of the range [0..n]. [...]*'' # Join the array using the empty string. (...)[n] # Take the char at the n-th index of the string. <?1 # Check if the char is < "1" (that is, "0"). ``` [Answer] # Bash, ~~31~~ 28 bytes ``` seq -s "" 0 $1|egrep ^.{$1}0 ``` Output is non-empty (truthy) or empty (falsy). Test it on [Ideone](http://ideone.com/7MOc2A). [Answer] # Julia, ~~21~~ 20 bytes ``` !n=join(0:n)[n+1]<49 ``` *Thanks to @LuisMendo for golfing off 1 byte!* [Try it online!](http://julia.tryitonline.net/#code=IW49am9pbigwOm4pW24rMV08NDkKCmZvciBuIGluIDA6MzEyCiAgICBpZiAhbiBwcmludGxuKG4pIGVuZAplbmQ&input=) [Answer] # R, 61 57 bytes Thanks to @plannapus for 4 bytes. ``` n=scan();strsplit(paste(0:n,collapse=""),"")[[1]][n+1]==0 ``` Creates a vector of numbers 0:n (for 0 indexing), creates a string of them, pulls the nth value from string (adjusting for 0 indexing). Converts to numeric and tests if it is 0. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 14 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/9429#9429) ``` {~×⍎⍵⊃∊⍕¨⍳1+⍵} ``` [Try it online!](https://tio.run/##Jc49CsJAEAXgPqdIL0Jm15ikFsRUguYCAVGLgOJPEUSbQJDAihbByt7OQryA3mQuEndeivlg5z3YSddZd5an2WrR8KWOx1xeveZw@t3ZXNh8uCr4XLGpv082b@rY1bGZ25LE6FfF96W5vNnXdDKwJqN42rB5uMM02@bO3CU7yo6WIYLacaSSbPa7pXQ86bWRxRcCISIEEBEhI4TUppGCPRjIZ54HNezDSCQFfRiKChsfhjiS1B8 "APL (Dyalog Unicode) – Try It Online") ## Explanation ``` {~×⍎⍵⊃∊⍕¨⍳1+⍵} ⍝ { } ⍝ A dfn, in this case with a single argument (⍵) ⍳1+⍵ ⍝ Computes the range of 0..arg ⍕¨ ⍝ For each (¨), convert to a string (⍕) ∊ ⍝ Enlist all strings into a single string ⍵⊃ ⍝ Pick (⊃) the element at the index of the given arg (⍵) ⍎ ⍝ 'Execute' to treat it as a numeric × ⍝ Turn >1 into 1 ~ ⍝ Negate ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 38 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 4.75 bytes ``` ʀṅi0= ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwiyoDhuYVpMD0iLCIiLCIzMiJd) [Answer] # GolfScript, 12 bytes ``` ~.),""*\=48= ``` Explanation: ``` ~ Evaluate the input. . Duplicate it ) Increment the duplicate. , Create an array from 0 to it. ""* Join it with an empty string. \= Get the n-th index of this string, where n is the input 48= Is it equal to 0? ``` [Try it online](http://golfscript.tryitonline.net/#code=fi4pLCIiKlw9NDg9&input=MTEx) or [verify all test cases!](http://golfscript.tryitonline.net/#code=bi97fi4pLCIiKlw9NDg9fVwlbio&input=MAoxMQozMQo1MQo3MQo5MQoxMTEKMTMxCjE1MQoxNzEKMTkxCjE5MgoxOTQKMTk3CjIwMAoyMDMKMjA2CjIwOQoyMTIKMjE1CjIxOAoyMjIKMjUyCjI4MgozMTI) [Answer] **C, 154 bytes** ``` s(n,v,k,z){for(k=1;(z=n%10,n/=10)&&!v||k<v;++k); return v?z:k;} f(n,i,j,c){for(i=0,j=0;;++i){c=s(i,0,0,0);j+=c;if(j>n){c=s(i,j-n,c,0);break;}}return !c;} ``` the function that calculate the value is f(n,0,0,0) where n is the input index. it can calculate from index changing "return !c" in "return c" the value of the array in that index... i don't understand how but it seems to work ok.... ``` main() {int i,r; char a[]="0123456789101112131415161718192021222324252627282930313233343536"; for(i=0; i<1000; ++i) if(r=f(i,0,0,0)) printf("%u|",i); } /* 154 0|11|31|51|71|91|111|131|151|171|191|192|194|197|200|203|206|209|212|215|218|222 |252|282|312|342|372|402|432|462|491|492|494|497|500|503|506|509|512|515|518|522|552 |582|612|642|672|702|732|762|791|792|794|797|800|803|806|809|812|815|818|822|852 |882|912|942|972| */ ``` [Answer] # Javascript (ES5): 61 60 bytes ``` function(b){for(s="";s.length<b;)s+=s.length;return 0==s[b]} ``` Ungolfed: ``` function a(b){ for(var s="";s.length<b;) s+=s.length; } return (s[b]==0); } ``` Old: ``` function(n){s="";while(s.length<n)s+=s.length;return s[n]==0} ``` Ungolfed old: ``` function a(n){ var str=""; while(str.length<n)str+=str.length; //Create String as long as needed return str[n]==0 //Check for 0 and return } ``` [Answer] # CoffeeScript, 56 bytes ``` a=(b)-> s="" while s.length<b #loop for building string with required length s+=s.length #add number "0"==s[b] #return, if the number at the position equals zero ``` [Answer] # C#, 71 bytes And I thought it was short at first, but then I had to add `n+=11` to prevent it from throwing a `System.IndexOutOfRangeException` when numbers below 11 were input ``` return String.Join("",Enumerable.Range(0,n+=11).ToArray())[n]=='0'?1:0; ``` ]
[Question] [ Two prime numbers are defined as twin primes if they differ by two. For example, 3 and 5 are twin primes as are 29 and 31. Write a program that finds the nth pair of twin primes (where n comes from STDIN) and prints them on STDOUT, separated by a comma and a space. This is code-golf, so the shortest code wins. Sample input: ``` 3 ``` Sample output: ``` 11, 13 ``` [Answer] # Haskell 118 ``` main=putStrLn.(!!)[show n++", "++show(n+2)|n<-[2..],all((>0).rem n)[2..n-1],all((>0).rem(n+2))[2..n]].(+)(-1)=<<readLn ``` Brute-force all twin primes and prints the nth pair. [Answer] # CJam, ~~29~~ 26 bytes ``` Y4]{{:)_{mp}/&!}g}q~*", "* ``` [Try it online.](http://cjam.aditsu.net/ "CJam interpreter") ### Examples ``` $ for i in {1..10}; do cjam twin-primes.cjam <<< $i; echo; done 3, 5 5, 7 11, 13 17, 19 29, 31 41, 43 59, 61 71, 73 101, 103 107, 109 ``` ### How it works ``` Y4] " Push [ 2 4 ]. "; { " "; { " "; :) " Increment each integer in the array. "; _ " Duplicate the array. "; {mp}/ " For each integer in the array, push 1 if it's prime and 0 otherwise. "; &! " Compute the logical NOT of the bitwise AND of the two previous integers. "; }g " If the result is non-zero, repeat the loop. "; }q~* " Do the above “N” times, where “N” is the integer read from STDIN. "; ", " " Join the array by comma and space. "; ``` [Answer] # Perl, 101 87 ### 87 characters, building over aschepler's comment ``` $n=pop;$r='^1$|^(11+?)\1+$';($t=1x$s)=~$r||"11t"=~$r||--$n||die"$s, ",$s+2,$/while++$s ``` ### 101 characters, earlier answer ``` $n=pop;$r=qr/^1$|^(11+?)\1+$/;(1x$s)!~$r&&(1x($s+2))!~$r&&++$i==$n&&say($s,", ",$s+2)&&exit while++$s ``` ### Usage: ``` $ perl ./twin_primes.pl 10 107, 109 ``` ### Explanation ``` $n = pop; # Pulls twin prime pair counter from @ARGV $r = qr/^1$|^(11+?)\1+$/; # The money line - a regex that verifies # if a string of 1's has non-prime length while ( ++$s ) { # Loop over integers # '&&' short-circuits (1 x $s ) !~ $r # Negated regex match evaluates to true if $s is prime && (1 x ($s+2) ) !~ $r # Same for $s + 2 && ++$i == $n # Counter to control which pair to print && say( $s, ", ", $s+2 ) # Print the line && exit # Terminate program } ``` The workings of the non-primality regex is explained in [this SO question](https://stackoverflow.com/q/3329766/133939). [Answer] # C: 113 ``` n,c,l;main(i){for(scanf("%d",&n),l=2;n;l=c==i?n-=i==l+2,i:l,i+=2)for(c=2;c<i&&i%c++;);printf("%d, %d\n",l-2,l);} ``` Sample run: ``` $ for i in $(seq 1 10); do echo $i | ./twinprimes; done 3, 5 5, 7 11, 13 17, 19 29, 31 41, 43 59, 61 71, 73 101, 103 107, 109 ``` Thanks for help from Dennis, bebe, and Alchymist. [Answer] # CJam - 26 ``` 1e4,{mp},_2f-&qi(=_2+", "\ ``` It works for primes smaller than 10000; you can replace `4` with a higher exponent for larger numbers (potentially up to 1020), but the program will get slower and will use more memory. Try it at <http://cjam.aditsu.net/> **Explanation:** `1e4,` creates the array [0 1 2 ... 9999] `{mp},` selects only the prime numbers `_2f-` copies the array and subtracts 2 from each item `&` intersects the two arrays, thus finding the lower primes from each twin prime pair `qi` reads the input and converts to integer `(=` adjusts the index and gets the corresponding (lower) twin prime from the array `_2+` copies the prime and adds 2 `", "\` puts the comma and space between the two primes [Answer] ## Mathematica - 63 characters ``` Print[#-2,", ",#]&@Nest[NestWhile[NextPrime,#,#2-#!=2&,2]&,1,n] ``` ### Notes This is in fact a rather straightforward implementation. Shortening resulted in almost no obfuscation. `NextPrime` is a builtin that finds the next prime after a number. `NestWhile[NextPrime,#,#2-#1!=2&,2]&` is an anonymous function that finds the larger prime of the next twin prime pair after a number. `Nest` applies this anonymous function `n` times. `Print[#-2,", ",#]&` is an anonymous function that prints to stdout according to the specifications. Sadly this alone takes up 18 characters of the 63 character solution. ### Example > > > ``` > In[1]:= Do[ > Print[#-2,", ",#]&@Nest[NestWhile[NextPrime,#,#2-#!=2&,2]&,1,n], > {n, 1, 10} > ] > 3, 5 > 5, 7 > 11, 13 > 17, 19 > 29, 31 > 41, 43 > 59, 61 > 71, 73 > 101, 103 > 107, 109 > > ``` > > --- **Update:** Two characters could be saved by reimplementing [this CJam solution](https://codegolf.stackexchange.com/a/31854/24980). However, this algorithm limits the maximum value of `n`. Just replace the `Nest...` part by `Intersection[#,#-2][[5]]&@Prime@Range[999]` [Answer] # Javascript (E6) 92 ~~96~~ Shorter and compliant - use spidermonkey shell to read stdin/write stdout (with comma and space). It finds the 10000th pair 1260989, 1260991 in under a minute on my PC Could be shorter using `p[n]=o=n` instead of `p.push(o=n)`, so that the p array is sparse. But that's quite slower, and I'm not going to win for code length anyway. ``` m=readline();for(n=3,o=p=[];m;n+=2)p.every(e=>n%e)&&(m-=n-o<3,p.push(o=n));print(o-2+', '+o) ``` To try in firefox console: ``` m=prompt();for(n=3,o=p=[];m;n+=2)p.every(e=>n%e)&&(m-=n-o<3,p.push(o=n));alert(o-2+', '+o) ``` **Ungolfed** A function that found all first m twins (returns the largest value): ``` T=m=>{ for (o=n=3, p=[2], t=[]; !t[m-1]; n+=2) p.every(e => n%e) && (n-o-2 ? 0 : t.push(n), p.push(o=n)) return t } ``` Example: `console.log(T(50))` `[5, 7, 13, 19, 31, 43, 61, 73, 103, 109, 139, 151, 181, 193, 199, 229, 241, 271, 283, 313, 349, 421, 433, 463, 523, 571, 601, 619, 643, 661, 811, 823, 829, 859, 883, 1021, 1033, 1051, 1063, 1093, 1153, 1231, 1279, 1291, 1303, 1321, 1429, 1453, 1483, 1489]` Just the last: ``` L=m=>{ for (o=n=3,p=[2]; m; n+=2) p.every(e => n%e) && (m -= n-o==2, p.push(o=n)) return o } ``` Then, take that 2 lines and add IO ``` m = prompt() for (o=n=3, p=[2]; m; n+=2) p.every(e => n%e) && (m -= n-o==2, p.push(o=n)) alert('o-2+', '+o) ``` [Answer] # J - ~~49 60 55~~ 51 bytes I decided to go with a simple approach. Function `t` finds the next twin prime given a prime number as input (now this is included in the `f` function). Function `f` finds the nth twin prime. This also happens to be the first actual program I've written in J. ``` f=:[:(":,', ',":@+&2)(4&p:(,{~-=2:)])^:_@>:^:(]`2:) ``` Examples: ``` f 1 3, 5 f 2 5, 7 f 3 11, 13 f 4 17, 19 f 5 29, 31 f 100000 18409199, 18409201 ``` Just for some eyebrowraises, have the ungolfed version. ``` twin =: (4&p:)(($:@[)`(,)@.(=(]+2:)))] f =: ((]-2:),])((0:{twin) ^: (]`(2:))) ``` ### Explanation: ``` f=:[:(":,', ',":@+&2)(4&p:(,{~-=2:)])^:_@>:^:(]`2:) (4&p:(,{~-=2:)])^:_@>:^:(]`2:) @>:^:(]`2:) main loop ^:(]`2:) Repeat n times, starting with value of 2 @>: Add one to the current value and apply to the following function. (4&p:(,{~-=2:)])^:_ Get the next twin prime ^:_ Recurse until there's no change (,{~-=2:) If next prime - current value == 2, return current value, otherwise the next prime. 4&p: Get the next prime (":,', ',":@+&2) Format the output and add 2 to the second value. [: Apply the twin prime to the formatter. Basically, if n is 4, this creates a recursion tree like this: let T be the recursion inside t and numbers between rows the return values of according function (t * n) 3 -> (t * 4) 3 -> t t t t 3 17 11 5 3 -> (T T) (T T) T T 3 17 13 11 7 5 3 -> 17 ``` [Answer] ## C#, 265 ``` using System.Linq;class P{static void Main(string[] args){var i=int.Parse(args[0]);int f=0,c=0;for(int j=1;;j+=2){var b=(Enumerable.Range(1,j).Count(x=>j%x==0)==2);if(f==0 && b){f=j;continue;}if(b){c++;if(c==i){System.Console.WriteLine(f+","+j);break;}j-=2;}f=0;}}} ``` [Answer] ### Ruby 94 ``` require'mathn' n=gets.to_i a=1 (a+=2;a.prime?&&(a+2).prime?&&n-=1)while n>0 $><<"#{a}, #{a+2}" ``` Online test: <http://ideone.com/B2wxnG> [Answer] # Perl, ~~100~~ 95 ``` $n=<>;$i=3;while($c<$n&&($l=$i++)){$i++until!grep{$i%$_<1}(2..$i-1);$c++if$i-$l<3}print"$l, $i" ``` Ungolfed: ``` $n = <>; # Read from STDIN $i = 3; # Tiny hack because I know I don't need the number 2 while ($c<$n && ($l = $i++)) { # $c counts the pairs, $l is the last prime $i++ until ! grep {$i%$_<1} (2..$i-1); # Increase $i until it's not divisible by anything $c++ if $i-$l < 3 # If $i and $l are twin primes, count it } print "$l, $i" # That damned comma added a whole character to my code! ``` [Answer] ## T-SQL (2008+): 344 Brute force a CTE to find primes, window function to count n, followed by a join to find the twin. Works in a second for outputs < 1,000, just under a minute for outputs < 10,000. Golfed (SQLFiddle **[here](http://sqlfiddle.com/#!3/d41d8/35725/0)**): ``` WITH x(i) AS(SELECT 99 UNION ALL SELECT i-2 FROM x WHERE i>3),z AS(SELECT RANK()OVER(ORDER BY x.i)n,x.i FROM x x LEFT JOIN x y ON x.i%y.i=0 AND y.i NOT IN(x.i,1) WHERE y.i IS NULL)SELECT LTRIM(a)+', '+LTRIM(b)FROM(SELECT RANK() OVER(ORDER BY x.i)n,x.i a,y.i b FROM z x,z y WHERE x.n=y.n-1 AND x.i=y.i-2) o WHERE n=3 OPTION(MAXRECURSION 0) ``` Legible: ``` WITH x(i) AS ( SELECT 99 UNION ALL SELECT i-2 FROM x WHERE i > 3 ) ,z AS ( SELECT RANK()OVER(ORDER BY x.i)n,x.i FROM x x WHERE NOT EXISTS (SELECT * FROM x y WHERE x.i%y.i = 0 AND y.i NOT IN (x.i,1) ) ) SELECT LTRIM(a)+', '+LTRIM(b) FROM ( SELECT RANK()OVER(ORDER BY x.i)n,x.i a, y.i b FROM z x, z y WHERE x.n = y.n+1 AND x.i = y.i+2 ) o WHERE n = 3 OPTION(MAXRECURSION 0) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `ṡ`, 57 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 8.125 7.125 bytes ``` Þp'⇧æ;i:⇧ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyLigKbhuaE9IiwiIiwiw55wJ+KHp8OmO2k64oenIiwiIiwiMyJd) Bitstring: ``` 001010110100000101111000110100001000110100111000111011110 ``` 0-indexed [Answer] ### GolfScript 46 ``` ~[1 3]\{\{))}%.{:x,{)x\%!},,2=}/*@\-.}do;', '* ``` Online test: [link](http://golfscript.apphb.com/?c=OyczJwoKflsxIDNdXHtceykpfSUuezp4LHspeFwlIX0sLDI9fS8qQFwtLn1kbzsnLCAnKg%3D%3D&run=true) **Annotated code:** ``` ~ # parse the input as an int [1 3] # add the array [1, 3] on the stack \ # invert the items on the stack { # begin loop \ # bring the array to the top of the stack {))}% # add 2 to each of the numbers in the array .{:x,{)x\%!},,2=}/ # check if numbers are prime (leaves a 0 or 1 for both numbers on the stack) * # multiply the two 0/1 numbers (will only get 1 if both are 1) @\- # subtract the result from the inital int . # copy the new int value on the stack to be consumed by the 'do' loop }do # repeat until the initial int was taken down to 0 # at this point the array contains the two numbers we're looking for ; # get rid of the 0 from the stack ', '* # format the output ``` [Answer] # PHP 5.4, 223 Not a smaller one, But one try from php. ``` $n=$argv[1];function i($k){for($i=2;$i<=(int)($k/2);$i++)if($k%$i==0)return 0;return 1;}function t($t){return (i($t) && i($t+2))?1:0;}$g=1;$d=0;do{if(t($g)==1){if($d<$n){$d++;}else{print_r([$g,$g+2]);break;}}$g++;}while(1); ``` [Answer] ## C 309 Keeps getting next primes and store odd and even terms then checks if the difference is two. ``` int main() { int n; scanf("%d",&n); int a=2,b=3,k=2,q; int odd=1; int p; if(n>0) { while(n) { k++; p=1; q=ceil(sqrt(k)); for(int i=2;i<=q;i++) { if(k%i==0) { p=0; break; } } if(p) { if(odd%2==0)a=k; else b=k; if(abs(a-b)==2)n--; odd++; } } } printf("%d %d\n",a,b); return 0; } ``` [Answer] ## R, 91 chars ``` a=scan();n=1;p=5;while(n!=a){p=p+1;q=p-2;if(sum(!p%%2:p,!q%%2:q)<3)n=n+1};cat(q,p,sep=", ") ``` Nothing really fancy: ``` a=scan() n=1 p=5 while(n!=a){ p=p+1 q=p-2 if(sum(!p%%2:p,!q%%2:q)<3) # Check that p and q are both primes by checking n=n+1 # the number of zeroes resulting from } # p modulo each integers 2 to p and same for q cat(q,p,sep=", ") ``` Usage: ``` > a=scan();n=1;p=5;while(n!=a){p=p+1;q=p-2;if(sum(!p%%2:p,!q%%2:q)<3)n=n+1};cat(q,p,sep=", ") 1: 10 2: Read 1 item 107, 109 ``` [Answer] # Japt, ~~23~~ 19 bytes -4 bytes thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy) ``` @µX°j ©°Xj}f [UU+2] ``` [Run it online](https://ethproductions.github.io/japt/?v=1.4.6&code=QLVYsGogqbBYan1mCltVVSsyXQ==&input=Mw==) [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` !fo=2F≠Ẋeİp ``` [Try it online!](https://tio.run/##yygtzv7/XzEt39bI7VHngoe7ulKPbCj4//@/MQA "Husk – Try It Online") non-competing, since it takes input from arguments rather than STDIN. Returns a 2-element list. Interesting version using `Ψ`: [Try it online!](https://tio.run/##yygtzv7/P1hH20jx3Iq0fFujR50Ljmwo@P//vzEA "Husk – Try It Online") [Answer] ### PHP (153) ``` $nth=readline();$i=1;$l=1;$c=0;while(1){$q=0;for($j=1;$j<=$i;$j++){$q+=$i%$j==0?1:0;}if($q==2){if($i-$l==2&&++$c==$nth){echo"$l, $i";break;}$l=$i;}++$I;} ``` Readable format with properly named variables: ``` $nth = readline(); $i = 1; $lastFoundPrime = 1; $countOfFoundPrimes = 0; while (1) { $quotient = 0; for ($j = 1; $j <= $i; $j++) { $quotient += $i % $j == 0 ? 1 : 0; } if ($quotient == 2) { if ($i - $lastFoundPrime == 2 && ++$countOfFoundPrimes == $nth) { echo "$lastFoundPrime, $i"; break; } $lastFoundPrime = $i; } ++$i; } ``` And wrapped in a for loop: ``` foreach (range(1, 10) as $nth) { $i = 1; $lastFoundPrime = 1; $countOfFoundPrimes = 0; while (1) { $quotient = 0; for ($j = 1; $j <= $i; $j++) { $quotient += $i % $j == 0 ? 1 : 0; } if ($quotient == 2) { if ($i - $lastFoundPrime == 2 && ++$countOfFoundPrimes == $nth) { echo "$lastFoundPrime, $i"; break; } $lastFoundPrime = $i; } ++$i; } echo "\n"; } ``` Output: ``` 3, 5 5, 7 11, 13 17, 19 29, 31 41, 43 59, 61 71, 73 101, 103 107, 109 ``` [Answer] **APL(NARS), 63 chars** ``` P;w;p;r w←⎕⋄p←2 →3×⍳0≥w⋄w-←2=p-⍨r←1πp⋄p←r⋄→2 ⎕←∊⍕¨3⌽', ',p,p-2 ``` 7+7+28+17+4=63 test ``` P ⎕: 1 3, 5 P ⎕: 1000 79559, 79561 P ⎕: 100000 18409199, 18409201 ``` [Answer] ## JavaScript (Node.js), 162 chars Reads from stdin, outputs to stdout, exits "early" for input `<= 0`. ``` t=process.argv[2],c=0,l=1;if(t>0){for(i=0;;i++){p=!Array(i+1).join(1).match(/^1?$|^(11+?)\1+$/);if(p){if(i-2==l){if(c>=t-1){console.log(l+", "+i);break}c++}l=i}}} ``` Usage (script above saved as `ntp.js`): ``` >for /l %x in (0, 1, 10) do node ntp.js %x >node ntp.js 0 >node ntp.js 1 3, 5 >node ntp.js 2 5, 7 >node ntp.js 3 11, 13 >node ntp.js 4 17, 19 >node ntp.js 5 29, 31 >node ntp.js 6 41, 43 >node ntp.js 7 59, 61 >node ntp.js 8 71, 73 >node ntp.js 9 101, 103 >node ntp.js 10 107, 109 ``` [Answer] # AWK - 129 The file `fsoe-pairs.awk`: ``` {n=2;N=1 for(;;){if(n in L){p=L[n];del L[n]}else{p=n if(n-N==2)if(!--$0){print N", "n;exit}N=n}P=p+n++ while(P in L)P+=p;L[P]=p}} ``` Running it: ``` $ awk -f fsoe-pairs.awk 1 3, 5 $ awk -f fsoe-pairs.awk 2 5, 7 $ awk -f fsoe-pairs.awk 10 107, 109 ``` (1st line after command is input, the 2nd one is output) This is based on an own prime generator algorithm I call "floating sieve of erastosthenes" (until I find it described elswhere) which only stores the needed part of the sieve and the already calculated primes. [Answer] # Python 2 (75) ``` c=input() n=3 while c:n+=2;c-=all(n%i&~2for i in range(2,n-2)) print(n-2,n) ``` So what's going on here? First, let's look at the expression `all(n%i&~2for i in range(2,n-2))`, which checks if `(n-2,n)` are a pair of twin primes. The simpler expression `all(n%i for i in range(2,n))` simply checks if `n` is prime by trying every divisor `i` in the range `2<=i<=n-1`, and seeing if all remainders are nonzero. This `all` checks exactly this, since Python treats `0` as `False` and all other numbers as `True`. Now, observe that `(n-2)%i==0` exactly when `n%i==2` for divisors `i>2`. So, we can perform the primality check on `n` and `n-2` at the same time by checking the remainders for both `0` and `2`. This could be done as `all(n%i not in [0,2] for i in range(2,n-2))`. We only try divisors in the range `2<=i<=n-3` for the sake of `n-2`, but this suffices for `n` as well since `n-1` and `n-2` can't be divisors unless `n<=4`. We will only try odd `n` starting from `5` to avoid this complication and that of the divisor `i=2`. We golf the expression `n%i not in [0,2]` into `n%i&~2`, remembering that `0` is False and other numbers are `True`. The operator precedence `(n%i)&(~2)` is exactly what's needed. The bit-complement `~2` is `...11111101`, so its bitwise `and` with a number zeroes-out the `2`'s binary place value. This gives `0` (i.e., `False`) only for `0` and `2`, exactly what we want. Phew! Now we have that the expression `all(n%i&~2for i in range(2,n-2))` checks whether `n` is the upper number of a twin prime pair. What remains is to iterate over them until we see `c` of them, where `c` is the inputted number. We start with `5` and counting up by `2` to avoid divisor issues. We decrement `c` each time we encounter an `n` that works, stopping when `c=0`. Finally, we print the twin prime pair that we end with. [Answer] # T-SQL(2012+),255 characters A more compact T-SQL twin prime finder that also gets a little bit of a speed up. ``` with t(n)as(select 2+number from spt_values where type='p')select*from(select concat(b,', ',a),rank()over(order by a)from(select n,lag(n)over(order by n)from t where not exists(select*from t f where f.n<t.n and t.n%f.n=0))z(a,b)where a=b+2)r(s,k)where k=2 ``` Human readable format:: ``` with t(n)as( select 2+number from spt_values where type='p' ) select * from( select concat(b,', ',a),rank() over (order by a) from( select n, lag(n) over(order by n) from t where not exists( select 1 from t f where f.n<t.n and t.n%f.n=0) ) z(a,b) where a=b+2 ) r(s,k) where k=2 ``` The basic gist is we use the built in table of numbers (master..spt\_values type='p') and alias that with a CTE as something short. We add 2 to remove the worry of pulling 0 or 1 trivial errors for our set, so now we have candidates of 2,2050. Z the inner most query gets all primes from 2 to 2050, by filtering out any number n that is divisible by a number less than n. We then use a nifty T-SQL 2012 windowing function `lag` that lets us pull the previous result, so now Z's results a and b are the primes `P[n]` and `P[n-1]` respectively. The R query creates the output string, and filters out non-twin primes and also creates a sequence number for the output we call K. Finally the last query R allows us to filter and get the Kth twin prime by changing its variable. [Answer] **Mathematica -- 71 bytes** ``` n=Input[]; i=j=0; While[j<n,i++;If[And@@PrimeQ[x={i,i+2}],j++]];Print@x ``` [Answer] # PHP 8.3 145char Runs up to 10,000 actually I had difficulty with `readline` simulating `stdin` not using this very often. Programming support: Notepad ``` $j=readline();for($i=1;$i<10000;$i=$i+2){if((gmp_prob_prime($i))&&(gmp_prob_prime($i+2))){$x++;}if($x==$j){break;}}echo"$i, "; $i=$i+2;echo"$i"; ``` ``` $j=readline(); for ($i=1;$i<10000;$i=$i+2) { if ((gmp_prob_prime($i))&&(gmp_prob_prime($i+2))) {$x++;} if($x==$j) {break;} } echo"$i, "; $i=$i+2; echo"$i"; ``` Output $j=[1-12]: ``` 3, 5 5, 7 11, 13 17, 19 29, 31 41, 43 59, 61 71, 73 101, 103 107, 109 137, 139 149, 151 ``` ]
[Question] [ A compound word is a word that contains 2 or more words in it. We can do better than that, though. We need you to **create 1 (nonsensical) word that contains *every* word**. However, we want this word to be as short as possible. We can use overlapping letters to achieve this. For example, if your word list was `["cat", "atom", "a"]`, you would want to return `"catom"`. # Input/Output Your program will need to take a list of words as input, and return a compound word as output. The word list you will be using is the [top 10000 words](https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english.txt) in English, according to Google (If this list turns out to be too easy, I may change it to a longer one). For reference, simply appending each word gives you a score of 65888. Your score is the number of letters in your final word, lower is better. Tie breaker goes to the first poster. [Answer] # C++, final word length: 38272 *(optimised version took about 20 minutes)* ``` #include <iostream> #include <string> #include <vector> std::size_t calcOverlap(const std::string &a, const std::string &b, std::size_t limit, std::size_t minimal) { std::size_t la = a.size(); for(std::size_t p = std::min(std::min(la, b.size()), limit + 1); -- p > minimal; ) { if(a.compare(la - p, p, b, 0, p) == 0) { return p; } } return 0; } int main() { std::vector<std::string> words; // Load all words from input while(true) { std::string word; std::getline(std::cin, word); if(word.empty()) { break; } words.push_back(word); } std::cerr << "Input word count: " << words.size() << std::endl; // Remove all fully subsumed words for(auto p = words.begin(); p != words.end(); ) { bool subsumed = false; for(auto i = words.begin(); i != words.end(); ++ i) { if(i == p) { continue; } if(i->find(*p) != std::string::npos) { subsumed = true; break; } } if(subsumed) { p = words.erase(p); } else { ++ p; } } std::cerr << "After subsuming checks: " << words.size() << std::endl; // Sort words longest-to-shortest (not necessary but doesn't hurt. Makes finding maxlen a tiny bit easier) std::sort(words.begin(), words.end(), [](const std::string &a, const std::string &b) { return a.size() > b.size(); }); std::size_t maxlen = words.front().size(); // Repeatedly combine most-compatible words until there is only one left std::size_t bestPossible = maxlen - 1; while(words.size() > 1) { auto bestA = words.begin(); auto bestB = -- words.end(); std::size_t bestOverlap = 0; for(auto p = ++ words.begin(), e = words.end(); p != e; ++ p) { if(p->size() - 1 <= bestOverlap) { continue; } for(auto q = words.begin(); q != p; ++ q) { std::size_t overlap = calcOverlap(*p, *q, bestPossible, bestOverlap); if(overlap > bestOverlap) { bestA = p; bestB = q; bestOverlap = overlap; } overlap = calcOverlap(*q, *p, bestPossible, bestOverlap); if(overlap > bestOverlap) { bestA = q; bestB = p; bestOverlap = overlap; } } if(bestOverlap == bestPossible) { break; } } std::string newStr = std::move(*bestA); newStr.append(*bestB, bestOverlap, std::string::npos); if(bestA == -- words.end()) { words.pop_back(); *bestB = std::move(words.back()); words.pop_back(); } else { *bestB = std::move(words.back()); words.pop_back(); *bestA = std::move(words.back()); words.pop_back(); } // Remove any words which are now in the result for(auto p = words.begin(); p != words.end(); ) { if(newStr.find(*p) != std::string::npos) { std::cerr << "Now subsumes: " << *p << std::endl; p = words.erase(p); } else { ++ p; } } std::cerr << "Words remaining: " << (words.size() + 1) << " Latest combination: (" << bestOverlap << ") " << newStr << std::endl; words.push_back(std::move(newStr)); bestPossible = bestOverlap; // Merging existing words will never make longer merges possible } std::string result = words.front(); std::cout << result << std::endl; std::cerr << "Word size: " << result.size() << std::endl; return 0; } ``` Verification bash one-liner: ``` cat commonwords.txt | while read p; do grep "$p" merged.txt >/dev/null || echo "Not found: $p"; done ``` It also produced some pretty cool in-progress words. Here are some of my favourites: * polyesterday *(synthetic nostalgia)* * afghanistanbul *(something [insert politician you dislike] would say)* * togethernet *(the friendly internet)* * elephantom *(a large ghost)* * thundergroundwaterproof *(as in "I don't know why they felt the need to make it thundergroundwaterproof, but it's making me nervous")* And: * codescribingo *(maybe an upcoming challenge on this site?)* The final output is on pastebin here: <http://pastebin.com/j3qYb65b> [Answer] # C++11, 38272 letters, proven optimal This algorithm is guaranteed to provide a lower bound on the solution. In this case, it is able to achieve the lower bound and output an optimal 38272 letter solution. (This matches the solution found by Dave’s greedy algorithm. I was surprised and a little disappointed to discover that it’s optimal, but, there we are.) It works by solving the [minimum-cost flow](https://en.wikipedia.org/wiki/Minimum-cost_flow_problem) problem on the network built as follows. * First, any words contained in other words are redundant; discard them. * For every word *w*, draw two nodes *w*\_0 and *w*\_1, where *w*\_0 is a source with capacity 1 and *w*\_1 is a sink with capacity 1. * For every (strict) prefix or suffix *a* of any word, draw a node *a*. * For every suffix *a* of *w*, draw an arc from *w*\_0 to *a* with capacity 1 and cost 0. * For every prefix *a* of *w*, draw an arc from *a* to *w*\_1 with capacity 1 and cost length(*w*) − length(*a*). Any string of length *n* that contains every word can be converted into a flow on this network with cost at most *n*. Therefore, the minimum cost flow on this network is a lower bound on the length of the shortest such string. If we’re lucky—and in this case we are—then after we redirect the flow coming into *w*\_1 back out of *w*\_0, we will find an optimal flow that has just one connected component and that passes through the node for the empty string. If so, it will contain an Eulerian circuit starting and ending there. Such an Eulerian circuit can be read back out as a string of optimal length. If we weren’t lucky, add some extra arcs between the empty string and the shortest strings in the other connected components in order to ensure that an Eulerian circuit exists. The string would no longer necessarily be optimal in that case. I use the [LEMON](http://lemon.cs.elte.hu/) library for its min-cost flow and Eulerian circuit algorithms. (This was my first time using this library, and I was impressed—I will definitely use it again for future graph algorithm needs.) LEMON comes with four different minimum-cost flow algorithms; you can try them here with `--net`, `--cost`, `--cap`, and `--cycle` (default). The program runs in **0.5 seconds**, producing [this output string](https://glot.io/snippets/eh5d81qf04/raw/string.txt). ``` #include <iostream> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> #include <lemon/core.h> #include <lemon/connectivity.h> #include <lemon/euler.h> #include <lemon/maps.h> #include <lemon/list_graph.h> #include <lemon/network_simplex.h> #include <lemon/cost_scaling.h> #include <lemon/capacity_scaling.h> #include <lemon/cycle_canceling.h> using namespace std; typedef lemon::ListDigraph G; struct Word { G::Node suffix, prefix; G::Node tour_node; }; struct Edge { unordered_map<string, Word>::iterator w; G::Arc arc; }; struct Affix { vector<Edge> suffix, prefix; G::Node node; G::Node tour_node; }; template<class MCF> bool solve(const G &net, const G::ArcMap<int> &lowerMap, const G::ArcMap<int> &upperMap, const G::ArcMap<int> &costMap, const G::NodeMap<int> &supplyMap, int &totalCost, G::ArcMap<int> &flowMap) { MCF mcf(net); if (mcf.lowerMap(lowerMap).upperMap(upperMap).costMap(costMap).supplyMap(supplyMap).run() != mcf.OPTIMAL) return false; totalCost = mcf.totalCost(); mcf.flowMap(flowMap); return true; } int main(int argc, char **argv) { clog << "Reading dictionary from stdin" << endl; unordered_map<string, Affix> affixes; unordered_map<string, Word> words; unordered_set<string> subwords; G net, tour; G::ArcMap<int> lowerMap(net), upperMap(net), costMap(net); G::NodeMap<int> supplyMap(net); string new_word; while (getline(cin, new_word)) { if (subwords.find(new_word) != subwords.end()) continue; for (auto i = new_word.begin(); i != new_word.end(); ++i) { for (auto j = new_word.end(); j != i; --j) { string s(i, j); words.erase(s); subwords.insert(s); } } words.emplace(new_word, Word()); } for (auto w = words.begin(); w != words.end(); ++w) { w->second.suffix = net.addNode(); supplyMap.set(w->second.suffix, 1); w->second.prefix = net.addNode(); supplyMap.set(w->second.prefix, -1); for (auto i = w->first.begin(); ; ++i) { affixes.emplace(string(w->first.begin(), i), Affix()).first->second.prefix.push_back(Edge {w}); affixes.emplace(string(i, w->first.end()), Affix()).first->second.suffix.push_back(Edge {w}); if (i == w->first.end()) break; } w->second.tour_node = tour.addNode(); } for (auto a = affixes.begin(); a != affixes.end();) { if (a->second.suffix.empty() || a->second.prefix.empty() || (a->second.suffix.size() == 1 && a->second.prefix.size() == 1 && a->second.suffix.begin()->w == a->second.prefix.begin()->w)) { affixes.erase(a++); } else { a->second.node = net.addNode(); supplyMap.set(a->second.node, 0); for (auto &e : a->second.suffix) { e.arc = net.addArc(e.w->second.suffix, a->second.node); lowerMap.set(e.arc, 0); upperMap.set(e.arc, 1); costMap.set(e.arc, 0); } for (auto &e : a->second.prefix) { e.arc = net.addArc(a->second.node, e.w->second.prefix); lowerMap.set(e.arc, 0); upperMap.set(e.arc, 1); costMap.set(e.arc, e.w->first.length() - a->first.length()); } a->second.tour_node = lemon::INVALID; ++a; } } clog << "Read " << words.size() << " words and found " << affixes.size() << " affixes; "; clog << "created network with " << countNodes(net) << " nodes and " << countArcs(net) << " arcs" << endl; int totalCost; G::ArcMap<int> flowMap(net); bool solved; if (argc > 1 && string(argv[1]) == "--net") { clog << "Using network simplex algorithm" << endl; solved = solve<lemon::NetworkSimplex<G>>(net, lowerMap, upperMap, costMap, supplyMap, totalCost, flowMap); } else if (argc > 1 && string(argv[1]) == "--cost") { clog << "Using cost scaling algorithm" << endl; solved = solve<lemon::CostScaling<G>>(net, lowerMap, upperMap, costMap, supplyMap, totalCost, flowMap); } else if (argc > 1 && string(argv[1]) == "--cap") { clog << "Using capacity scaling algorithm" << endl; solved = solve<lemon::CapacityScaling<G>>(net, lowerMap, upperMap, costMap, supplyMap, totalCost, flowMap); } else if ((argc > 1 && string(argv[1]) == "--cycle") || true) { clog << "Using cycle canceling algorithm" << endl; solved = solve<lemon::CycleCanceling<G>>(net, lowerMap, upperMap, costMap, supplyMap, totalCost, flowMap); } if (!solved) { clog << "error: no solution found" << endl; return 1; } clog << "Lower bound: " << totalCost << endl; G::ArcMap<string> arcLabel(tour); G::Node empty = tour.addNode(); affixes.find("")->second.tour_node = empty; for (auto &a : affixes) { for (auto &e : a.second.suffix) { if (flowMap[e.arc]) { if (a.second.tour_node == lemon::INVALID) a.second.tour_node = tour.addNode(); arcLabel.set(tour.addArc(e.w->second.tour_node, a.second.tour_node), ""); } } for (auto &e : a.second.prefix) { if (flowMap[e.arc]) { if (a.second.tour_node == lemon::INVALID) a.second.tour_node = tour.addNode(); arcLabel.set(tour.addArc(a.second.tour_node, e.w->second.tour_node), e.w->first.substr(a.first.length())); } } } clog << "Created tour graph with " << countNodes(tour) << " nodes and " << countArcs(tour) << " arcs" << endl; G::NodeMap<int> compMap(tour); int components = lemon::stronglyConnectedComponents(tour, compMap); if (components != 1) { vector<unordered_map<string, Affix>::iterator> breaks(components, affixes.end()); for (auto a = affixes.begin(); a != affixes.end(); ++a) { if (a->second.tour_node == lemon::INVALID) continue; int c = compMap[a->second.tour_node]; if (c == compMap[empty]) continue; auto &b = breaks[compMap[a->second.tour_node]]; if (b == affixes.end() || b->first.length() > a->first.length()) b = a; } int offset = 0; for (auto &b : breaks) { if (b != affixes.end()) { arcLabel.set(tour.addArc(empty, b->second.tour_node), b->first); arcLabel.set(tour.addArc(b->second.tour_node, empty), ""); offset += b->first.length(); } } clog << "warning: Found " << components << " components; solution may be suboptimal by up to " << offset << " letters" << endl; } if (!lemon::eulerian(tour)) { clog << "error: failed to make tour graph Eulerian" << endl; return 1; } for (lemon::DiEulerIt<G> e(tour, empty); e != lemon::INVALID; ++e) cout << arcLabel[e]; cout << endl; return 0; } ``` [Answer] # Java 8, ~5 Minutes, Length of 39,279 ``` import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; public class Words { public static void main(String[] args) throws Throwable { File file = new File("words.txt"); List<String> wordsList = new ArrayList<>(); BufferedReader reader = new BufferedReader(new FileReader(file)); String line; while ((line = reader.readLine()) != null) { wordsList.add(line); } reader.close(); Set<String> words = new HashSet<>(); System.out.println("Finished I/O"); for (int i = 0; i < wordsList.size(); i++) { //Step 1: remove any words that occur in other words boolean in = false; for (int j = 0; j < wordsList.size(); j++) { if (i != j && wordsList.get(j).contains(wordsList.get(i))) { in = true; break; } } if (!in) { words.add(wordsList.get(i)); } } System.out.println("Removed direct containers"); List<String> working = words.stream().sorted((c, b) -> Integer.compare(c.length(), b.length())).collect(Collectors.toList()); //Sort by length, shortest first StringBuilder result = new StringBuilder(); result.append(working.get(0)); while (!working.isEmpty()) { Optional<String> target = working.stream().sorted((c, b) -> Integer.compare(firstLastCommonality(result.toString(), b), firstLastCommonality(result.toString(), c))).findFirst(); //Find the string that has the greatest in common with the end of 'result' if(target.isPresent()) { //It really should be present, but just in case String s = target.get(); working.remove(s); int commonality = firstLastCommonality(result.toString(), s); s = s.substring(commonality); result.append(s); } } System.out.println("Finished algorithm"); String r = result.toString(); System.out.println("The string: \n" + r); System.out.println("Length: \n" + r.length()); System.out.println("Verified: \n" + !wordsList.stream().filter(s -> !r.contains(s)).findFirst().isPresent()); } private static int firstLastCommonality(String a, String b) { int count = 0; int len = b.length(); while (!a.endsWith(b) && !b.equals("")) { b = cutLastChar(b); count++; } return len - count; } private static String cutLastChar(String string) { if (string.length() - 1 < 0) { return string; } else { return string.substring(0, string.length() - 1); } } } ``` ### Input: * a file called 'words.txt' in the working directory, in the exact same format as the file in the main post ### Output: ``` Finished I/O Removed direct containers Finished algorithm The string: [Moved to pastebin](http://pastebin.com/iygyR3zL) Length: 39279 Verified: true ``` [Answer] # Python 2, 39254 characters Takes 1-2 minutes to run on my machine, works by taking the longest word and then always adding the word to the result string that has the most strings in common. (Before that all words that are substrings of other words are removed to prevent unnecessary adding to the string.) *Update: Tried to look in both directions, but that doesn't do any better. (maybe it's using words that can be used better later?)* [Link to the word on pastebin.](http://pastebin.com/BwyK6P9r) **first 100 chars:** ``` telecommunicationsawayneillegallynnbabyenbcjrxltdxmlbsrcwvtxxxboxespnycdsriconsentencessexyrsslipodc ``` ### Code: ``` import re import urllib def suffix_dist(w1,w2): for i in range(min(map(len,[w1,w2])))[::-1]: if w1[-i:]==w2[:i]: return i return 0 url="https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english.txt" s=urllib.urlopen(url).read() words=s.split() words.sort(key=len,reverse=True) ## remove words that are substrings of other words anyway for i in range(len(words))[::-1]: if any(words[i] in w for w in words[:i]): words.pop(i) print len(words) words.sort(key=len) w1=words.pop(-1) result=w1 while words: ## get the word with longest shared suffix/prefix w2=max(words,key=lambda x:suffix_dist(w1,x)) print w2 words.pop(words.index(w2)) if w2 in result: break result+=w2[suffix_dist(w1,w2):] w1=w2 print result[:100] print len(result) print "Test:", all(w in result for w in s.split()) ``` [Answer] # Ruby, 39222 characters Uses a similar approach to @KarlKastor in his Python answer, but the starting string is one of the smallest words instead of the largest. Another optimization (I don't know how much it helps) is that in between each addition, it prunes any words that may have already been included in the string due to overlapping words. Runs in a little over 4 minutes on my machine, not counting the web request to retrieve the list of words, but not quite 4:20. [The word on Pastebin.](http://pastebin.com/RippbFJH) ``` require 'net/http' puts "Obtaining word list..." data = Net::HTTP.get(URI'https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english.txt') puts "Word list obtained!" puts "Starting calculation..." time = Time.now words = data.split.sort_by(&:size) words.reject!{|w| words.find{|x| w!=x && x.include?(w)}} string = words.shift def merge_dist(prefix, suffix) [prefix.size,suffix.size].min.downto(0).find{|i| prefix.end_with?(suffix[0,i])} end while words.length > 0 suffix = words.max_by{|w| merge_dist string, w} string += suffix[merge_dist(string, suffix)..-1] words.reject!{|w| string.include? w} end delta = Time.now - time puts "Calculation completed in #{delta} seconds!" puts "Word is #{string.size} chars long." open("word.txt", 'w') << string puts "Word saved to word.txt" ``` [Answer] ## PowerShell v2+, 46152 characters ``` param([System.Collections.ArrayList]$n)$n=$n|sort length -des;while($n){$x=$n.Count;$o+=$n[0];0..$x|%{if($o.IndexOf($n[$_])-ge0){$n.RemoveAt($_)}}}$o ``` Takes the input as a list, casts it into an ArrayList (so we can manipulate it). We `sort` it by `length` in `-des`cending order. Then, `while` we still have words in our input array, do a loop. Each iteration, set helper `$x` to be equal to how many we have left, tack on the next item in the list to our output `$o`, and then trawl through everything still in our list. If the `.IndexOf` is not equal to `-1` (i.e., the word was found somewhere in `$o`), we remove that word from our list of remaining words. Finally, at the end, output `$o`. I don't have access to a Pastebin or similar, so here's the beginning and end of the word for temporary -- `telecommunicationscharacterizationresponsibilitiessublimedirectory...fcmxvtwvfxwujmjsuhjjrxjdbkdxqc`. Which I guess has shaved about 20,000 characters off of the input, so not that bad, I suppose. I'm working on refinements. [Answer] **PHP 46612 characters** This is just a start. I hope to improve it. All I've done so far is remove any word that is a sub-string of another word. I'm working on 3 copies of the array, but the memory doesn't seem to be an issue. ``` <?php set_time_limit(3000); $words=file('https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english.txt'); $words = array_map('trim', $words); usort($words, function ($a, $b) { if (strlen($a) == strlen($b) ){ return 0; } return ( strlen($a) < strlen($b) )? -1 : 1; }); $final_array=$words; $comparison_array=$words; foreach($words as $key => $word){ echo $word."<br>\n"; foreach($comparison_array as $nestedKey => $nestedWord){ if (strlen($nestedWord) <= strlen($word)) { unset($comparison_array[$nestedKey]); continue; } if( strpos($nestedWord,$word) !== FALSE ){ unset($final_array[$key]); $restart=true; break; } } } sort($final_array); $compound=''; $compound = implode($final_array); echo $compound; echo " <br><br>\n\n". strlen($compound); ``` ]
[Question] [ Today, November 11th, is known as [Remembrance Day](https://en.wikipedia.org/wiki/Remembrance_Day), [Armistice Day](https://en.wikipedia.org/wiki/Armistice_Day), or [Veterans Day](https://en.wikipedia.org/wiki/Veterans_Day) (depending upon the country), and is a day of reflection and gratitude for members of the military and their service, specifically started to reflect the end of European hostilities in the first World War. Let us reflect on that with a simple ASCII-art output of `11/11`. Given an input `n`, output an ASCII-art rendition of `11/11` that is `n` units tall. Specifically, each `1` is composed of vertical pipes `||`, the slash is composed of slashes `//`, and each character is two spaces apart. Note that this means varying output widths -- for example, for `n=3` below, see how the "bottom" of the slash is two spaces from the `1` to its left, but is four spaces from the `1` on its right, so that the top of the slash lines up appropriately and is two spaces from the `1` on its right. ``` n = 1 || || // || || n = 2 || || // || || || || // || || n = 3 || || // || || || || // || || || || // || || n = 4 || || // || || || || // || || || || // || || || || // || || n = 5 || || // || || || || // || || || || // || || || || // || || || || // || || ``` and so on. ### Input A single positive integer [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963), `n > 0`. ### Output An ASCII-art representation of `11/11`, following the above rules and examples. Leading/trailing newlines or other whitespace are optional, provided that the characters line up appropriately. ### Rules * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * [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), 57 bytes ``` n=>" ".repeat(n).replace(/./g,"|| || $'//$` || ||\n") ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 24 bytes ``` <ðׄ//J¹FD" ||"2׊««,À ``` [Try it online!](http://05ab1e.tryitonline.net/#code=PMOww5figJ4vL0rCuUZEIiAgfHwiMsOXw4LFoMKrwqssw4A&input=NQ) **Explanation** ``` # implicit input n <ð× # push n-1 spaces „//J # join with "//" ¹F # input times do: D # duplicate top of stack " ||"2× # push " || ||"  # push "|| || " Š # move the top of the stack down 2 places on the stack «« # concatenate the top 3 elements of the stack , # print with newline À # rotate top of stack left ``` **Previous 26 byte version** ``` F"|| "2שð¹N-<ׄ//ðN×®RJ, ``` [Try it online!](http://05ab1e.tryitonline.net/#code=RiJ8fCAgIjLDl8Kpw7DCuU4tPMOX4oCeLy_DsE7Dl8KuUkos&input=MQ) [Answer] ## Perl, 45 bytes *-9 bytes thanks to @Gabriel Benamy* 47 bytes of code + 1 byte for `-n` flag. ``` say$@="|| "x2,$"x$_,"//",$"x++$.,$@while$_-- ``` Run with `-nE` flags : ``` perl -nE 'say$@="|| "x2,$"x$_,"//",$"x++$.,$@while$_--' <<< 5 ``` [Answer] # JavaScript (ES6), ~~88~~ 77 bytes ``` f=(n,i=n)=>i--?`|| || ${" ".repeat(i)}//${" ".repeat(n+~i)} || || `+f(n,i):"" ``` The recursive approach ~~may not be~~ [could not possibly be the shortest](https://codegolf.stackexchange.com/a/99460/42545). --- `.map` version (88 bytes): ``` n=>[...Array(n)].map((_,i)=>`|| || ${" ".repeat(n+~i)}//${" ".repeat(i)} || ||`).join` ` ``` Array comprehension (86 bytes): ``` n=>[for(_ of Array(i=n))`|| || ${" ".repeat(--i)}//${" ".repeat(n+~i)} || ||`].join` ` ``` `for` loop version (89 bytes): ``` n=>{for(a="",i=n;i--;a+=s+" ".repeat(i+2)+`//${" ".repeat(n-i+1)+s} `)s="|| ||";return a} ``` `.replace` version (85 bytes): ``` n=>`|| || q || || `[r="repeat"](n).replace(/q/g,_=>" "[r](--i)+"//"+" "[r](n+~i),i=n) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ⁾| Ḥẋ2µ,Ṛðj ⁶ẋṖ;⁾//ṙḶÇ€Y ``` **[TryItOnline!](http://jelly.tryitonline.net/#code=4oG-fCDhuKThuosywrUs4bmaw7BqCuKBtuG6i-G5ljvigb4vL-G5meG4tsOH4oKsWQ&input=&args=MTE)** ### How? ``` ⁾| Ḥẋ2µ,Ṛðj - Link 1, join two "11"s with: middle ⁾| - string literal: "| " Ḥ - double "|| " ẋ2 - repeat twice "|| || " µ - monadic chain separation , - pair with Ṛ - reversed ["|| || "," || ||"] ð - dyadic chain separation j - join with input "|| || middle || ||" ⁶ẋṖ;⁾//ṙḶÇ€Y - Main link: n e.g. 5 ⁶ - literal ' ' ' ' ẋ - repeat n times " " Ṗ - remove last entry " " ; - concatenate with ⁾// - literal "//" " //" Ḷ - lowered range(n) [0,1,2,3,4] ṙ - rotate left [" //"," // "," // "," // ","// "] Ç€ - call last link (1) as a monad for €ach Y - join with line feeds ``` [Answer] ## Retina, 29 bytes ``` .+ $* . xx$'//$` xx¶ x || ``` Port of my JavaScript solution. Note the space after `$*` and two spaces after `||`. [Answer] # [V](http://github.com/DJMcMayhem/V), 30 bytes ``` 4i|| 2Bi// Àé XÀ«ñÄf/é Elx ``` [Try it online!](http://v.tryitonline.net/#code=NGl8fCAgGzJCaS8vICAbw4DDqSBYw4DCq8Oxw4RmL8OpIEVseA&input=&args=NQ) As usual, here is a hexdump: ``` 0000000: 3469 7c7c 2020 1b32 4269 2f2f 2020 1bc0 4i|| .2Bi// .. 0000010: e920 58c0 abf1 c466 2fe9 2045 6c78 . X....f/. Elx ``` [Answer] ## Batch, 130 bytes ``` @set s=xx// xx @set l=@for /l %%i in (2,1,%1)do @call %l% set s=%%s://= //%% %l%:l :l @echo %s:x=^|^| % @set s=%s: //=// % ``` Not a port of my JavaScript solution. Since `|`s are hard to manipulate in Batch, I use `x`s as placeholders and replace them on output, this conveniently also reduces my code size. Starts by setting `s` to the desired output for `n=1` (`n` is passed on the command line), then inserts spaces as necessary to obtain the first line for the actual value of `n`, then loops through printing the string and shifting the slash left by one character each time. [Answer] # **[BaCon](http://www.basic-converter.org), 71 bytes** A complete BASIC program in one line. ``` INPUT n:FOR x=1 TO n:?"|| ||",SPC$(n-x+2),"//",SPC$(x+1),"|| ||":NEXT ``` [Answer] # Common Lisp, 216 bytes I'm going to state right off the bat that this is an awful solution to the challenge. Nevertheless, it works, and I'm tired. ``` (defun arm (n) (format t "~{|| || ~v,,,vA//~v,,,vA || ||~%~}" (butlast (butlast (butlast (butlast (butlast (butlast (loop for i from 1 to (+ n 1) append `(,(- (+ n 1) i) #\Space #\Space ,i #\Space #\Space)))))))))) ``` Usage: ``` * (arm 4) || || // || || || || // || || || || // || || || || // || || ``` For some reason, instead of doing anything sane, I decided to approach this with a loop inside a `format` call. This loop iterates through the contents returned by the *other* actual loop construct at the very end, with the last six elements removed (thus the repeated `butlast`s). The contents of the value returned by this loop construct consist of a padding count for the front of the slashes, the padding characters (spaces), the padding count for the back of the slashes, and finally the same padding characters. I'm rather new to Lisp, and I understand that there is definitely a lot of room for improvement here. [Answer] # Python 2, ~~76~~ ~~75~~ 71 Bytes Still working on a shorter version, not too bad though. ``` n=input() k='|| ||' for i in range(n):print k,(n-i)*' '+'//'+' '*-~i,k ``` *thanks mbomb007 for catching an error!* [Answer] ## R, 86 bytes Just a simple `for` loop approach: ``` x="|| ||";n=scan();for(i in 1:n)cat(x,rep(" ",2+n-i),"//",rep(" ",1+i),x,"\n",sep="") ``` [Answer] ## [Retina](http://github.com/mbuettner/retina), 40 bytes ``` .+ x $&$* // x ;{:`x || || // // ``` [Try it online!](http://retina.tryitonline.net/#code=LisKeCAkJiQqIC8vICB4Cjt7OmB4Cnx8ICB8fAogICAvLwogIC8vIA&input=NQ) ### Explanation ``` .+ x $&$* // x ``` This turns the input `N` into ``` x S// x ``` Where `S` corresponds to `N` spaces. ``` ;{:`x || || ``` There are two things happening here. `;{:` indicates that this stage and the last one should be run in a loop until they fail to change the string. `:` indicates that the result of this stage should be printed after each iteration and `;` indicates that the final result of the loop (and therefore of the entire program) should *not* be printed. The stage itself just replaces the `x`s with `|| ||` on the first iteration (and does nothing afterwards), so that we now have the first line of the required output (and print it). ``` // // ``` Finally, this shifts the `//` one character to the left, provided there are still at least three spaces left of the `//`. Afterwards we return to the previous stage (which now only prints the current line, since there are no more `x`s) and then repeat. [Answer] # Ruby, 60 bytes ``` ->n{n.times{|i|puts (a='|| || ')+' '*(n-i)+'// '+' '*i+a}} ``` [Answer] # C, ~~116 94~~ 89 bytes ``` c,d;f(a){for(d=a;a--;puts(" || ||"))for(c=-1;c<d;)printf(a-c++?c?" ":"|| || ":"//");} ``` [Try it out on Ideone](http://ideone.com/jNtQ0z) [Answer] # Ruby, ~~76~~ ~~74~~ 73 bytes ``` x="|| ||";n=gets.to_i;puts (1..n).map{|i|x+" "*(n-i+2)+"//"+" "*(i+1)+x} ``` As a function it takes ~~73~~ 72 bytes, counting the definition: ``` def f n,x="|| ||";(1..n).map{|i|x+" "*(n-i+2)+"//"+" "*(i+1)+x}*?\n;end ``` [Answer] # Powershell, 66 bytes ``` $a=read-host;1..$a|%{$s="|| ";$s*2+" "*($a-$_)+"// "+" "*$_+$s*2} ``` [Answer] # C#, 150 Bytes Golfed: ``` string A(int n){string a="",b= "|| ||";for(int i=0;i<n;i++)a+=b+" // ".PadLeft(5+n-i,'\0')+string.Concat(Enumerable.Repeat(" ",i))+b+"\n";return a; ``` Ungolfed: ``` public string A(int n) { string a = "", b = "|| ||"; for (int i = 0; i < n; i++) a += b + " // ".PadLeft(5 + n - i, '\0') + string.Concat(Enumerable.Repeat(" ", i)) + b + "\n"; return a; } ``` Testing: ``` Console.WriteLine(new ArmisticeDayChallenge().A(11)); ``` Output: ``` || || // || || || || // || || || || // || || || || // || || || || // || || || || // || || || || // || || || || // || || || || // || || || || // || || || || // || || ``` [Answer] # Groovy, 63 chars/bytes Here's my attempt with Groovy, using an anonymous closure and simple loops to print the ASCII art to standard output: `{n->n.times{println'|| '*2+' '*(n-it-1)+'//'+' '*it+' ||'*2}}` [You can try it online here](https://groovyconsole.appspot.com/script/5159049351921664). Just click "Edit in console" and then "Execute script". Trying to do the same and returning a string instead of printing, I couldn't get below 71 bytes: `{n->a='';n.times{a+='|| '*2+' '*(n-it-1)+'//'+' '*it+' ||'*2+'\n'};a}` [Answer] # Python 3, 78 bytes ``` a="|| ||" def m(n): for e in range(n):print(a," "*(n-e),"//"," "*(e+1),a) ``` Still trying to shorten... ]
[Question] [ Time for another maze challenge, but not as you know it. The rules for this challenge are a little different than most maze challenges. The tile types are defined as follows: * `S`: The location on the maze you start at * `E`: The location you are trying to get to * `0`: Wall that you can't cross * `+`: Floor that you can cross You can travel in one of six directions: up-left, up-right, left, right, down-left, or down-right. ``` \ / -S- / \ ``` The maze does not wrap. The goal is to find the shortest path string to get from `S` to `E`. ### Input: Input is space separated lines like the mazes shown. No trailing space will follow a line. ### Output: A string of `R`, `L`, and `F` where * `R` rotates you right (clockwise) 60 degrees * `L` rotates you left (counter clockwise) 60 degrees * `F` moves you one space in the direction you are pointing You start pointing `left-up` ***The shortest path is counted by the length of the string produced, not the number of positions visited. Your program must print the shortest path as the solution.*** If the maze is unsolvable you should output *`Invalid maze!`*. (`>>>` is the output) ``` 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 E 0 + 0 0 + + 0 + + 0 + 0 + 0 0 0 0 0 0 + + 0 + + + 0 S 0 0 >>>RFRFFLFLFRFFLFFFLFLFFRFLFLFRFRFRF + 0 0 0 0 0 0 0 0 0 0 0 + + 0 0 0 E 0 + 0 0 + 0 0 0 0 0 0 0 0 + 0 + 0 0 + + + 0 0 + + 0 0 S + 0 0 0 >>>Invalid maze! 0 E S >>>LF E + 0 0 + + + 0 0 S + + >>>FFLF E 0 + 0 + + 0 + S >>>RFFLFF 0 E + 0 0 0 + 0 0 + + + 0 + + + 0 + 0 + 0 + 0 + + + 0 S >>>FFLFLFFRFRFFRFF E 0 + + 0 0 + 0 + + 0 + + + 0 + 0 + 0 0 0 0 0 + + + + 0 + 0 S 0 >>>FLFFRFFRFLF ``` (Note that some of the mazes have other solutions that are the same length but are not listed here) [Answer] # [Hexagony](https://github.com/m-ender/hexagony), 2437 bytes The long-awaited program is here: ``` (.=$>({{{({}}{\>6'%={}{?4=$/./\_><./,{}}{<$<\?{&P'_("'"#<".>........_..\></</(\.|/<>}{0/'$.}_.....><>)<.$)).><$./$\))'"<$_.)><.>%'2{/_.>(/)|_>}{{}./..>#/|}.'/$|\})'%.<>{=\$_.\<$))<>(|\4?<.{.%.|/</{=....$/<>/...'..._.>'"'_/<}....({{>%'))}/.><.$./{}{\>$\|$(<><$?..\\<.}_>=<._..\(/.//..\}\.)))))<...2/|$\){}/{..><>).../_$..$_>{0#{{((((/|#.}><..>.<_.\(//$>))<(/.\.\})'"#4?#\_=_-..=.>(<...(..>(/\")<((.\=}}}\>{}{?<,|{>/...(...>($>{)<.>{=P&/(>//(_.)\}=#=\4#|)__.>"'()'\.'..".(\&P'&</'&\$_></}{)<\<0|\<.}.\"\.(.(.(/(\..{.>}=P/|><.(...(..."/<.{"_{{=..)..>})<|><$}}/\}}&P<\(/._...>\$'/.>}/{}}{)..|/(\'.<(\''"")$/{{}})<..'...}}>3#./\$<}|.}|..$.><${{}/>.}}{{<>(""''/..>){<}\?=}{\._=/$/=_>)\{_\._..>)</{\=._.....>(($>}}<.>5#.\/}>)<>-/(.....{\<>}}{{/)\$>=}}}))<...=...(\?{{{?<\<._...}.><..\}}/..>'P&//(\......(..\})"'/./&P'&P{}}&P'<{}\{{{({{{(.\&P=<.><$"&1}(./'"?&'&"\.|>}{?&"?&'P&/|{/&P''</(\..>P&{/&/}{}&'&},/"&P'&?<.|\}{&?"&P'&P'<._.>"&}\(>))<\=}{}<.{/}&?"&"&/"&"?&}\.|>?&"?&{{}}?&//x'&{((<._\($|(}.\/}{/>=&'P&"&/".{3?<.|\"&P'&P}{}&P'<.>&{}}?&"&'P&\=}}<.}/2?".?''5?"/?1{(}\."..../{},<../&//&"&P'&P'&"&"</{}}{{/>"?1''?.'({/}}{}<..>?&"?&}}$>)|P/<.>"&'P&'P&"&"&{/........._/"\$#1}/._.........|,($<'"}'?/_$P#"$0'${)$})$)|........(>/\.#1?<$<|.....>?&}$>=?&"?&/1$..>I;n;v;a;l;i;d;P0;m;a\|\"(}}({=/..$_...\"&P=},}}&P'<.|><....................;...>1"(}}){=/_....>'P&'P&}}_?&/#.>}?4'%\/<...@;1P;e;z<._><>"))'?=<.$$=..\&P}{&</\"><_'|/'&=}<.>{{.<.........|>(/>3")}}){=/=/_.>}P&"?/"<).}_.>?4{=:<.|_...........\$\2$'>4")}}({/."\{&P'&?/><.?|>P...."/=(>(/./(}{{\..>(<>(<>?5'"((..'/...#,</,}{{\.......;.F>..\(...}....._.._..._..._........__..'$......\.<R..$.>))<$}{{&P'&?}<.\$$.\...................$\.<>L\.\(('_"\>}P&"?&{/__/=(.(<.>_)..<...>....\..._.<.....&?=\}=&?"&<.."'>.\>))<.|>))\.|$.>&"?&{{}=P&}?&=}/{\.>&{{P/{">)<|\{<(|\(_(<>\_\?"&P'&P}{{{&<=_.>\&\?"&?<|'{/(/>{{/_>.{/=/\\.>'P&"?&"?&"?/._(\)\\>?&"/_|.>/.$/|$..\\><..\&?}{{}&P'&<}.._>{<|\{}<._$>-")<.>_)<|{)$|..>}=P&"?&"?/...{"./>'P&/=_\{?(/>(<>\(|)__.\&?}}{}&P<}.$.\&P'&P'&<\})))&=<\)<'.'_,><.>"?&'P&'/.|>?&{{}?&"?/>&"?&"?&}}<.".(\\\&?={&P<{..\"&?"&P'&<.?....|.$'\$/\"/.,.>{}{}=/..>&'P&}{{}P/\{}&P{(&?"&?"<'.(\&?"&<}..\?"&?"&<.>P&={}}?&}}P&'P&/.'.>&"?/..>P&}}{{P/\}&P'&?={&?<$}=\"."\P'<{..\'&P'&<....>'P&{}P&"?&{{<\\..>&/$.>}{?&"?/|'$&.P&$P\$'&P={(/..\P\\.\{&?"&?\...\?{{}=<$&P'&P<.,./<?\...{}=P\"&<.>=P&""'?&'P&'/$.#1.>{?1#=$\&'P/\}&P'&?={(,}<._?_&\&?{=&{*=}4<.>P&"?&"?&'P&/1_$>}?&}}=?&){?/\{}&P'&?={&?#<$ ``` [Try it online!](https://tio.run/##bVVNbxw3DL3nVxgaeSQ1G9LrbHro6qOXFijQw6C9EhACNGgLtOmtSKvhb08fNes4BTJe2zuSSD4@PlK/vfvw9te/3v/z8WOk4mscY8ShOqR@He7L0NEuxTOx9JqJT7aVfZY21i306IJbsqNKt6cTSc2cOQrtnKuOBw6etM/dmmvK5FPCN0/sJaXgsu@U4Lveh8fBnWrktHdYDiWGzcK7UmC/i6ZwT7mOIjCRDD@5xl0uLdOge4vHo1gcj8gwpTAR1eBC56y2g/QQJyVlQCBgGJapl93HDEwN8CUDbi155hKROTyJCiV7Mnw88g7kQ3kcGWGJu0fUXsfDAvrw8L6QIgKYyd3csK@whjshy8Mtl7ZIL/0VUUHK5jeS5S4OxyJJUVWpxn8@7WOmE43C6OsADLCwrRwrcwR9omUpcln21JGvCzEFsewdRUGd1sxhBWmojMJY8sNuWZI4gVP8WLnAYdWy8Q7Y8RbNMah1fRityLNqytj2qiyq65aNHyttFR/AKCiBPHBwh8NAGX@Cc8kzaqnGnRVEtb5eoCefdSd8UAW4xAmu2BsDNXUuBCt9GlmlFZSIemHPpdcko4vFhJJ4SKGbsiJ4UQUvbxYSVuzWVxzn3hDoEI45ia9G61FGU0qEjgcYllltMGIlQ2oWPIDfyQsdZKBsDqjY@NyGpR/yUJn9gl8C0RANUnHrWSNxcG0NKxjeoeW22hs87sMchNkgVLcVr6iJ4qSe2JlvqBlSH2ubbwhiEnarSjQFQRcDaQ5WO@BW2MCzWpQZw5huAP4hrBAibCX6PapxMrgWw2BGNF7POEcMA2CB6jqtnZ0yAUIj/NgctRDeNMftPCIiOSMElT6BK6Dn9QYU/12eCkAk184hNAoRSCdiOvCpohH2DbqqM8zE40ADfRoh7MQvZ@Vbae3ZT9Hn4DQ0dNq2OP8Q/Ehek0/70xn0gtBybphOxxoCIliZYfmMBq0/XN9f/76@vf5x/f36y3V7uP55fSsgIarGUdhaGHZGStHTUWGydvjCc7UAZ7NMsJxI65GOake8Bd3QLuFe2My/vZ6367vrv6gHJobD2GvQivfQoBj9aFBxNfewo1GLyXgMeo67Yy7U1y4dwSxcVfDW2OVks7W2yyjfAGv/DKF4efShXswMVSAnY8qLkVDb60azv0usNuMiimaCxBTEp70JDjOIrAlpOWU@Hdu3zL@vNhlnv9xmfqfn32MN3zD3DyCUf5pdDvl6OJookKN4T/IFaj0M6o@YkzGG7uRIFQrpHWgJmq4dI8bYqYd7i3uQtbaCUWidgXcXKi4ja/Ydf9EhgHBrEcxO6LxgXomJfmw8HEbGLiPjQokdHEiX9tQdwJwLaJbV1lrew2BUBDrvFa1YWGRW37XjA@lGSSImee47YXp7XBp2ucwBg/THbLnVbiVcGxYZjHRfX7k0E8w79L3THMlPTjHKHPEcTKXLaIBgQOOc@uZ09jFcepJbS2ZMrZTWkiXlQKGf7KI9RhGKazMDQKb3ekNvXW/XhsBhQa3ymB1xcAHlTD2SD@IhWaYT2R2l1jx1qh/@NhYDMqJZNYfAuIWsJkh2Emjlwewrc9qozrZhXA71SLNaE1lRZHJkMNDVWsRBxDZ14ebI7qntxk0jI4upeGWU@hi6vAe/0rb6DVcU@npEu843HJM5YpvJx24BLdlP0jJy4jzXTSgywVoRXLjx5jFmkHY7L8ULlp5xxpNVsfUV@Y6yjq@KXmaq7tMFcEaRZ9YYTGm0g6pbkkv2Hz/e3b28e3j@efHZy0vbemHfvptvx9r/jsylF3efbb@c78/2dh7Pz09h/gM "Hexagony – Try It Online") "Readable" version: ``` ( . = $ > ( { { { ( { } } { \ > 6 ' % = { } { ? 4 = $ / . / \ _ > < . / , { } } { < $ < \ ? { & P ' _ ( " ' " # < " . > . . . . . . . . _ . . \ > < / < / ( \ . | / < > } { 0 / ' $ . } _ . . . . . > < > ) < . $ ) ) . > < $ . / $ \ ) ) ' " < $ _ . ) > < . > % ' 2 { / _ . > ( / ) | _ > } { { } . / . . > # / | } . ' / $ | \ } ) ' % . < > { = \ $ _ . \ < $ ) ) < > ( | \ 4 ? < . { . % . | / < / { = . . . . $ / < > / . . . ' . . . _ . > ' " ' _ / < } . . . . ( { { > % ' ) ) } / . > < . $ . / { } { \ > $ \ | $ ( < > < $ ? . . \ \ < . } _ > = < . _ . . \ ( / . / / . . \ } \ . ) ) ) ) ) < . . . 2 / | $ \ ) { } / { . . > < > ) . . . / _ $ . . $ _ > { 0 # { { ( ( ( ( / | # . } > < . . > . < _ . \ ( / / $ > ) ) < ( / . \ . \ } ) ' " # 4 ? # \ _ = _ - . . = . > ( < . . . ( . . > ( / \ " ) < ( ( . \ = } } } \ > { } { ? < , | { > / . . . ( . . . > ( $ > { ) < . > { = P & / ( > / / ( _ . ) \ } = # = \ 4 # | ) _ _ . > " ' ( ) ' \ . ' . . " . ( \ & P ' & < / ' & \ $ _ > < / } { ) < \ < 0 | \ < . } . \ " \ . ( . ( . ( / ( \ . . { . > } = P / | > < . ( . . . ( . . . " / < . { " _ { { = . . ) . . > } ) < | > < $ } } / \ } } & P < \ ( / . _ . . . > \ $ ' / . > } / { } } { ) . . | / ( \ ' . < ( \ ' ' " " ) $ / { { } } ) < . . ' . . . } } > 3 # . / \ $ < } | . } | . . $ . > < $ { { } / > . } } { { < > ( " " ' ' / . . > ) { < } \ ? = } { \ . _ = / $ / = _ > ) \ { _ \ . _ . . > ) < / { \ = . _ . . . . . > ( ( $ > } } < . > 5 # . \ / } > ) < > - / ( . . . . . { \ < > } } { { / ) \ $ > = } } } ) ) < . . . = . . . ( \ ? { { { ? < \ < . _ . . . } . > < . . \ } } / . . > ' P & / / ( \ . . . . . . ( . . \ } ) " ' / . / & P ' & P { } } & P ' < { } \ { { { ( { { { ( . \ & P = < . > < $ " & 1 } ( . / ' " ? & ' & " \ . | > } { ? & " ? & ' P & / | { / & P ' ' < / ( \ . . > P & { / & / } { } & ' & } , / " & P ' & ? < . | \ } { & ? " & P ' & P ' < . _ . > " & } \ ( > ) ) < \ = } { } < . { / } & ? " & " & / " & " ? & } \ . | > ? & " ? & { { } } ? & / / x ' & { ( ( < . _ \ ( $ | ( } . \ / } { / > = & ' P & " & / " . { 3 ? < . | \ " & P ' & P } { } & P ' < . > & { } } ? & " & ' P & \ = } } < . } / 2 ? " . ? ' ' 5 ? " / ? 1 { ( } \ . " . . . . / { } , < . . / & / / & " & P ' & P ' & " & " < / { } } { { / > " ? 1 ' ' ? . ' ( { / } } { } < . . > ? & " ? & } } $ > ) | P / < . > " & ' P & ' P & " & " & { / . . . . . . . . . _ / " \ $ # 1 } / . _ . . . . . . . . . | , ( $ < ' " } ' ? / _ $ P # " $ 0 ' $ { ) $ } ) $ ) | . . . . . . . . ( > / \ . # 1 ? < $ < | . . . . . > ? & } $ > = ? & " ? & / 1 $ . . > I ; n ; v ; a ; l ; i ; d ; P 0 ; m ; a \ | \ " ( } } ( { = / . . $ _ . . . \ " & P = } , } } & P ' < . | > < . . . . . . . . . . . . . . . . . . . . ; . . . > 1 " ( } } ) { = / _ . . . . > ' P & ' P & } } _ ? & / # . > } ? 4 ' % \ / < . . . @ ; 1 P ; e ; z < . _ > < > " ) ) ' ? = < . $ $ = . . \ & P } { & < / \ " > < _ ' | / ' & = } < . > { { . < . . . . . . . . . | > ( / > 3 " ) } } ) { = / = / _ . > } P & " ? / " < ) . } _ . > ? 4 { = : < . | _ . . . . . . . . . . . \ $ \ 2 $ ' > 4 " ) } } ( { / . " \ { & P ' & ? / > < . ? | > P . . . . " / = ( > ( / . / ( } { { \ . . > ( < > ( < > ? 5 ' " ( ( . . ' / . . . # , < / , } { { \ . . . . . . . ; . F > . . \ ( . . . } . . . . . _ . . _ . . . _ . . . _ . . . . . . . . _ _ . . ' $ . . . . . . \ . < R . . $ . > ) ) < $ } { { & P ' & ? } < . \ $ $ . \ . . . . . . . . . . . . . . . . . . . $ \ . < > L \ . \ ( ( ' _ " \ > } P & " ? & { / _ _ / = ( . ( < . > _ ) . . < . . . > . . . . \ . . . _ . < . . . . . & ? = \ } = & ? " & < . . " ' > . \ > ) ) < . | > ) ) \ . | $ . > & " ? & { { } = P & } ? & = } / { \ . > & { { P / { " > ) < | \ { < ( | \ ( _ ( < > \ _ \ ? " & P ' & P } { { { & < = _ . > \ & \ ? " & ? < | ' { / ( / > { { / _ > . { / = / \ \ . > ' P & " ? & " ? & " ? / . _ ( \ ) \ \ > ? & " / _ | . > / . $ / | $ . . \ \ > < . . \ & ? } { { } & P ' & < } . . _ > { < | \ { } < . _ $ > - " ) < . > _ ) < | { ) $ | . . > } = P & " ? & " ? / . . . { " . / > ' P & / = _ \ { ? ( / > ( < > \ ( | ) _ _ . \ & ? } } { } & P < } . $ . \ & P ' & P ' & < \ } ) ) ) & = < \ ) < ' . ' _ , > < . > " ? & ' P & ' / . | > ? & { { } ? & " ? / > & " ? & " ? & } } < . " . ( \ \ \ & ? = { & P < { . . \ " & ? " & P ' & < . ? . . . . | . $ ' \ $ / \ " / . , . > { } { } = / . . > & ' P & } { { } P / \ { } & P { ( & ? " & ? " < ' . ( \ & ? " & < } . . \ ? " & ? " & < . > P & = { } } ? & } } P & ' P & / . ' . > & " ? / . . > P & } } { { P / \ } & P ' & ? = { & ? < $ } = \ " . " \ P ' < { . . \ ' & P ' & < . . . . > ' P & { } P & " ? & { { < \ \ . . > & / $ . > } { ? & " ? / | ' $ & . P & $ P \ $ ' & P = { ( / . . \ P \ \ . \ { & ? " & ? \ . . . \ ? { { } = < $ & P ' & P < . , . / < ? \ . . . { } = P \ " & < . > = P & " " ' ? & ' P & ' / $ . # 1 . > { ? 1 # = $ \ & ' P / \ } & P ' & ? = { ( , } < . _ ? _ & \ & ? { = & { * = } 4 < . > P & " ? & " ? & ' P & / 1 _ $ > } ? & } } = ? & ) { ? / \ { } & P ' & ? = { & ? # < $ ``` Tested on Esoteric IDE: TIO might time out on some of the larger test cases but all verified. Many thanks to Timwi, this wouldn't have been possible without the IDE. There's quite a bit of empty space, so I might have been able to fit this onto a side-length 28 hexagon (instead of side-length 29) but that will be a massive task so I'm probably not going to attempt it. # Basic Explanation Click the images for a larger and more detailed version. ## Functions [![Functions](https://i.stack.imgur.com/gtYOGm.png)](https://i.stack.imgur.com/gtYOG.png) *Note: Divisions are generally correct but may occasionally be a rough guess.* This code is quite "functional" - as much as Hexagony allows it to be. There are eight main functions in this code labelled in the above diagram, named by the numbers with which they are called (so their instruction pointer numbers are that number mod 6). In (rough) order of calling, they are (quoted names are locations in memory which will be explained later): * S: The starting function - reads the input and sets up the "reference array", then starts the "path stack" with the three paths `F`, `R` and `L` ready for main processing. Instruction pointer 0 moves to function 0 while the execution moves to function 1. * 1 (-11): The main function - uses 2 to get a path, 3 to check its validity, and if valid goes to function -110/-10 twice and then 4 three times to copy the new paths across into the "path stack", finishing by returning to itself. May call function 5 if the path is at the end location. * 2: Gets the next path off the "path stack" ready for processing, calls function -1 if no paths left on the stack. Returns to function 1. * 3: Takes a pair of values as well as the move number and checks the "reference array" to see whether the current path has ended at a valid location. A valid location is either the start within the first 3 moves, or any `+` within 2 moves of it first being reached. Returns to function 1. * -10/-110: Copies the current path. Returns to function 1. * 0: Helps function 1 to manage direction of movement with `F`. Returns to function 1. * 4: Takes a copy of the current path and interlinked with function 1 changes it into the same path with either `F`, `R` or `L` appended. Returns to function 1. * 5: Takes the path and prints out the correct path (e.g. `FFLF`), then terminates the program. * -1: Prints `Invalid maze!` and terminates. * (Double arrows): Due to lack of space, function 1/-11 had to go off into the space above function -1. ## Memory [![Memory layout](https://i.stack.imgur.com/AROSym.png)](https://i.stack.imgur.com/AROSy.png) Note: Thanks to Esoteric IDE again for the diagram The memory consists of three main parts: * Reference array: The grid is stored columns 2 apart, with a value at each step: + 0 represents either a , `0` or a valid place that was accessed more moves ago than would be required to exit the place in any direction. + 1 represents a `+` that hasn't yet been reached. + (higher number) represents the move number where there will have been enough moves to exit the place in any direction. + 10 also represents a new-line: these are never reached assuming they immediately follow the last non-white-space character. * Rail: Consists of `-1`s with a single `-2` on the left, allows memory pointer to quickly return to the core processing area. * Path stack: Stores each of the untested paths in order by path ID (which is directly related to move number so the shorter paths are tested first). The path is stored as follows: [![Path layout](https://i.stack.imgur.com/hx6JBt.png)](https://i.stack.imgur.com/hx6JB.png) + Rot: the rotation at the end of the current path: 0 for up-left and increasing clockwise to 5 + Move: the current move number (instructions - 1) + Path: the current path, stored in quaternary with `F`, `R`, `L` as `1`, `2`, `3` respectively + x/y: coordinates at the end of the current path: x+1 `-1`s right then y values up (though y=0 is processed as 1 anyway for the purposes of separating the rail from the reference data) Other important memory locations: 1. The x/y of the `E` is stored here. 2. This space is used to transition paths in and out of memory. 3. This location is the centre of where each path is stored during processing. [Answer] # Python 2, 291 bytes ``` def f(M): Y=map(max,M).index("S");X=M[Y].find("S");V={()};Q=[(0,0,0,1,"")] while Q: try:x,y,u,v,p=s=Q.pop(0);c=(Y>=y<=X-2*x)*ord(M[Y-y][X-2*x-y]) except:c=0 if c==69:return p if{c%2*s[:4]}-V:V|={s[:4]};Q+=(x+u,y+v,u,v,p+"F"),(x,y,-v,u+v,p+"R"),(x,y,u+v,-u,p+"L") return"Invalid maze!" ``` A function, `f`, taking the maze as a list of rows, and returning a solution, if one exists. ## Explanation Performs a breadth-first search on the graph of position/direction pairs to find the shortest path from `S` to `E`. What's interesting is finding a compact way to represent positions and directions on a hexagonal grid, that admits simple "stepping" (i.e., moving in a certain direction) and rotation. It's tempting to use complex numbers here, to represent coordinates on a "real" hexagonal grid, but this is not a very good idea for a number of reasons, the most serious of which is the fact that we need to plug in a √3 somewhere to make it work (sin 60° = √3/2), which, when using floating-point numbers, is a no go if we need absolute precision (e.g., for keeping track of the states we've already visited;) you can try firing up your JavaScript console and typing `Math.sqrt(3)*Math.sqrt(3) == 3` and see for yourself. But, we can use a little trick! Instead of using complex numbers, let's define *hexagonal numbers* in a similar vein, as a pair of real numbers *a* + *bh*, where *h* plays a similar role to the imaginary *i* when dealing with complex numbers. Just like with complex numbers, we can associate the pair (*a*, *b*) with a point on the plane, where the real axis points right, the imaginary axis points 60° up, and they both intersect the unit regular hexagon when the real and the imaginary parts equal 1, respectively. Mapping this coordinate system to the cells of the maze is trivial. [![Figure 1](https://i.stack.imgur.com/wJIVU.png)](https://i.stack.imgur.com/wJIVU.png) Unlike *i*, the constant *h* is defined by the relation *h*2 = *h* - 1 (solving for *h* might reveal some insights.) And that's it! Hexagonal numbers can be added and multiplied, using the above relation, much like complex numbers: (*a* + *bh*) + (*c* + *dh*) = (*a* + *c*) + (*b* + *d*)*h*, and (*a* + *bh*) · (*c* + *dh*) = (*ac* - *bd*) + (*ad* + *bc* + *bd*)*h*. These operations have the same geometric interpretation as their complex counterparts: addition is vector addition, and multiplication is scaling and rotation. In particular, to rotate a hexgonal number 60° counter-clockwise, we multiply it by *h*: (*a* + *bh*) · *h* = -*b* + (*a* + *b*)*h*, and to rotate the same number 60° clockwise, we divide by *h*: (*a* + *bh*) / *h* = (*a* + *bh*) · (1 - *h*) = (a + b) - *ah*. For example, we can take the unit hexagonal number pointing right, 1 = (1, 0), a full circle, going counter-clockwise, by multiplying it by *h* six times: (1, 0) · *h* = (0, 1); (0, 1) · *h* = (-1, 1); (-1, 1) · *h* = (-1, 0); (-1, 0) · *h* = (0, -1); (0, -1) · *h* = (1, -1); (1, -1) · *h* = (1, 0). The program uses hexagonal numbers in this fashion to represent the current position in the maze and the current direction, to advance in the specified direction, and to rotate the direction to the left and to the right. [Answer] # Python 3, 466 bytes Would have probably ended up smaller if I used depth-first search or something. This monstrosity uses Dijkstra and is quite fast, but very long. The code defines a function `S` that takes a multiline string with the maze and returns the result. ``` def F(M,L,c):y=M[:M.index(c)].count("\n");return L[y].index(c),y def S(M): L=M.split("\n");Q=[("",)+F(M,L,"S")+(0,)];D={};R=range;H=len;U=R(2**30) while Q: C,*Q=sorted(Q,key=H);w,x,y,d=C for e in R(H(L)>y>-1<x<H(L[y])>0<H(D.get(C[1:],U))>H(w)and(L[y][x]in"+SE")*6):D[C[1:]]=w;E=(d+e)%6;Q+=[(w+",R,RR,RRR,LL,L".split(",")[e]+"F",x+[-1,1,2,1,-1,-2][E],y+[-1,-1,0,1,1,0][E],E)] J=min([D.get(F(M,L,"E")+(d,),U)for d in R(6)],key=H);return[J,"Invalid maze!"][J==U] ``` [Here is a test of the code.](http://ideone.com/oJgKn2) ### Ungolfed ``` def find_char(maze, lines, char): y = maze[:maze.index(char)].count("\n") return lines[y].index(char), y def solve(maze): lines = maze.split("\n") x, y = find_char(maze, lines, "S") queue = [("", x, y, 0)] solutions = {} very_long = range(2**30) x_for_direction = [-1,1,2,1,-1,-2] y_for_direction = [-1,-1,0,1,1,0] rotations = ["","R","RR","RRR","LL","L"] while len(queue) > 0: queue = sorted(queue, key=len) current, *queue = queue route, x, y, direction = current if 0 <= y < len(lines) and 0 <= x < len(lines[y]) and lines[y][x] in "+SE" and len(solutions.get(current[1:], very_long)) > len(route): solutions[current[1:]] = route for change in range(6): changed = (direction + change) % 6 queue += [(route + rotations[change] + "F", x + x_for_direction[changed], y + y_for_direction[changed], changed)] end_x, end_y = find_char(maze, lines, "E") solution = min([solutions.get((end_x, end_y, direction), very_long) for direction in range(6)], key=len) return "Invalid maze!" if solution == very_long else solution ``` [Answer] # Groovy, 624 bytes. *Fore!* Time time get the ball rolling with a big one. Takes multi-line string as arg to `Q` ``` Q={a->d=[0]*4 a.eachWithIndex{x,y->f=x.indexOf('S');e=x.indexOf('E'); if(f!=-1){d[0]=f;d[1]=y} if(e!=-1){d[2]=e;d[3]=y}} g=[] s={x,y,h,i,j->if(h.contains([x, y])|y>=a.size()||x>=a[y].size()|x<0|y<0)return;k = a[y][x] def l=h+[[x, y]] def m=j def n=1 if(h){ o=h[-1] p=[x,y] q=[p[0]-o[0],p[1]-o[1]] n=[[-2,0]:0,[-1,-1]:1,[1,-1]:2,[2,0]:3,[1,1]:4,[-1,1]:5][q] r=n-i m=j+((r==-5|r==5)?' LR'[(int)r/5]:['','R','RR','LL','L'][r])+'F'} if(k=='E')g+=m if(k=='+'|k=='S'){s(x-2,y,l,n,m) s(x+2,y,l,n,m) s(x+1,y+1,l,n,m) s(x+1,y-1,l,n,m) s(x-1,y+1,l,n,m) s(x-1,y-1,l,n,m)}} s(d[0],d[1],[],1,'') print(g.min{it.size()}?:"Invalid maze!")} ``` Ungolfed version: ``` def map = """ + 0 0 0 0 0 0 0 0 0 0 0 + + 0 0 0 E 0 + 0 0 + 0 0 0 0 0 0 0 0 + 0 + 0 0 + + + 0 0 + + 0 0 S + 0 0 0""".split('\n').findAll() //map = // """ // 0 + + //E + 0 S 0 // 0 0 0 + // + + +""".split('\n').findAll() //map = [""]// TODO remove this, this is type checking only //map.remove(0) //reader = System.in.newReader() //line = reader.readLine() //while (line != '') { // map << line // line = reader.readLine() //} startAndEnd = [0, 0, 0, 0] map.eachWithIndex { it, idx -> s = it.indexOf('S'); e = it.indexOf('E'); if (s != -1) { startAndEnd[0] = s; startAndEnd[1] = idx } if (e != -1) { startAndEnd[2] = e; startAndEnd[3] = idx } } def validPaths = [] testMove = { x, y, visited ->// visited is an array of x y pairs that we have already visited in this tree if (visited.contains([x, y]) || y >= map.size() || x >= map[y].size() || x < 0 || y < 0) return; def valueAtPos = map[y][x] def newPath = visited + [[x, y]] if (valueAtPos == 'E') validPaths += [newPath] if (valueAtPos == '+' || valueAtPos == 'S') { println "$x, $y passed $valueAtPos" testMove(x - 2, y, newPath) testMove(x + 2, y, newPath) testMove(x + 1, y + 1, newPath) testMove(x + 1, y - 1, newPath) testMove(x - 1, y + 1, newPath) testMove(x - 1, y - 1, newPath) } } //if (!validPath) invalid() testMove(startAndEnd[0], startAndEnd[1], []) println validPaths.join('\n') //println validPath def smallest = validPaths.collect { def path = '' def orintation = 1 it.inject { old, goal -> def chr = map[goal[1]][goal[0]] def sub = [goal[0] - old[0], goal[1] - old[1]] def newOrin = [[-2, 0]: 0, [-1, -1]: 1, [1, -1]: 2, [2, 0]: 3, [1, 1]:4, [-1, 1]:5][sub] def diff = newOrin - orintation// 5L -5R def addedPath= ((diff==-5||diff==5)?' LR'[(int)diff/5]:['', 'R', 'RR', 'LL', 'L'][diff]) + 'F'//(diff == 0) ? '' : (diff > 0 ? 'R'*diff : 'L'*(-diff)) + 'F' // println "old:$old, goal:$goal chr $chr, orintation $orintation, sub:$sub newOrin $newOrin newPath $addedPath diff $diff" path += addedPath orintation = newOrin goal } path }.min{it.size()} //println "paths:\n${smallest.join('\n')}" if (smallest) println "path $smallest" else println "Invalid maze!" ``` [Answer] # C#, ~~600~~ 574 bytes Complete program, accepts input from STDIN, output to STDOUT. *Edit: there was a bug in the wrap handling (didn't break on any of the given test cases) which would have added 1 byte, so I did a bit more golfing to compensate.* ``` using Q=System.Console;struct P{int p,d;static void Main(){string D="",L;int w=0,W=0,o,n=1;for(;(L=Q.ReadLine())!=null;D+=L)w=(o=(L+="X").Length+1)>w?o:w;for(;W<D.Length;)D=D.Insert(W+1,"".PadLeft(D[W++]>87?w-W%w:0));P[]K=new P[W*6];var T=new string[W*6];P c=K[o=0]=new P{p=D.IndexOf('S')};for(System.Action A=()=>{if(c.p>=0&c.p<W&System.Array.IndexOf(K,c)<0&&D[c.p]%8>0){T[n]=T[o]+L;K[n]=c;n=D[c.p]==69?-n:n+1;}};o<n;o++){c=K[o];L="R";c.d=++c.d%6;A();L="L";c.d=(c.d+4)%6;A();L="F";c=K[o];c.p+=new[]{~w,1-w,2,1+w,w-1,-2}[c.d%6];A();}Q.WriteLine(n>0?"Invalid maze!":T[-n]);}} ``` It starts by reading in the map, appending `(` to each line so that it knows where it ends, and can go back and add in a load of spaces to make the map rectangular, and with a row of spaces along the right side (this saves us doing wrapping checks as will be explained below). It works out the width of rectangle at some point in this, and ascertains the total length of the Map. Next, it initialises everything for a Breadth-First-Search. Two biggish arrays are created, one to store all the states we need to explore in our search, the other to record the route we took to get to each state. The initial state is added to the due array, with the head and tail pointers pre-set someway above. Everything is 1-indexed. We then iterate until the tail crashes into the head, or at least it *appears* to have crashed into the head. For each state we've visited, we attempt to add a new state at the same position where we are rotated left or right, and then one where we have moved forward. The directions are indexed, with the initial direction (defaulting to `0`) corresponding to "up-left". When we try to queue a state, it is bound checked, but not wrap checked, because of the columns of spaces on the right side, which is picked up on by the "are we allowed to be here?" check (you aren't allowed to be on spaces). If the state is queued, we then check if it's on the `E` cell, and if it is, we set the head of the queue to be minus itself, which causes the main loop to exit, and tells the last line of the program to print out the corresponding route, rather than the failure message (which shows if we run out of states to expand (the tail crashes into the head)). ``` using Q=System.Console; // mod 8 table (the block of zeros is what we are after - it's everywhere we /can't/ go) // 0 (space) // O 0 // X 0 // S 3 // + 3 // E 5 struct P { int p,d; static void Main() { // it's probably a bad thing that I have my own standards for naming this stupid read sequence by now string D="", // map L; // line/path char int w=0, // width W=0, // full length o, // next state to expand n=1; // next state to fill for(;(L=Q.ReadLine())!=null;D+=L) // read in map w=(o=(L+="X").Length+1)>w?o:w; // assertain max length (and mark end, and remove any need for wrap checking) // now we need to add those trailing spaces... for(;W<D.Length;) D=D.Insert(W+1,"".PadLeft(D[W++]>87?w-W%w:0)); // inject a load of spaces if we hit an X P[]K=new P[W*6]; // create space for due states (can't be more states than 6*number of cells) var T=new string[W*6]; // create space for routes (never done it this way before, kind of exciting :D) P c=K[o=0]=new P{p=D.IndexOf('S')}; // set first state (assignment to c is just to make the lambda shut up about unassigned variables) // run bfs for( System.Action A=()=> // this adds c to the list of states to be expanded, if a whole load of checks pass { if(//n>0& // we havn't already finished - we don't need this, because we can't win on the first turn, so can't win unless we go forward, which we check last c.p>=0&c.p<W& // c is within bounds System.Array.IndexOf(K,c)<0&& // we havn't seen c yet (the && is to prevent the following lookup IOBing) D[c.p]%8>0) // and we can move here (see table at top of code) { T[n]=T[o]+L; // store route K[n]=c; // store state n=D[c.p]==69?-n:n+1; // check if we are at the end, if so, set n to be negative of itself so we know, and can look up the route (otherwise, increment n) } } ;o<n;o++) // o<n also catches n<0 { c=K[o]; // take current L="R"; // say we are going right c.d=++c.d%6; // turn right A(); // go! L="L"; // say we are going left c.d=(c.d+4)%6; // turn left A(); // go! L="F"; // say we - you get the picture c=K[o]; c.p+=new[]{~w,1-w,2,1+w,w-1,-2}[c.d%6]; // look up direction of travel (~w = -w-1) A(); } // check if we visited the end Q.WriteLine(n>0?"Invalid maze!":T[-n]); // if n<0, then we found the end, so spit out the corresponding route, otherwise, the maze is invlida } } ``` Like most of my Graph-Searches on this site, I am making good use of C# structs, which default to compare by literal value. [Answer] # Python 2, 703 bytes Not as good as the other two versions, but at least it works haha. Set `M` to the maze. Since I have no experience at solving mazes, it just goes by a brute force approach, where it'll find all the solutions it can that doesn't involve crossing back over itself. It calculates the turns from the shortest ones, and then chooses the shortest result from that. ``` z=zip;d=z((-1,1,-2,2,-1,1),(-1,-1,0,0,1,1));E=enumerate;D={};t=tuple;o=list;b=o.index for y,i in E(M.split('\n')): for x,j in E(o(i)): c=(x,y);D[c]=j if j=='S':s=c if j=='E':e=c def P(s,e,D,p): p=o(p);p.append(s);D=D.copy();D[s]='' for i in d: c=t(x+y for x,y in z(s,i)) if c not in p and c in D: if D[c]=='E':L.append(p+[c]) if D[c]=='+':P(c,e,D,p) def R(p): a=[0,1,3,5,4,2];h=d[0];x=p[0];s='' for c in p[1:]: r=t(x-y for x,y in z(c,x));n=0 while h!=r:n+=1;h=d[a[(b(a,b(d,h))+1)%6]] s+=['L'*(6-n),'R'*n][n<3]+'F';x=t(x+y for x,y in z(x,h)) return s L=[];P(s,e,D,[]) try:l=len(min(L)) except ValueError:print"Invalid maze!" else:print min([R(i)for i in L if len(i)==l],key=len) ``` Messy ungolfed version: ``` maze = """ 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 E 0 + 0 0 + + 0 + + 0 + 0 + 0 0 0 0 0 0 + + 0 + + + 0 S 0 0 """ directions = [(-1, -1), (1, -1), (-2, 0), (2, 0), (-1, 1), (1, 1)] maze_dict = {} maze_lines = maze.split('\n') for y, row in enumerate(maze_lines): if row: for x, item in enumerate(list(row)): coordinates = (x, y) maze_dict[coordinates] = item if item == 'S': start = coordinates elif item == 'E': end = coordinates list_of_paths = [] def find_path(start, end, maze_dict, current_path=None): if current_path is None: current_path = [] current_path = list(current_path) current_path.append(start) current_dict = maze_dict.copy() current_dict[start] = '0' for direction in directions: new_coordinate = (start[0] + direction[0], start[1] + direction[1]) if new_coordinate in current_path: pass elif new_coordinate in current_dict: if current_dict[new_coordinate] == 'E': list_of_paths.append(current_path + [new_coordinate]) break elif current_dict[new_coordinate] == '+': find_path(new_coordinate, end, current_dict, current_path) find_path(start, end, maze_dict) def find_route(path): heading_R = [0, 1, 3, 5, 4, 2] heading = (-1, -1) current_pos = path[0] current_heading = directions.index(heading) output_string = [] for coordinate in path[1:]: required_heading = (coordinate[0] - current_pos[0], coordinate[1] - current_pos[1]) count_R = 0 while heading != required_heading: count_R += 1 heading_index = directions.index(heading) heading_order = (heading_R.index(heading_index) + 1) % len(heading_R) heading = directions[heading_R[heading_order]] if count_R: if count_R > 3: output_string += ['L'] * (6 - count_R) else: output_string += ['R'] * count_R output_string.append('F') current_pos = (current_pos[0] + heading[0], current_pos[1] + heading[1]) return ''.join(output_string) routes = [] try: min_len = len(min(list_of_paths)) except ValueError: print "Invalid maze!" else: for i in list_of_paths: if len(i) == min_len: routes.append(find_route(i)) print 'Shortest route to end: {}'.format(min(routes, key=len)) ``` ]
[Question] [ Given (by any means) two different natural numbers (of any reasonable size), output (by any means) the square of their sum as in the examples below: Given 4 and 3, output: ``` 12 12 12 12 9 9 9 12 12 12 12 9 9 9 12 12 12 12 9 9 9 16 16 16 16 12 12 12 16 16 16 16 12 12 12 16 16 16 16 12 12 12 16 16 16 16 12 12 12 ``` Given 1 and 3, output: ``` 3 9 9 9 3 9 9 9 3 9 9 9 1 3 3 3 ``` Whitespace may vary within reason but the columns must be left-aligned, right-aligned, or (pseudo-)centered. A trailing newline is fine, but standard loopholes are not. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so include a header like `# LanguageName, 123` in your answer, where the number is chars (bytes for languages that are not text-based). Packing code to large Unicode chars is not allowed. --- **Bonus:** -3 if your code outputs just one square when one of the numbers is 0; e.g. given 0 and 3, output: ``` 9 9 9 9 9 9 9 9 9 ``` [Answer] ## J, 9 bytes - 3 = 6 ``` #~@|.*/#~ ``` Inspired by [@NBZ's APL answer](https://codegolf.stackexchange.com/a/61279/32014), golfed down by @randomra. This defines a verb that takes in an array of numbers. It's used as follows: ``` (#~@|.*/#~) 4 3 12 12 12 12 9 9 9 12 12 12 12 9 9 9 12 12 12 12 9 9 9 16 16 16 16 12 12 12 16 16 16 16 12 12 12 16 16 16 16 12 12 12 16 16 16 16 12 12 12 ``` I also claim the 3-byte bonus, since an input of 0 produces sub-matrices of size zero: ``` (#~@|.*/#~) 4 0 16 16 16 16 16 16 16 16 16 16 16 16 16 16 16 16 (#~@|.*/#~) 0 3 9 9 9 9 9 9 9 9 9 ``` ## Explanation J has a definite edge in this challenge. In addition to eating array manipulation problems for breakfast, it prints 2D matrices in the correct format by default. ``` #~ Replicate each number n in input n times #~@|. The same for reversed input */ Compute their multiplication table ``` [Answer] # Octave, 45 bytes - 3 = 42 ``` s=@(m,n)[a=ones(n,1)*n;b=ones(m,1)*m].*[b;a]' ``` ### Explanation This constructs two vectors (let's assume `m = 4` and `n = 3`): `ones(n, 1)` constructs an array of ones of size `n x 1`, so multiplying the ones by `n` we get: ``` ones(n, 1) * n => [3 3 3]' (where ' is transpose... n x 1 is a column vector) a = [3 3 3 4 4 4 4]' %// a is a column vector b = [4 4 4 4 3 3 3] %// b is a row vector ``` Then the vectors are multiplied in an element-wise fashion, with automatic broadcast expansion so that the 7-element vectors produce a 7x7-element matrix: ``` [3] .* [4 4 4 4 3 3 3] [3] [3] [4] [4] [4] [4] ``` For example, multiplication of the first row of `a` by `b` gives: ``` [3] .* [4 4 4 4 3 3 3] = [12 12 12 12 9 9 9] ``` And similarly for the remaining rows of `a`. ### Output: ``` >> s(4,3) ans = 12 12 12 12 9 9 9 12 12 12 12 9 9 9 12 12 12 12 9 9 9 16 16 16 16 12 12 12 16 16 16 16 12 12 12 16 16 16 16 12 12 12 16 16 16 16 12 12 12 >> s(3,0) ans = 9 9 9 9 9 9 9 9 9 ``` You can try it here on [ideone](http://ideone.com/Ube8ft) [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 10-3 = 7 Inspired\* by [this answer](https://codegolf.stackexchange.com/a/61221/43319) where the arguments are replicated and then used in a multiplication table: ``` ⊖∘.×⍨(/⍨⎕) ``` `⎕` Issues a prompt (`⎕:`) and evaluates any expression entered then. (For security reasons, this doesn't work on [TryAPL](http://tryapl.org/) but it does work on [NGN/APL](http://ngn.github.io/apl/web/).) `/⍨` Replicates its argument itself times (`/⍨4 3` ​⇔ `3 3 3 4 4 4 4`) `∘.×⍨` Creates a multiplication table. `⊖` Flips upside down. This happens to work on any length input (input is indented 6 spaces, output is at left margin): ``` ⊖∘.×⍨(/⍨⎕) ⎕: ⍬ ⍝ Empty list (the square of nothing) ⊖∘.×⍨(/⍨⎕) ⎕: 0 ⍝ 0​² = 0 ⊖∘.×⍨(/⍨⎕) ⎕: 0 1 ⍝ (0+1)​² = 1² 1 ⊖∘.×⍨(/⍨⎕) ⎕: 2 3 ⍝ (2+3)​² = 2² + 3² 6 6 9 9 9 6 6 9 9 9 6 6 9 9 9 4 4 6 6 6 4 4 6 6 6 ⊖∘.×⍨(/⍨⎕) ⎕: 1 2 3 ⍝ (1+2+3)​² = 1² + 2(1×2) + 2(1×3) + 2² + 2(2×3) + 3² 3 6 6 9 9 9 3 6 6 9 9 9 3 6 6 9 9 9 2 4 4 6 6 6 2 4 4 6 6 6 1 2 2 3 3 3 ⊖∘.×⍨(/⍨⎕) ⎕: ⍳4 ⍝ Integers 1 through 4 4 8 8 12 12 12 16 16 16 16 4 8 8 12 12 12 16 16 16 16 4 8 8 12 12 12 16 16 16 16 4 8 8 12 12 12 16 16 16 16 3 6 6 9 9 9 12 12 12 12 3 6 6 9 9 9 12 12 12 12 3 6 6 9 9 9 12 12 12 12 2 4 4 6 6 6 8 8 8 8 2 4 4 6 6 6 8 8 8 8 1 2 2 3 3 3 4 4 4 4 ``` --- \*Originally, I had a different solution in mind: Each rectangle is created separately by creating a multiplication table for each combination of the two arguments. Then the four squares are mended together vertically and horizontally. It looks like this: ``` ,/⍪⌿⊖∘.(,⍴×)⍨⎕ ``` `⎕` Prompt, as above. `,⍴×<` Combine (`,`) the args and use that to shape (`⍴`) a rectangle filled with their product (`×`). `∘.(`​…`)⍨` Create a table where each cell is whatever is specified in `(`​…`)` `⊖` Flip vertically. `⍪⌿` Combine cells vertically. `,/` Combine cells horizontally. [Answer] # R, 31 - 3 = 28 ``` rev(b<-rep(a<-scan(),a))%*%t(b) ``` Explanation: ``` a<-scan() # take numeric input and store as vector a b<-rep( ,a) # repeat each numeric input by itself and store as vector b rev( ) # the reverse of vector b %*% # matrix multiplication t(b) # the transposed of vector b ``` This also works for more than two numbers. For example, the output for (5,3,2) looks like this: ``` [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 10 10 10 10 10 6 6 6 4 4 [2,] 10 10 10 10 10 6 6 6 4 4 [3,] 15 15 15 15 15 9 9 9 6 6 [4,] 15 15 15 15 15 9 9 9 6 6 [5,] 15 15 15 15 15 9 9 9 6 6 [6,] 25 25 25 25 25 15 15 15 10 10 [7,] 25 25 25 25 25 15 15 15 10 10 [8,] 25 25 25 25 25 15 15 15 10 10 [9,] 25 25 25 25 25 15 15 15 10 10 [10,] 25 25 25 25 25 15 15 15 10 10 ``` [Answer] # Haskell, ~~153~~ 125 bytes - 3 = 122 ``` (#)=replicate d=length.show y%x=unlines$(>>= \n->(1+d(x*x+y*y)-d n)#' '++show n)<$>x#(y#(x*y)++x#(x*x))++y#(y#(y*y)++x#(x*y)) ``` Half of the code is for output formatting. It works for arbitrary large integers. Example output: ``` > putStrLn $ 4 % 3 12 12 12 12 9 9 9 12 12 12 12 9 9 9 12 12 12 12 9 9 9 16 16 16 16 12 12 12 16 16 16 16 12 12 12 16 16 16 16 12 12 12 16 16 16 16 12 12 12 > putStrLn $ 6 % 0 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 ``` Sometimes there's an additional whitespace between the numbers, because I'm calculating the space needed based on `x*x+y*y` instead of `max (x*x) (y*y)`, e.g. ``` > putStrLn $ 2 % 3 6 6 9 9 9 6 6 9 9 9 6 6 9 9 9 4 4 6 6 6 4 4 6 6 6 ``` But it's at most one whitespace. [Answer] # Mathematica 56-3 = 53 *Update*: I added a second method, of precisely the same code size, that uses a named function. It employs an `Array` rather than a `Table` but follows the same logic. (See below.) **Method 1** This makes a table of products, the factors of which depend on the row, column values. The pair of numbers is entered as a list of integers. Anonymous functions such as the following, are most useful if they are used only once in a program. Otherwise it makes more sense to use a named function. ``` Grid@Table[If[r>#2,#,#2]If[c>#,#2,#],{r,#+#2},{c,#+#2}]& ``` Each factor is an If-then statement: * `If[r>#2,#,#2]` means, "If the row number is greater than the second input, use the first input as the factor, otherwise use the second input. * `If[c>#,#2,#]` means, "If the column number is greater than the first input, use the second input as the factor, otherwise use the first input. --- Example 1 ``` Grid@Table[If[r>#2,#,#2]If[c>#,#2,#],{r,#+#2},{c,#+#2}]&@@{5,3} ``` [![ex1](https://i.stack.imgur.com/gArTX.png)](https://i.stack.imgur.com/gArTX.png) --- Example 2 ``` Grid@Table[If[r>#2,#,#2]If[c>#,#2,#],{r,#+#2},{c,#+#2}]&@@{0,3} ``` [![ex2](https://i.stack.imgur.com/kbmC8.png)](https://i.stack.imgur.com/kbmC8.png) --- **Method 2** (Also 56-3 = 53) This works similarly to Method 1. But it requires less code when called. And the cells are addressable, unlike cells in a table. This method is better to use if the function will be used more than once. ``` a_~f~b_:=Grid@Array[If[#>a,a,b]If[#2>a,b,a]&,{a+b,a+b}] ``` The examples from above are produced by the following: Ex 1: ``` f[4,3] ``` Ex 2: ``` f[0,3] ``` [Answer] # Octave, 34 - 3 = 31 ``` @(a)rot90(b=repelems(a,[1,2;a]))*b ``` **Examples:** ``` octave:1> f = @(a)rot90(b=repelems(a,[1,2;a]))*b; octave:2> f([4,3]) ans = 12 12 12 12 9 9 9 12 12 12 12 9 9 9 12 12 12 12 9 9 9 16 16 16 16 12 12 12 16 16 16 16 12 12 12 16 16 16 16 12 12 12 16 16 16 16 12 12 12 octave:3> f([0,3]) ans = 9 9 9 9 9 9 9 9 9 ``` [Answer] # CJam, 27 bytes - 3 = 24 ``` q:L~_]ze~_ff{*sL,2*Se[}W%N* ``` Takes input as a CJam style array. It uses a bit more spacing than necessary, but I think it's "within reason", and it's always properly right aligned. [Test it here.](http://cjam.aditsu.net/#code=q%3AL~_%5Dze~_ff%7B*sL%2C2*Se%5B%7DW%25N*&input=%5B4%203%5D) ## Explanation ``` q:L e# Read the input and store it in L. ~_ e# Evaluate the input, pushing [A B] onto the stack and duplicate it. ]z e# Wrap both in an array and transpose it to get [[A A] [B B]]. e~ e# Run-length decode, getting A copies of A and B copies of B. _ff{ e# Double map over each pair of entries in this new array... *s e# Multiply the two values. L,2* e# Push twice the length of the input string. Se[ e# Pad the result to this width with spaces (from the left). } W% e# Reverse the resulting matrix to get the correct orientation. N* e# Join the rows with linefeed characters. ``` [Answer] # C function (using glibc), 122 bytes - 3 = 119 Mostly straightforward implementation with 2 loops. I expect there are some golfing opportunities I have missed here: ``` f(n,m,x,y){for(x=0;x<n+m;x+=puts(""))for(y=0;y<n+m;y++)printf(" %*d",snprintf(0,0,"%d",n>m?n*n:m*m),(x<m?m:n)*(y<n?n:m));} ``` Inputs are passed in the first two parameters of the function, the other two are dummies. Columns are right-aligned. Note glibc `puts()` always seems to return the number of bytes written including implicit trailing newline, which is what we need here. No guarantees this will work with any other libc. In a full program: ``` f(n,m,x,y){for(x=0;x<n+m;x+=puts(""))for(y=0;y<n+m;y++)printf(" %*d",snprintf(0,0,"%d",n>m?n*n:m*m),(x<m?m:n)*(y<n?n:m));} int main (int argc, char **argv) { if (argc == 3) { f(atoi(argv[1]),atoi(argv[2])); } } ``` Compile as `gcc sqrbin.c -o sqrbin` (or `make sqrbin`). Warnings may safely be ignored. ### Example output: ``` $ ./sqrbin 4 3 12 12 12 12 9 9 9 12 12 12 12 9 9 9 12 12 12 12 9 9 9 16 16 16 16 12 12 12 16 16 16 16 12 12 12 16 16 16 16 12 12 12 16 16 16 16 12 12 12 $ ./sqrbin 4 0 16 16 16 16 16 16 16 16 16 16 16 16 16 16 16 16 $ ``` [Answer] # Ruby, (133 - 3) = 130 bytes ``` s=1 a=ARGV.map{|e|s*=(e=e.to_i);[e]*e}.flatten s=s.to_s.size a.reverse.each{|i|a.each{|j|print (i*j).to_s.rjust(s).ljust(s+3)};puts} ``` ## for 4,3 ``` 12 12 12 12 9 9 9 12 12 12 12 9 9 9 12 12 12 12 9 9 9 16 16 16 16 12 12 12 16 16 16 16 12 12 12 16 16 16 16 12 12 12 16 16 16 16 12 12 12 ``` ## for 1,3 ``` 3 9 9 9 3 9 9 9 3 9 9 9 1 3 3 3 ``` ## for 0,3 ``` 9 9 9 9 9 9 9 9 9 ``` [Answer] # Python 2, 176 bytes - 3 = 173 ``` def g(m,n): y,x,z,l,f='y','x','z','l','%'+str(len(str(max(m*m,n*n))))+'s' d={y:m*n,x:n*n,z:m*m,l:'\n'} for i in map(lambda x:d[x],(y*m+x*n+l)*n+(z*m+y*n+l)*m): print f % i, ``` This uses Python string functions to create a character grid, then replaces the characters with integers and prints formatted output. [Answer] # Matlab, 58 − 3 = 55 Using an anonymous function: ``` @(a,b)flipud(blkdiag(a^2*ones(a)-a*b,b^2*ones(b)-a*b)+a*b) ``` Example: ``` >> @(a,b)flipud(blkdiag(a^2*ones(a)-a*b,b^2*ones(b)-a*b)+a*b) ans = @(a,b)flipud(blkdiag(a^2*ones(a)-a*b,b^2*ones(b)-a*b)+a*b) >> ans(4,3) ans = 12 12 12 12 9 9 9 12 12 12 12 9 9 9 12 12 12 12 9 9 9 16 16 16 16 12 12 12 16 16 16 16 12 12 12 16 16 16 16 12 12 12 16 16 16 16 12 12 12 >> @(a,b)flipud(blkdiag(a^2*ones(a)-a*b,b^2*ones(b)-a*b)+a*b) ans = @(a,b)flipud(blkdiag(a^2*ones(a)-a*b,b^2*ones(b)-a*b)+a*b) >> ans(0,3) ans = 9 9 9 9 9 9 9 9 9 ``` ### (Old solution) 59 − 3 = 56 Using an anonymous function: ``` @(a,b)[b*a*ones(b,a) b^2*ones(b);a^2*ones(a) a*b*ones(a,b)] ``` [Answer] # C, (125 - 3) bytes ``` i,j,a;main(b,s){for(sscanf(gets(s),"%d %d",&a,&b);j<a+b;)printf(++i>a+b?i=!++j,"\n":"%*d",strlen(s)*2,(i<a?a:b)*(j<b?b:a));} ``` Input is taken as two space-separated integers on the same line. Each cell is padded with spaces to twice length of the input string. [Answer] # Pyth, 39 − 3 = 36 Pyth doesn't have built-in matrix formatting, which greatly increases the size, as one has to manually pad the output numbers. Here's what I came up with. ``` JAQL*b]jdm.[`d\ l`eS^R2Jsm*d]*bdJj+yHyG ``` [Try it online.](https://pyth.herokuapp.com/?code=JAQL*b%5Djdm.%5B%60d%5C%20l%60eS%5ER2Jsm*d%5D*bdJj%2ByHyG&input=4%2C3&debug=0) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), \$6 - 3 = 3\$ bytes ``` x`×þU$ ``` [Try it online!](https://tio.run/##y0rNyan8/78i4fD0w/tCVf4fbnfXzHrUuO/QtkPb/v@PNtFRMI7VUYg2hNIGIBoA "Jelly – Try It Online") A port of the APL and J answers. Takes input as `[a, b]` ## How it works ``` x`×þU$ - Main link. Takes a pair `[a, b]` on the left ` - Using [a, b] as both arguments: x - Repeat a a times and b b times $ - To this repeated array: U - Reverse the array ×þ - Generate a multiplication table ``` [Answer] # [Blocks](https://esolangs.org/wiki/Unnamed), ~~52~~ ~~62~~ ~~82~~ ~~87~~ 51 bytes ``` ::`+`1|U;{`*`1}|A;`+`1,0+`1={`1^2}|;0+`,`1+`={`^2}| ``` Ungolfed: ``` :: ` + `1 | Expand; {` * `1} | SetAll; ` + `1, 0 + `1 = {`1 ^ 2} | Set; 0 + `, `1 + ` = {` ^ 2} | Set ``` [Try it](http://vihanserver.tk/p/Unnamed/?code=%3F%3AF%3A%60%2B%601%7CU%3B%60%2B%601%2C0%2B%601%7C%24a%3B%24a%3D%7B%601%5E2%7D%7C%3B%24a%3D%7B%60*%601%7D%7Cn%3B0%2B%60%2C%601%2B%60%3D%7B%60%5E2%7D%7C) ]
[Question] [ When this question was posted, it was [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing)'s birthday! (source: [1](https://chat.stackexchange.com/transcript/message/58633501), [2](https://chat.stackexchange.com/transcript/message/58633511), [3](https://chat.stackexchange.com/transcript/message/58633514), [4](https://chat.stackexchange.com/transcript/message/58633516)) (It was also World Emoji Day.) As a bit of some CGCC lore, caird's name came from a [Jelly answer by Dennis](https://codegolf.stackexchange.com/questions/117949/from-programming-puzzles-to-code-golf/118068#118068) ([source](https://codegolf.meta.stackexchange.com/a/20723/68942)) - the compressed form of "Code Golf" in Jelly is `“½ċṭ6Ỵ»`, and if you insert a space (`“½ċṭ6 Ỵ»`), it becomes "caird coinheringaahing" instead, which was important for this challenge as the former is lexicographically smaller than "Programming Puzzles", but the latter is larger. Shifting the space around also gives some other resulting strings, and among them is "ChartZ Belatedly", which was caird's username during March of 2021. ## Challenge Output the string `Happy Birthday, caird coinheringaahing!` exactly. The catch: for every character in your code, there must be at least one valid position that you can move it to such that the resulting program outputs `Happy Birthday, ChartZ Belatedly!` exactly. For example, if `abcd` outputs the first string and `bcad`, `acdb`, `cabd`, and `abdc` output the second string, then this would be a valid program (`a` can be moved to the third position, `b` to the fourth, `c` to the first, and `d` to the third). (The idea for this came from [caird themself](https://chat.stackexchange.com/transcript/message/58646645), actually, so thanks to them :P) ## Rules * You may output any amount of leading or trailing whitespace, and it does not have to be consistent either between the two strings or between varying programs printing the second string. For example, printing `"Happy Birthday, ChartZ Belatedly! "` for `bcad` and `" \nHappy Birthday, ChartZ Belatedly! \t \r\n"` for `acdb` would be valid. * No input will be given (the standard rules like allowing accepting an empty/null input apply). * Your output method must be consistent though, so for example, if you print to STDOUT for the first string, you must do so for all other strings. * You must not output anything else with the chosen output method, but you can output to other methods (what I mean by this is if you output to STDOUT, you can flood STDERR with random garbage, and if your submission is a function that produces the result, you can output freely to STDOUT, etc.) ## Scoring This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge still, so the shortest answer in bytes wins among submissions in its language. [Answer] # [Zsh](https://www.zsh.org) `-y`, ~~145~~ ~~148~~ ~~144~~ ~~142~~ ~~131~~ 130 bytes ``` 1="echo Happy Birthday, ";$1caird coinheringaahing!>x "\";$1ChartZ Belatedly!>x #" "\";echo Happy Birthday, ChartZ Belatedly!>x #" ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwTogoaBbaWOjnqxup2a0tLQkTdfiZpOhrVJqcka-gkdiQUGlglNmUUlGSmKljoKStYphcmJmUYpCcn5mXkZqUWZeemJiBpBUtKvgUooByTtnJBaVRCk4peYklqSm5FQCZRSUlcCSWM3Erh7ikiXJXDYVEOaCBRAaAA) Outputs to a file called `x`, which allows us to save bytes exiting because we can overwrite the file to change the output instead of needing to exit the program. * Any character on the first line, including its trailing newline, should go between the `\` and `"` on the third line * The final `"` on the second line should go at the end of the third, and vice versa * Any other character on the second line, including its trailing newline, should go between the `\` and `"` on the third line, and vice versa --- Some of the modified programs are highly cursed. For instance, moving the `x` on the first line: ``` 1="echo Happy Birthday, ";$1caird coinheringaahing!> "\";$1ChartZ Belatedly!>x #" "\x";echo Happy Birthday, ChartZ Belatedly!>x #" ``` This produces a "parse error" because of the trailing `>`, but zsh ...just continues executing the program?? [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~88~~ 69 bytes ``` FLe33,39ḷ¶““ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» ``` [Try it online!](https://tio.run/##y0rNyan8/9/NJ9XYWMfY8uGO7Ye2PWqYA0QPdzY93LHk0P5Dyx817ny4c9WhbcYPd3Ud3nhyz8OdzQ93NhybcWj3oZ1AhYfWPdzVoX5o28Ndk06sqwJqU87yTvc7tPtwu/3h9hPLVcAE0OAT6yEG41L//z8A "Jelly – Try It Online") A niladic link that prints "Happy Birthday, caird coinheringaahing!" Thanks to @JonathanAllan for pointing out I could save 19 bytes by changing the last string to a compressed one. Explanation of base script: ## Helper link ``` F | Flatten L | Length e33,39 | Is one of 33 or 39 ḷ | Left (effectively a no-op here) ``` ## Main link ``` ““ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ» | ["", "Happy Birthday, caird coinheringaahing!"] Ç? | If helper link returns truthy: ¹ | - Identity function “®Ẉ'¶ẒȮzṂ#jKgN» | Else: ["", "Happy Birthday, ChartZ Belatedly!"] Çȧ$ | helper(x) logical and x Çȧ$ | helper(x) logical and x ḷ | Left (effectively a no-op here) ȯ““®Ẉ'¶ẒȮzṂ#jKgN» | logical or ["", "Happy Birthday, ChartZ Belatedly!"] ``` Here are the variants ([produced by this script](https://tio.run/##fVVNb9RGGL77VwxOJXsa4wQ2RGWFaQUSKioqh3Kqa1ne9ezuLP7SzBjWnGipBOLYUw89torUA1UvKZtUQnKkKv0Z5o@k7zv@2BCgltf2PPPM@z7vx8wWlVrk2ejsjKdFLhSRlXTIkiVJ5RCeO2QSSba/55AnCZ8YxjSJpCS3o0KVgmdzO@FS0bFB4IrZjIQhyxQTYWhLlsy6Cbxw6IZSxXmpiIdO3HawYQwQznd09MFzAHjufqNHd@/bdFgjGMjINPu8hBVXnQKHfBqJubwohK0Uy2L7XS/unKlHUVIym7qySLhKeMakTTfuYpZcVAbXFpkJxkhZEJmnjKQszUX1/2HpwI1pnhaRhpVw0@ghUyLKpG19lzXHvzXrN5ZDrPqwPjj50aIGVMQz79xjo5Ezut68/qs@fPv0F7ib9Q/N61/rN/XB2@/Xzfr3@nDUHL08@fPfv5v1s2b99J@f6@N6DcT6VXP0Auw1Rz@dvnoCy7aWX82/ro9Pnn9@8vz04BP9AMOnf7SGP8Y3DQPTnOaPWDhdRMJWkE2HSDF1SNw2wxRiQtQHMDD0Z4/sjhEj28P89pXxexQwg5RpT4MxkrpqI9RqUEyqcJrHzMYHelaiwlI/5mpxrkkpiSSBlBel0o2guxsyzjPbstxlDm@MhMxyQfQHzwhadHVBkkihA6wVJXw2MForyAuLaM6o4weOZWG3dEKhkJ311jdMsdWUFVpExzG7dM54FodFLu0V7DqMRKpIKO/KroEuueddH/dQj@zv9hCQUPoSVYHiObM17pCEZfaK6u7n59O18pcBJZ5HrC@joqjILS7UIo5gx9@G4NS35BbDqOOkumTpjHVql13toVfDNM4fZyHskYdD9nEAVTQXShVyvLOjYFOJMtvZ2jKhlO1B4k7291imVeCJ4mJiBZPSnlSgzzZ1Vk3HLNXs8mcm3W5h/@q1aw78gh5AAx8nUf/q@PJe4EzML0KTujHT/nr6ILStIGzl1EbEIb7pmYFDBJ8vsB0fiJLRoe/QBoRhkRsRWQg280wLhtoUoObNB6IidxW5n@G5cenGTnTTMgwjShKsqwRzvr/ZNOAaCg0HLb1YOqwZzFIa6Bn@oRlttT1S/Hc7R6@xwfCK4kKWlSkT2MC9DlhcwKZQ2lL32b83DdKz/d0Abroh@u0H138RPodkLZ33@mFYzQNstEHU8gOaIAoanJ39Bw)) that print "Happy Birthday, ChartZ Belatedly!": ``` 0 F 10 Le33,39ḷ¶“F“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_98n1dhYx9jy4Y7th7Y9apjjBsQPdzY93LHk0P5Dyx817ny4c9WhbcYPd3Ud3nhyz8OdzQ93NhybcWj3oZ1AhYfWPdzVoX5o28Ndk06sqwJqU87yTvc7tPtwu_3h9hPLVcAE0OQT64GK8aj__x8A) 1 L 10 Fe33,39ḷ¶“L“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_98t1dhYx9jy4Y7th7Y9apjjA8QPdzY93LHk0P5Dyx817ny4c9WhbcYPd3Ud3nhyz8OdzQ93NhybcWj3oZ1AhYfWPdzVoX5o28Ndk06sqwJqU87yTvc7tPtwu_3h9hPLVcAE0OQT64GK8aj__x8A) 2 e 26 FL33,39ḷ¶““ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»e¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_Nx9hYx9jy4Y7th7Y9apgDRA93Nj3cseTQ_kPLHzXufLhz1aFtxg93dR3eeHLPw53ND3c2HJtxaHfqoZ1AlYfWPdzVoX5o28Ndk06sqwLqU87yTvc7tPtwu_3h9hPLVcAE0OQT6yEm41L__z8A) 3 3 10 FLe3,39ḷ¶“3“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9VYx9jy4Y7th7Y9aphjDMQPdzY93LHk0P5Dyx817ny4c9WhbcYPd3Ud3nhyz8OdzQ93NhybcWj3oZ1AhYfWPdzVoX5o28Ndk06sqwJqU87yTvc7tPtwu_3h9hPLVcAE0OQT64GK8aj__x8A) 4 3 10 FLe3,39ḷ¶“3“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9VYx9jy4Y7th7Y9aphjDMQPdzY93LHk0P5Dyx817ny4c9WhbcYPd3Ud3nhyz8OdzQ93NhybcWj3oZ1AhYfWPdzVoX5o28Ndk06sqwJqU87yTvc7tPtwu_3h9hPLVcAE0OQT64GK8aj__x8A) 5 , 10 FLe3339ḷ¶“,“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XY2Njy4Y7th7Y9apijA8QPdzY93LHk0P5Dyx817ny4c9WhbcYPd3Ud3nhyz8OdzQ93NhybcWj3oZ1AhYfWPdzVoX5o28Ndk06sqwJqU87yTvc7tPtwu_3h9hPLVcAE0OQT64GK8aj__x8A) 6 3 10 FLe33,9ḷ¶“3“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfy4Y7th7Y9aphjDMQPdzY93LHk0P5Dyx817ny4c9WhbcYPd3Ud3nhyz8OdzQ93NhybcWj3oZ1AhYfWPdzVoX5o28Ndk06sqwJqU87yTvc7tPtwu_3h9hPLVcAE0OQT64GK8aj__x8A) 7 9 10 FLe33,3ḷ¶“9“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMf44Y7th7Y9aphjCcQPdzY93LHk0P5Dyx817ny4c9WhbcYPd3Ud3nhyz8OdzQ93NhybcWj3oZ1AhYfWPdzVoX5o28Ndk06sqwJqU87yTvc7tPtwu_3h9hPLVcAE0OQT64GK8aj__x8A) 8 ḷ 10 FLe33,39¶“ḷ“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8tC2Rw1zHu7YDiJ3Nj3cseTQ_kPLHzXufLhz1aFtxg93dR3eeHLPw53ND3c2HJtxaPehnUCFh9Y93NWhfmjbw12TTqyrAmpTzvJO9zu0@3C7_eH2E8tVwATQzBPrgYrxqP__HwA) 9 ¶ 1 F¶Le33,39ḷ““ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_t0DafVGNjHWPLhzu2P2qYA0QPdzY93LHk0P5Dyx817ny4c9WhbcYPd3Ud3nhyz8OdzQ93NhybcWj3oZ1AhYfWPdzVoX5o28Ndk06sqwJqU87yTvc7tPtwu_3h9hPLVcAE0NgT6yEG41L__z8A) 10 “ 13 FLe33,39ḷ¶“ṂḤ“¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqY83Bn08MdS4CMQ_sPLX_UuPPhzlWHthk_3NV1eOPJPQ93Nj_c2XBsxqHdh3aClKx7uKtD_dC2h7smnVhXBdSpnOWd7ndo9@F2@8PtJ5argAmgwSfWAxXjUf__PwA) 11 “ 13 FLe33,39ḷ¶“ṂḤ“¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqY83Bn08MdS4CMQ_sPLX_UuPPhzlWHthk_3NV1eOPJPQ93Nj_c2XBsxqHdh3aClKx7uKtD_dC2h7smnVhXBdSpnOWd7ndo9@F2@8PtJ5argAmgwSfWAxXjUf__PwA) 12 Ṃ 13 FLe33,39ḷ¶““ḤṂ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYA0QPdyx5uLPp0P5Dyx817ny4c9WhbcYPd3Ud3nhyz8OdzQ93NhybcWj3oZ1AhYfWPdzVoX5o28Ndk06sqwLqUc7yTvc7tPtwu_3h9hPLVcAE0OAT6yEG41L__z8A) 13 Ḥ 11 FLe33,39ḷ¶“Ḥ“Ṃ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqY83DHEhC5s@nQ_kPLHzXufLhz1aFtxg93dR3eeHLPw53ND3c2HJtxaPehnUBVh9Y93NWhfmjbw12TTqyrAupRzvJO9zu0@3C7_eH2E8tVwATQ4BPrgYrxqP__HwA) 14 ¿ 11 FLe33,39ḷ¶“¿“ṂḤ§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYc2g_kHi4s@nhjiWHlj9q3Plw56pD24wf7uo6vPHknoc7mx_ubDg249DuQztBatc93NWhfmjbw12TTqyrAmpSzvJO9zu0@3C7_eH2E8tVwATQ4BPrgYrxqP__HwA) 15 § 11 FLe33,39ḷ¶“§“ṂḤ¿⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYc2g5kHi4s@nhjiWH9j9q3Plw56pD24wf7uo6vPHknoc7mx_ubDg249DuQztBatc93NWhfmjbw12TTqyrAmpSzvJO9zu0@3C7_eH2E8tVwATQ4BPrgYrxqP__HwA) 16 ⁹ 10 FLe33,39ḷ¶⁹““ṂḤ¿§Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWrc@ahhDhA93Nn0cMeSQ_sPLX@4c9WhbcYPd3Ud3nhyz8OdzQ93NhybcWj3IZDCQ@se7upQP7Tt4a5JJ9ZVAfUoZ3mn@x3afbjd_nD7ieUqYAJo8In1EFNxqf__HwA) 17 Ṫ 11 FLe33,39ḷ¶“Ṫ“ṂḤ¿§⁹¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqY83DnKjDZ9HDHkkP7Dy1_1Ljz0Dbjh7u6Dm88uefhzuaHOxuOzTi0@9BOoKpD6x7u6lA_tO3hrkkn1lUB9Shneaf7Hdp9uN3@cPuJ5SpgAmjwifVAxXjU__8PAA) 18 ¶ 11 FLe33,39ḷ¶“¶“ṂḤ¿§⁹Ṫ3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYAyYe7mx6uGPJof2Hlj9q3Plw5yrjh7u6Dm88uefhzuaHOxuOzTi0@9BOkNp1D3d1qB_a9nDXpBPrqoCalLO80_0O7T7cbn@4_cRyFTABNPjEeqBiPOr__wcA) 19 3 10 FLe33,39ḷ¶3““ṂḤ¿§⁹Ṫ¶ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2GT9qmANED3c2Pdyx5ND@Q8sfNe58uHPVoW0Pd3Ud3nhyz8OdzQ93NhybcWj3oZ1AdYfWPdzVoQ6SnXRiXRVQl3KWd7rfod2H2@0Pt59YrgImgAafWA8xF5f6__8B) 20 Ẋ 11 FLe33,39ḷ¶“Ẋ“ṂḤ¿§⁹Ṫ¶3ñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqY83BXF4jc2fRwx5JD@w8tf9S48@HOVYe2GR_eeHLPw53ND3c2HJtxaPehnUBVh9Y93NWhfmjbw12TTqyrAupRzvJO9zu0@3C7_eH2E8tVwATQ4BPrgYrxqP__HwA) 21 ñ 10 FLe33,39ḷ¶ñ““ṂḤ¿§⁹Ṫ¶3ẊɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2Hd74qGEOED3c2fRwx5JD@w8tf9S48@HOVYe2GT_c1XVyz8OdzQ93NhybcWj3oZ1AZYfWPdzVoX5o28Ndk06sqwJqUs7yTvc7tPtwu_3h9hPLVcAE0OAT6yHG4lL__z8A) 22 ɼ 11 FLe33,39ḷ¶“ɼ“ṂḤ¿§⁹Ṫ¶3ẊñṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYc3IPkHi4s@nhjiWH9h9a_qhx58Odqw5tM364q@vwxoc7mx_ubDg249DuQzuByg6te7irQ_3Qtoe7Jp1YVwXUpJzlne53aPfhdvvD7SeWq4AJoMEn1gMV41H__z8A) 23 ṃ 10 FLe33,39ḷ¶ṃ““ṂḤ¿§⁹Ṫ¶3ẊñɼṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PdzZ_KhhDhA93Nn0cMeSQ_sPLX_UuPPhzlWHthk_3NV1eOPJPQ93NhybcWj3oZ1AVYfWPdzVoQ7UtmvSiXVVQD3KWd7pfod2H263P9x@YrkKmAAafGI9xFRc6v__BwA) 24 Ṁ 11 FLe33,39ḷ¶“Ṁ“ṂḤ¿§⁹Ṫ¶3ẊñɼṃƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqY83BnA5hserhjyaH9h5Y_atz5cOeqQ9uMH@7qOrzx5J6HO5uPzTi0@9BOoKpD6x7u6lA_tO3hrkkn1lUB9Shneaf7Hdp9uN3@cPuJ5SpgAmjwifVAxXjU__8PAA) 25 Ƙ 11 FLe33,39ḷ¶“Ƙ“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYc2wGkHi4s@nhjiWH9h9a_qhx58Odqw5tM364q@vwxpN7Hu5sfriz4dDuQzuByg6te7irQ_3Qtoe7Jp1YVwXUpJzlne53aPfhdvvD7SeWq4AJoMEn1gMV41H__z8A) 26 » 10 FLe33,39ḷ¶»““ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2Hdr9qGEOED3c2fRwx5JD@w8tf9S48@HOVYe2GT_c1XV448k9D3c2P9zZcGzGoZ1AZYfWPdzVoX5o28Ndk06sqwJqUs7yTvc7tPtwu_3h9hPLVcAE0OAT6yHG4lL__z8A) 27 ¹ 10 FLe33,39ḷ¶¹““ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2Hdr5qGEOED3c2fRwx5JD@w8tf9S48@HOVYe2GT_c1XV448k9D3c2P9zZcGzGod1AZYfWPdzVoX5o28Ndk06sqwJqUs7yTvc7tPtwu_3h9hPLVcAE0OAT6yHG4lL__z8A) 28 “ 27 FLe33,39ḷ¶““ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»“¹®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYA0QPdzY93LHk0P5Dyx817ny4c9WhbcYPd3Ud3nhyz8OdzQ93NhybcWg3UNmhnYfWPdzVoX5o28Ndk06sqwJqU87yTvc7tPtwu_3h9hPLVcAE0OAT6yEG41L__z8A) 29 ® 11 FLe33,39ḷ¶“®“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYc2gdkHi4s@nhjiWH9h9a_qhx58Odqw5tM364q@vwxpN7Hu5sfriz4diMQ7sP7QQp3NWhfmjbw12TTqyrAmpSzvJO9zu0@3C7_eH2E8tVwATQ4BPrgUrBZmNX__8_AA) 30 Ẉ 11 FLe33,39ḷ¶“Ẉ“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqY83BXB4jc2fRwx5JD@w8tf9S48@HOVYe2GT_c1XV448k9D3c2P9zZcGzGod2HdgIVHlqnfmjbw12TTqyrAupRzvJO9zu0@3C7_eH2E8tVwATQ4BPrgSrBioGmY1H__z8A) 31 ' 11 FLe33,39ḷ¶“'“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYow7ED3c2Pdyx5ND@Q8sfNe58uHPVoW3GD3d1Hd54cs_Dnc0PdzYcm3Fo96GdQIWH1j3c1XFo28Ndk06sqwLqUs7yTvc7tPtwu_3h9hPLVcAE0OAT64FqYcrVMdX__w8A) 32 ¶ 11 FLe33,39ḷ¶“¶“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYAyYe7mx6uGPJof2Hlj9q3Plw56pD24wf7uo6vPHknoc7mx_ubDg249DuQztBqtc93NWh_nDXpBPrqoCalLO80_0O7T7cbn@4_cRyFTABNPjEeqBSuOpD29DV__8PAA) 33 Ẓ 11 FLe33,39ḷ¶“Ẓ“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqY83DXJBC5s@nhjiWH9h9a_qhx58Odqw5tM364q@vwxpN7Hu5sfriz4diMQ7sP7QQqPLTu4a4O9UPbTqyrAupRzvJO9zu0@3C7_eH2E8tVwATQ4BPrgSqRFAPtQFH__z8A) 34 Ȯ 11 FLe33,39ḷ¶“Ȯ“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYc2IdkHi4s@nhjiWH9h9a_qhx58Odqw5tM364q@vwxpN7Hu5sfriz4diMQ7sP7QQqPLTu4a4O9UPbHu6aVAXUpJzlne53aPfhdvvD7SeWq4AJoMEn1gOVoqo@sQ5J_f__AA) 35 z 11 FLe33,39ḷ¶“z“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYUwXED3c2Pdyx5ND@Q8sfNe58uHPVoW3GD3d1Hd54cs_Dnc0PdzYcm3Fo96GdQIWH1j3c1aF@aNvDXZNOrAPqUs7yTvc7tPtwu_3h9hPLVcAE0OAT64Fq0ZVXIdT__w8A) 36 Ṃ 11 FLe33,39ḷ¶“Ṃ“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮz#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqY83BnE4R8uGPJof2Hlj9q3Plw56pD24wf7uo6vPHknoc7mx_ubDg249DuQzuBCg@te7irQ_3Qtoe7Jp1YV6Wc5Z3ud2j34Xb7w@0nlquACaDBJ9YDVWIoBtoBVf__PwA) 37 # 11 FLe33,39ḷ¶“#“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂjKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYowzED3c2Pdyx5ND@Q8sfNe58uHPVoW3GD3d1Hd54cs_Dnc0PdzYcm3Fo96GdQIWH1j3c1aF@aNvDXZNOrKsCasvyTvc7tPtwu_3h9hPLVcAE0OAT64FqsSlXhqj__x8A) 38 j 10 FLe33,39ḷ¶j““ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#KgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2ZT1qmANED3c2Pdyx5ND@Q8sfNe58uHPVoW3GD3d1Hd54cs_Dnc0PdzYcm3Fo96GdQIWH1j3c1aF@aNvDXZNOrKsCalP2Tvc7tPtwu_3h9hPLVcAE0OAT6yHmYirPAqv__x8A) 39 K 11 FLe33,39ḷ¶“K“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqY4w3ED3c2Pdyx5ND@Q8sfNe58uHPVoW3GD3d1Hd54cs_Dnc0PdzYcm3Fo96GdQIWH1j3c1aF@aNvDXZNOrKsCalPOSvc7tPtwu_3h9hPLVcAE0OAT64FqsSv3Bqn__x8A) 40 g 11 FLe33,39ḷ¶“g“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYkw7ED3c2Pdyx5ND@Q8sfNe58uHPVoW3GD3d1Hd54cs_Dnc0PdzYcm3Fo96GdQIWH1j3c1aF@aNvDXZNOrKsCalPO8vY7tPtwu_3h9hPLVcAE0OAT64FqcShPB6r__x8A) 41 N 11 FLe33,39ḷ¶“N“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKg»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqY4wfED3c2Pdyx5ND@Q8sfNe58uHPVoW3GD3d1Hd54cs_Dnc0PdzYcm3Fo96GdQIWH1j3c1aF@aNvDXZNOrKsCalPO8k4_tPtwu_3h9hPLVcAE0OAT64FqcSn3O7T7_38A) 42 » 41 FLe33,39ḷ¶““ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKg»NÇ?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYA0QPdzY93LHk0P5Dyx817ny4c9WhbcYPd3Ud3nhyz8OdzQ93NhybcWj3oZ1AhYfWPdzVoX5o28Ndk06sqwJqU87yTj@02@9wu_3h9hPLVcAE0OAT6yEGY1Xvd2j3__8A) 43 Ç 11 FLe33,39ḷ¶“Ç“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYc7gdSDzc2fRwx5JD@w8tf9S48@HOVYe2GT_c1XV448k9D3c2P9zZcGzGod2HdgIVHlr3cFeH@qFtD3dNOrGuCqhNOcs73e_QbvvD7SeWq4AJoMEn1gOV4lH9_z8A) 44 ? 43 FLe33,39ḷ¶““ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»?ÇÇȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYA0QPdzY93LHk0P5Dyx817ny4c9WhbcYPd3Ud3nhyz8OdzQ93NhybcWj3oZ1AhYfWPdzVoX5o28Ndk06sqwJqU87yTvc7tNv@cPvh9hPLVcAE0OAT6yEG41L__z8A) 45 Ç 11 FLe33,39ḷ¶“Ç“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?ȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYc7gdSDzc2fRwx5JD@w8tf9S48@HOVYe2GT_c1XV448k9D3c2P9zZcGzGod2HdgIVHlr3cFeH@qFtD3dNOrGuCqhNOcs73e_Q7sPt9ieWqxxuBxJAg0@sByrFo_r_fwA) 46 ȧ 10 FLe33,39ḷ¶ȧ““ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Ç$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2nVj@qGEOED3c2fRwx5JD@w8tf9S48@HOVYe2GT_c1XV448k9D3c2P9zZcGzGod2HdgIVHlr3cFeH@qFtD3dNOrGuCqhNOcs73e_Q7sPt9ofbVQ63n1iuAjT4xHqIsbhU__8PAA) 47 $ 11 FLe33,39ḷ¶“$“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?ÇȧÇȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYowLED3c2Pdyx5ND@Q8sfNe58uHPVoW3GD3d1Hd54cs_Dnc0PdzYcm3Fo96GdQIWH1j3c1aF@aNvDXZNOrKsCalPO8k73O7T7cLv94fYTy0FYBWjwifVAtXiU__8PAA) 48 Ç 11 FLe33,39ḷ¶“Ç“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$ȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYc7gdSDzc2fRwx5JD@w8tf9S48@HOVYe2GT_c1XV448k9D3c2P9zZcGzGod2HdgIVHlr3cFeH@qFtD3dNOrGuCqhNOcs73e_Q7sPt9ofbTyxXASKgwSfWA5XiUf3_PwA) 49 ȧ 43 FLe33,39ḷ¶““ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»ȧÇ?Çȧ$Ç$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYA0QPdzY93LHk0P5Dyx817ny4c9WhbcYPd3Ud3nhyz8OdzQ93NhybcWj3oZ1AhYfWPdzVoX5o28Ndk06sqwJqU87yTvc7tPvE8sPt9ofbTyxXOdyuAjT4xHqIwbjU__8PAA) 50 $ 27 FLe33,39ḷ¶““ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»$¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧḷȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYA0QPdzY93LHk0P5Dyx817ny4c9WhbcYPd3Ud3nhyz8OdzQ93NhybcWi3yqGdQJWH1j3c1aF@aNvDXZNOrKsC6lPO8k73O7T7cLv94fYTy1VABNDgE@shBuNS_v8_AA) 51 ḷ 10 FLe33,39ḷ¶ḷ““ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ȯ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2AYlHDXOA6OHOpoc7lhzaf2j5o8adD3euOrTN@OGursMbT@55uLP54c6GYzMO7T60E6jw0LqHuzrUgTp3TTqxrgqoTTnLO93v0O7D7faH208sVwETJ9ZDTMWl@P9_AA) 52 ȯ 11 FLe33,39ḷ¶“ȯ“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷ““®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYc2I9kHi4s@nhjiWH9h9a_qhx58Odqw5tM364q@vwxpN7Hu5sfriz4diMQ7sP7QQqPLTu4a4O9UPbHu6adGJdFVCbcpZ3ut@h3Yfb7Q@3n1iuAiaARgOV4lH9_z8A) 53 “ 14 FLe33,39ḷ¶““ṂḤ“¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ“®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYA0QPdzY93LEEyDi0_9DyR407H@5cdWib8cNdXYc3ntzzcGfzw50Nx2Yc2n1oJ0jJuoe7OtQPbXu4a9KJdVVAncpZ3ul@h3Yfbrc_3H5iuQqYAJp9Yj0exf__AwA) 54 “ 14 FLe33,39ḷ¶““ṂḤ“¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ“®Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYA0QPdzY93LEEyDi0_9DyR407H@5cdWib8cNdXYc3ntzzcGfzw50Nx2Yc2n1oJ0jJuoe7OtQPbXu4a9KJdVVAncpZ3ul@h3Yfbrc_3H5iuQqYAJp9Yj0exf__AwA) 55 ® 11 FLe33,39ḷ¶“®“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““Ẉ'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYc2gdkHi4s@nhjiWH9h9a_qhx58Odqw5tM364q@vwxpN7Hu5sfriz4diMQ7sP7QSrfrirQ_3Qtoe7Jp1YVwXUppzlne53aPfhdvvD7SeWq4AJoNEn1gMVgwzGqvr_fwA) 56 Ẉ 11 FLe33,39ḷ¶“Ẉ“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®'¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqY83BXB4jc2fRwx5JD@w8tf9S48@HOVYe2GT_c1XV448k9D3c2P9zZcGzGod2HdgIVHloH1KB@aNvDXZNOrKsCalPO8k73O7T7cLv94fYTy1XABNDsE@uBisHqsSj@_x8A) 57 ' 11 FLe33,39ḷ¶“'“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ¶ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYow7ED3c2Pdyx5ND@Q8sfNe58uHPVoW3GD3d1Hd54cs_Dnc0PdzYcm3Fo96GdQIWH1j3c1aF@aNvDXZNOrKsCalPO8k73O7T7cLv94fYTy1XABNDkE@uBimHqMZX__w8A) 58 ¶ 11 FLe33,39ḷ¶“¶“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'ẒȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYAyYe7mx6uGPJof2Hlj9q3Plw56pD24wf7uo6vPHknoc7mx_ubDg249DuQztBqtc93NWhfmjbw12TTqyrAmpTzvJO9zu0@3C7_eH2E8tVwATQ6BPrgYrh6tFV__8PAA) 59 Ẓ 11 FLe33,39ḷ¶“Ẓ“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ȮzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqY83DXJBC5s@nhjiWH9h9a_qhx58Odqw5tM364q@vwxpN7Hu5sfriz4diMQ7sP7QQqPLTu4a4O9UPbgNpOrKsCalPO8k73O7T7cLv94fYTy1XABNDsE@uBipHUoyj@_x8A) 60 Ȯ 11 FLe33,39ḷ¶“Ȯ“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒzṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYc2IdkHi4s@nhjiWH9h9a_qhx58Odqw5tM364q@vwxpN7Hu5sfriz4diMQ7sP7QQqPLTu4a4O9UPbHu6adGJdFVCbcpZ3ut@h3Yfb7Q@3n1iuAiaARp9YD1SMqh5J9f__AA) 61 z 11 FLe33,39ḷ¶“z“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮṂ#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYUwXED3c2Pdyx5ND@Q8sfNe58uHPVoW3GD3d1Hd54cs_Dnc0PdzYcm3Fo96GdQIWH1j3c1aF@aNvDXZNOrKsCalPO8k73O7T7cLv94fYTy1XABNDkE@uBitHVI5T__w8A) 62 Ṃ 11 FLe33,39ḷ¶“Ṃ“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮz#jKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqY83BnE4R8uGPJof2Hlj9q3Plw56pD24wf7uo6vPHknoc7mx_ubDg249DuQzuBCg@te7irQ_3Qtoe7Jp1YVwXUppzlne53aPfhdvvD7SeWq4AJoNkn1gMVY6iHKv7_HwA) 63 # 11 FLe33,39ḷ¶“#“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂjKgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYowzED3c2Pdyx5ND@Q8sfNe58uHPVoW3GD3d1Hd54cs_Dnc0PdzYcm3Fo96GdQIWH1j3c1aF@aNvDXZNOrKsCalPO8k73O7T7cLv94fYTy1XABNDkE@uBirGphyj__x8A) 64 j 10 FLe33,39ḷ¶j““ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#KgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2ZT1qmANED3c2Pdyx5ND@Q8sfNe58uHPVoW3GD3d1Hd54cs_Dnc0PdzYcm3Fo96GdQIWH1j3c1aF@aNvDXZNOrKsCalPO8k73O7T7cLv94fYTy1XABNDkE@shBmOqByv__x8A) 65 K 11 FLe33,39ḷ¶“K“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jgN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqY4w3ED3c2Pdyx5ND@Q8sfNe58uHPVoW3GD3d1Hd54cs_Dnc0PdzYcm3Fo96GdQIWH1j3c1aF@aNvDXZNOrKsCalPO8k73O7T7cLv94fYTy1XABNDkE@uBirGrByn__x8A) 66 g 11 FLe33,39ḷ¶“g“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKN» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYkw7ED3c2Pdyx5ND@Q8sfNe58uHPVoW3GD3d1Hd54cs_Dnc0PdzYcm3Fo96GdQIWH1j3c1aF@aNvDXZNOrKsCalPO8k73O7T7cLv94fYTy1XABNDkE@uBinGoByr__x8A) 67 N 11 FLe33,39ḷ¶“N“ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKg» [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqY4wfED3c2Pdyx5ND@Q8sfNe58uHPVoW3GD3d1Hd54cs_Dnc0PdzYcm3Fo96GdQIWH1j3c1aF@aNvDXZNOrKsCalPO8k73O7T7cLv94fYTy1XABNDkE@uBinGpP7T7_38A) 68 » 42 FLe33,39ḷ¶““ṂḤ¿§⁹Ṫ¶3ẊñɼṃṀƘ»¹“®Ẉ'¶ẒȮzṂ#jKgN»»Ç?Çȧ$Çȧ$ḷȯ““®Ẉ'¶ẒȮzṂ#jKgN [Try It Online!](https://tio.run/##y0rNyan8_9_NJ9XYWMfY8uGO7Ye2PWqYA0QPdzY93LHk0P5Dyx817ny4c9WhbcYPd3Ud3nhyz8OdzQ93NhybcWj3oZ1AhYfWPdzVoX5o28Ndk06sqwJqU87yTvcDSu4@3G5_uP3EchUwATT6xHqI0dh1_P8PAA) ``` [Answer] # C, 148 bytes ``` /**/main(){printf("Happy Birthday, %s!",'\0'?"ChartZ Belatedly":"caird coinheringaahing");}///*/b;main(){puts("Happy Birthday, ChartZ Belatedly!");} ``` * Any character within the first `main` definition is moved to separate the first `*/`, so the comment does not end there; it ends at the second `*/`, and the second `main` definition applies. * Any of the first four characters `/**/`, except the first, is moved to make it `/*/*`, with the same effect. * The first character, `/`, is moved one step right, making the program begin `*/*/`. This leaves `*` outside the comment, which combines with the later `b;` (a declaration of an implicit-`int` global variable) to form `* b;` (which declares `b` as a pointer to `int`). * Any other character (starting from `///*/`) is moved into `'\0'`, after the first `'`, to make it a multicharacter constant with a nonzero value, changing the string selected by the `? :`; the last part originally beginning with three slashes ensures that it remains a line comment after any character is taken out from it. [Answer] # [Klein](https://github.com/Wheatwizard/Klein) 000, ~~[133](https://codegolf.stackexchange.com/revisions/231565/2)~~, ~~[120](https://codegolf.stackexchange.com/revisions/231565/3)~~, ~~[119](https://codegolf.stackexchange.com/revisions/231565/4)~~, 111 bytes ``` .\"Happy Birthday, "\"ChartZ Belatedly!"@ >."Happy Birthday, ChartZ Belatedly!"@ "oinheringaahing!"@.>"caird c" ``` [Try it online!](https://tio.run/##bcqxDYAgEEDR3inwaiVMQBQbZzA2FyBykSAhNEx/0mvzi593R0@JWZ6wY85NGCo1OGyTgBO2gKUewviI1bvYRlgGLT/yj8FDKfhC6UIMvf1JDRapOGGBmZVSPK8v "Klein – Try It Online") The idea of this follows the classic klein [source-layout](/questions/tagged/source-layout "show questions tagged 'source-layout'")/[radiation-hardening](/questions/tagged/radiation-hardening "show questions tagged 'radiation-hardening'") approach. We have 3 programs and we use the alignment to select which one we run. All of our swaps move one character to a different line breaking the alignment and putting it into a different program. ## The breakdown If the character is one of the first two then we swap them ``` \."Happy Birthday, "\"ChartZ Belatedly!"@ >."Happy Birthday, ChartZ Belatedly!"@ "oinheringaahing!"@.>"caird c" ``` Anything else on the first line we can put at the begining of the second line. ``` .\"Happy Birhday, "\"ChartZ Belatedly!"@ t>."Happy Birthday, ChartZ Belatedly!"@ "oinheringaahing!"@.>"caird c" ``` For the first two characters of the second line we can swap them too. ``` .\"Happy Birthday, "\"ChartZ Belatedly!"@ .>"Happy Birthday, ChartZ Belatedly!"@ "oinheringaahing!"@.>"caird c" ``` For the rest of the line we can insert it before the `.` in the third line ``` .\"Happy Birthday, "\"ChartZ Belatedly!"@ >."Happy Birhday, ChartZ Belatedly!"@ "oinheringaahing!"@t.>"caird c" ``` Any character on the third line can be inserted at the front of the second line. ``` .\"Happy Birthday, "\"ChartZ Belatedly!"@ a>."Happy Birthday, ChartZ Belatedly!"@ "oinheringahing!"@.>"caird c" ``` Finally we can do the newlines as follows: ``` .\"Happy Birthday, "\"ChartZ Belatedly!" @>."Happy Birthday, ChartZ Belatedly!"@ "oinheringaahing!"@.>"caird c" ``` ``` .\"Happy Birthday, "\"ChartZ Belatedly!"@ >."Happy Birthday, ChartZ Belatedly!"@"oinheringaahing!"@.>"caird c " ``` [Answer] # [Python 3](https://docs.python.org/3/), 130 bytes ``` '''''';print("Happy Birthday,",""and"ChartZ Belatedly!"or"caird coinheringaahing!")#''';print('Happy Birthday, ChartZ Belatedly!') ``` [Try it online!](https://tio.run/##ZcwxCoAwDIXhq8Q4VKGbo5sunsEt2GIK0paQpaevxUXQN/zb@3JRTnGq1Tybs4SoA26Uc4EliLKjYtEiUnS4MonusPiL1LurdJgEDwri4Eghsm/vk4hbOxz7FzQfEH6SGWu9AQ "Python 3 – Try It Online") ## Alternate programs * Byte 1 to 6: The `'` is moved behind the first `;`, therefore characters 1 to 87 are a string and are disregarded. Characters 89+ are executed. ``` ''''';'print("Happy Birthday,",""and"ChartZ Belatedly!"or"caird coinheringaahing!")#''';print('Happy Birthday, ChartZ Belatedly!') ``` * Byte 7 to 84: The byte is moved behind the fifth byte. As none of these characters is a `'`, this also creates a string from character 1 to character 87, with the same effects as above. ``` '''''"';print(Happy Birthday,",""and"ChartZ Belatedly!"or"caird coinheringaahing!")#''';print('Happy Birthday, ChartZ Belatedly!') ``` * Byte 85-130: The byte is moved between the `""` at position 32-33. This makes the string a truthy value and the other string is printed. There is no `"` in byte 85-130, so this will always work. The second part of the program is not executed, because it is commented out. ``` '''''';print("Happy Birthday,","'"and"ChartZ Belatedly!"or"caird coinheringaahing!")#''';print(Happy Birthday, ChartZ Belatedly!') ``` [Answer] # JavaScript (browser), ~~146~~ 136 bytes Based off of the C and python answers. This is too long and it still seems sketchy to me ``` 0/**/;;alert("Happy Birthday, "+(""?"ChartZ Belatedly!":"caird coinheringaahing!"))//*/-2;alert('Happy Birthday, ChartZ Belatedly!')//*/ ``` ## Where to move: * The 0 goes after the second asterisk * The first slash moves to the right, forming `0* -1` * The first two asterisks and the second slash can move to right anywhere before the `//*/-1` * The first two semicolons go inside the empty string * Any text between the two semicolons and the `//*/-1` go after the second asterisk * Any text starting from `//*/-1` goes inside the empty string [Try this mess online!](https://tio.run/##ZczLCsIwEIXhV0ln04vWiEuLCHXjM7gbkqGJDEmYBiFPH6W40s3Z/JzviS9cjfiUxxAtVaaskEnyxcSwRqYDx6Ue9TDoadpCB3dMqajZS3YWy17BrgO4ws2h5IeaiTGT5dLAGQx6scpEHxyJDwui@2wDfa/1oMfTl2x/yT@r3Q61vgE "JavaScript (Node.js) – Try It Online") Hope this is valid and it works aaaa [Answer] # JavaScript, 123 bytes ``` 17/**/,x=>"Happy Birthday, "+(''?"ChartZ Belatedly!":"caird coinheringaahing!")//**/,x=>"Happy Birthday, ChartZ Belatedly!" ``` [Try it online!](https://tio.run/##dcyxDsIgEADQX6G3FGqVOGmaqEld/Aa3C5ByhgC5kka@Ht2NyxvfCzdcDVMu@@3cTIprCu4Q0iJlO570MOjxfbnCA3OuYiYu3mIdBexk39/g7pHLU8wuYHE21A4mMEhshUkUvWOKC6L/2oHSf7ffpimpVPsA "JavaScript (V8) – Try It Online") ## Variations (full text omitted for brevity) ``` 17/**/,x=>"HB"+(''?"CB":"cc")//**/,x=>"HBCB" 7/**1/,x=?"HB"+(''?"CB":"cc")//**/,x=>"HBCB" 1/**7/,x=>"HB"+(''?"CB":"cc")//**/,x=>"HBCB" 17**/,x=>"HB"+(''?"CB":"cc")//*/*/,x=>"HBCB" (syntax highlighting is broken, but runs ok) 17/*/*,x=>"HB"+(''?"CB":"cc")//**/,x=>"HBCB" 17/**,/x=>"HB"+(''?"CB":"cc")//**/,x=>"HBCB" 17/**x/,=>"HB"+(''?"CB":"cc")//**/,x=>"HBCB" 17/**=/,x>"HB"+(''?"CB":"cc")//**/,x=>"HBCB" // ... 17/**"/,x=>"HB'+('"?"CB":"cc)//**/,x=>"HBCB" 17/**)/,x=>"HB"+(''?"CB":"cc"//**/,x=>"HBCB" 17/**/,x=>"HB"+('/'?"CB":"cc")/**/,x=>"HBCB" 17/**/,x=>"HB"+('*'?"CB":"cc")//*/,x=>"HBCB" 17/**/,x=>"HB"+('/'?"CB":"cc")//**,x=>"HBCB" 17/**/,x=>"HB"+('x'?"CB":"cc")//**/,=>"HBCB" // ... 17/**/,x=>"HB"+('B'?"CB":"cc")//**/,x=>"HBC" 17/**/,x=>"HB"+('"'?"CB":"cc")//**/,x=>"HBCB ``` ]
[Question] [ Bibi-binary is a numeric system invented by [Boby Lapointe](https://en.wikipedia.org/wiki/Boby_Lapointe) in order to represent numbers in letters which pronunciation seems funny. Your task is to convert decimal numbers into Bibi-binary! ## Conversion A number is converted to base 16 (hexadecimal) and each character is replaced by its Bibi-binary name: ``` 0 = HO 1 = HA 2 = HE 3 = HI 4 = BO 5 = BA 6 = BE 7 = BI 8 = KO 9 = KA A = KE B = KI C = DO D = DA E = DE F = DI ``` Let `N` be a positive integer (between 1 -> 2^31-1). For every character in the hexadecimal representation of `N`, replace the character by its according Bibi-binary pair (the table above contains all the pairs). ## Example * `N` = 156 * `H` = (hexadecimal representation of `N`) --> 9C * 9 --> KA, C --> DO Thus the output is KADO. ## Input & output You will receive an positive 32-bit integer `N`, which you will have to turn into Bibi-binary. You may (return, print, etc...) in any convenient format, **but the pairs have to be connected**! So `KA DO` wouldn't be okay, but `KADO` would. Both, **lowercase and uppercase** are allowed. ## Rules * No loopholes. * This is code-golf, so the shortest code wins. ## Testcases ``` 2048 -> KOHOHO 156 -> KADO 10000 -> HEBIHAHO 12 -> DO ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~20~~ ~~18~~ 16 bytes ``` hv…ÂkdžM¨ÁâyHèJ ``` **Explanation** ``` h # convert input to hex v # for each …Âkd # string of the possible first Bibi-binary letters žM¨Á # string of the possible second Bibi-binary letters â # cartesian product to produce list of Bibi-binary pairs yH # convert hex char to base 10 è # use this to index into the list J # join ``` [Try it online!](http://05ab1e.tryitonline.net/#code=aHbigKbDg-KAmmtkxb5NwqjDgcOieUjDqEo&input=MTAwMDA) Saved 2 bytes thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan) [Answer] # Python 2, 58 bytes ``` f=lambda n:(n>15and f(n/16)or"")+"HBKD"[n/4%4]+"OAEI"[n%4] ``` A recursive solution. [Try it on Ideone](http://ideone.com/pe889f). [Answer] # Python 2, ~~81~~ 76 bytes ``` lambda n:''.join('HBKD'[int(x,16)/4]+'OAEI'[int(x,16)%4]for x in hex(n)[2:]) ``` Chooses the bibi-digit to represent each hex digit based on the patterns in the bibi-digits. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` b⁴d4ị"€“BKDH“AEIO ``` [Try it online!](http://jelly.tryitonline.net/#code=YuKBtGQ04buLIuKCrOKAnEJLREjigJxBRUlP&input=&args=MTU2) or [verify all test cases](http://jelly.tryitonline.net/#code=YuKBtGQ04buLIuKCrOKAnEJLREjigJxBRUlP4oCdCsOH4oKsWQ&input=&args=MjA0OCwgMTU2LCAxMDAwMCwgMTI). ### How it works ``` b⁴d4ị"€“BKDH“AEIO Main link. Argument: n b⁴ Convert n to base 16. d4 Divmod 4; map each base-16 digit k to [k / 4, k % 4]. “BKDH“AEIO Yield ["BKDH", "AEIO"]. € For each quotient-remainder pair [q, r]: ị" Yield "BKDH"[q] and "AEIO"[r] (1-based indexing). ``` [Answer] ## Javascript (ES6), ~~58~~ ~~53~~ 43 bytes ``` f=n=>n?f(n>>4)+'HBKD'[n/4&3]+'OAEI'[n&3]:'' ``` *Saved 10 bytes (no support for n = 0 anymore)* ### Demo ``` var f=n=>n?f(n>>4)+'HBKD'[n/4&3]+'OAEI'[n&3]:'' console.log(f(2048)); // -> KOHOHO console.log(f(156)); // -> KADO console.log(f(10000)); // -> HEBIHAHO console.log(f(12)); // -> DO ``` [Answer] # Pyth, 28 bytes ``` L+?>b15y/b16k@*"HBKD""OAEI"b ``` Defines a function `y`. Basically the same algorithm as my [Python answer](https://codegolf.stackexchange.com/a/92123/34543). Explanation: ``` L # Define a function, y, with an argument, b. ?>b15 # If b > 15, then: y/b16 # Call y with b / 16, else: k # The empty string. + # Append with *"HBKD""OAEI" # The Cartesian product of "HBKD" and "OAEI". Gives all the letter pairs in order @ b # Get the b'th number from that list. Because @ in Pyth is modular, we don't need to take b % 16. ``` [Try it here!](http://pyth.herokuapp.com/) (The extra two chars at the end is just to call the function) [Answer] # Ruby, ~~55~~ 51 bytes A recursive anonymous function: ``` f=->i{(i>15?f[i/16]:'')+'HBKD'[i%16/4]+'OAEI'[i%4]} ``` Call it for example with `f[156]` and it returns `"KADO"` [Answer] # J, ~~35~~ 33 bytes ``` [:,(,/'HBKD',"0/'OAEI'){~16#.inv] ``` Generates the table of bibi-binary values for integers [0, 16), then converts the input *n* to a list of base 16 digits and selects the corresponding bibi-binary name for each hex digit. Saved 2 bytes thanks to @randomra. ## Usage ``` ,/'HBKD',"0/'OAEI' HO HA HE HI BO BA BE BI KO KA KE KI DO DA DE DI ``` This part generates a 16 x 2 array of characters for the bibi-binary name of each hex digit. ``` f =: [:,(,/'HBKD',."0 1'OAEI'){~16#.inv] f 156 KADO f 2048 KOHOHO ``` ## Explanation ``` ,/'HBKD',"0/'OAEI' 'HBKD' 'OAEI' Constant char arrays ,"0/ Form the table of joining each char with the other ,/ Join the rows of that table [:,(,/'HBKD',."0 1'OAEI'){~16#.inv] Input: n ] Identity function, get n 16#.inv Performs the inverse of converting an array of hex digits meaning it converts a value to a list of hex digits (,/'HBKD',."0 1'OAEI') Create the bibi-binary names of each hex digit {~ For each hex digit, select its bibi-binary name [:, Join the names to form a single string and return ``` [Answer] # Perl, ~~52~~ 51 bytes Includes +1 for `-p` Run with the number on STDIN ``` bibi.pl <<< 156 ``` `bibi.pl`: ``` #!/usr/bin/perl -p 1while$\=(<{H,B,K,D}{O,A,E,I}>)[$_%16].$\,$_>>=4}{ ``` [Answer] # PHP ,63 Bytes contribution by @Titus Thank You ``` for($n=$argv[1];$n;$n>>=4)$r=HBKD[$n/4&3].OAEI[$n&3].$r;echo$r; ``` 72 Bytes works also with zero ``` do$r=OAEIHBKD[$t*4+($n=&$argv[1])%4].$r;while(($t=!$t)|$n=$n>>2);echo$r; ``` 76 Bytes alternative Version ``` for($i=2*strlen(dechex($n=$argv[1]));$i;)echo HBKDOAEI[$i%2*4+$n/4**--$i%4]; ``` [Answer] # Ruby, ~~85~~ 83 bytes ``` ->x{x.to_s(16).chars.map{|d|"HOHAHEHIBOBABEBIKOKAKEKIDODADEDI"[2*d.to_i(16),2]}*''} ``` Just a quick and simple solution without encoding the string. [Answer] # Pyth, 21 bytes ``` sm@*"HBKD""OAEI"djQ16 ``` A program that takes input of an integer from STDIN and prints the result. [Try it online](https://pyth.herokuapp.com/?code=sm%40%2a%22HBKD%22%22OAEI%22djQ16&test_suite=1&test_suite_input=2048%0A156%0A10000%0A12&debug=0) **How it works** ``` sm@*"HBKD""OAEI"djQ16 Program. Input: Q jQ16 Yield decimal digits of the base-16 representation of Q as a list "HBKD" Possible first letters "OAEI" Possible second letters * Cartesian product of those two strings @ Index into the above m d Map that across the digits list s Concatenate Implicitly print ``` [Answer] # PHP, 93 bytes ``` $a=HBKDOAEI;$h=dechex($argv[1]);while($h{$i}!=''|$c=hexdec($h{$i++}))echo$a{$c/4}.$a{4+$c%4}; ``` This basically leverages the integrated hexadecimal functions and a little trick in the while statement to save on curly braces. [Answer] # Java, 224 bytes ``` class N{public static void main(String[]a){String x="0HO1HA2HE3HI4BO5BA6BE7BI8KO9KAaKEbKIcDOdDAeDEfDI";for(int c:Long.toHexString(Long.valueOf(a[0])).toCharArray()){c=x.indexOf(c)+1;System.out.print(x.substring(c++,++c));}}} ``` Using some lookup table trickery Usage of Long type was to shave off a few bytes compared to Integer [Answer] ## [CJam](http://sourceforge.net/projects/cjam/), 20 bytes ``` qiGb"HBKD""OAEI"m*f= ``` [Try it online!](http://cjam.tryitonline.net/#code=cU4ve1MvMD06UTsKClFpR2IiSEJLRCIiT0FFSSJtKmY9Cgpdbn0v&input=MjA0OCAtPiBLT0hPSE8KMTU2IC0-IEtBRE8KMTAwMDAgLT4gSEVCSUhBSE8KMTIgLT4gRE8) (As a linefeed-separated test suite.) ### Explanation ``` qi e# Read input and convert to integer. Gb e# Get hexadecimal digits. "HBKD" e# Push this string. "OAEI" e# Push this string. m* e# Cartesian product, yields ["HO" "HA" "HE" "HI" "BO" ... "DE" "DI"]. f= e# For each digit, select the corresponding syllable. ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 19 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) Requires `⎕IO←0` which is default on many systems. ``` ∊(,'HBKD'∘.,'OAEI')[16⊥⍣¯1⊢⎕] ``` `∊` enlist (make completely flat) `(`...  `,` the raveled  `'HBKD'∘.,'OAEI'` concatenation table (i.e. all combos) `)[` indexed by...  `16⊥⍣¯1` the inverse of base-16 to base 10 (i.e. base-10 to base 16) representation  `⊢` of  `⎕` the numeric input `]` [TryAPL online!](http://tryapl.org/?a=%u2395IO%u21900%20%u22C4%20f%u2190%7B%u220A%28%2C%27HBKD%27%u2218.%2C%27OAEI%27%29%5B16%u22A5%u2363%AF1%u22A2%u2375%5D%7D%20%u22C4%20f%A82048%20156%2010000%2012&run) [Answer] # Lua, 196 Bytes ``` function(n)s=""t={"H","B","K","D"}p={"O","A","E","I"}while n>0 do s=n%4 ..s n=math.floor(n/4)end s=("0"):rep(#s%2)..s o=nil return s:gsub(".",function(s)o=not o return o and t[s+1]or p[s+1]end)end ``` Lua is annoying for this sort of a task, as it doesn't per default contain a hex or binary conversion method. Most of the flesh is converting it to base 4. After that we force a 0 behind it if we need to using `s=("0"):rep(#s%2)`, then we using gsub replace all the didgets with with their BIBI counterpart. [Answer] # [Haskell](https://www.haskell.org/), 76 bytes ``` (until(\x->x<="HO"||x>="HP")(drop 2)`map`mapM id([1..8]>>["HBKD","OAEI"])!!) ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX6M0ryQzRyOmQteuwsZWycNfqaamwg7ICFDS1Egpyi9QMNJMyE0sAGFfhcwUjWhDPT2LWDu7aCUPJ28XJR0lf0dXT6VYTUVFzf@5iZl5tgVFmXklKkDlCmkK0QY6hjpGBiYWOoamZjqGBkCgY2gU@/9fclpOYnrxf93kggIA "Haskell – Try It Online") Since the input is guaranteed to fit in 32 bits, we can generate a list of all \$16^8 = 2^{32}\$ strings and index into it, after removing `HO` (zeroes) from the start. (Haskell's Prelude has no good tools for base conversion, but Cartesian products are real easy with `mapM`.) To strip superfluous `HO`s from the start of each string, we `drop 2` characters from the front `until` the string either *equals* `HO` (0), or does not start with `HO`. The obvious way to write this is `x=="HO"||take 2x/="HO"`, but `x<="HO"||x>="HP"` is a little shorter. [Answer] # [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` s"HBKD"ï"OAEI ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=cyJIQktEIu8iT0FFSQ&input=MTAwMDA) Or, with string compression: ``` s`baki`ó rï ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=c2CXYmFrgmlg8yBy7w&input=MTAwMDA) [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), ~~30~~ 27 bytes ``` ,/(,/"HBKD",/:\:"OAEI")@16\ ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NSkdfQ0dfycPJ20VJR98qxkrJ39HVU0nTwdAs5n@aupGBiYWCoamZgqEBECgYGv0HAA "K (ngn/k) – Try It Online") Quite similar to the J solution by @miles and the APL solution by @adám. [Answer] # [Haskell](https://www.haskell.org/), 50 bytes ``` (l!!) l=[]:tail[x++[a,b]|x<-l,a<-"HBKD",b<-"OAEI"] ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzXyNHUVGTK8c2OtaqJDEzJ7pCWzs6UScptqbCRjdHJ9FGV8nDydtFSScJyPJ3dPVUiv2fm5iZp2CrUFCUmVeioKKQm1igkKYQbWRgYqGjYGhqBiQMgABIGcX@/5eclpOYXvxfN7mgAAA "Haskell – Try It Online") Recursively defines the infinite list `l` of all encoded numbers starting from 0. --- # [Haskell](https://www.haskell.org/), 54 bytes ``` f n=mapM id([1|i<-[0..8],16^i<=n]>>["HBKD","OAEI"])!!n ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzY3scBXITNFI9qwJtNGN9pAT88iVsfQLC7TxjYv1s4uWsnDydtFSUfJ39HVUylWU1Ex739uYmaegq1CQVFmXomCigLQBIU0hWgDHQVDHQUjIAnCpmZAtoGJBZBpAASx//8lp@Ukphf/100uKAAA "Haskell – Try It Online") Based off of [Lynn's solution](https://codegolf.stackexchange.com/a/214538/20260). The new idea is to avoid leading "zeroes" (`HO`'s) by predicting the number of digits in advance and only generating that many copies for `mapM`. A number has one digit in base 16 for each number in `1,16,256,4096,...` that is no greater than it. This gives the empty string for zero, but we could change it to `HO` like this: **56 bytes** ``` f n=mapM id(0:[1|i<-[1..8],16^i<=n]>>["HBKD","OAEI"])!!n ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzY3scBXITNFw8Aq2rAm00Y32lBPzyJWx9AsLtPGNi/Wzi5aycPJ20VJR8nf0dVTKVZTUTHvf25iZp6CrUJBUWZeiYKKAtAMhTSFaAMdBUMdBSMgCcKmZkC2gYkFkGkABLH//yWn5SSmF//XTS4oAAA "Haskell – Try It Online") A variant where we compute the number of digits directly: **60 bytes** ``` f n=mapM id([0..until(\i->16^i>n)(+1)0]>>["HBKD","OAEI"])!!n ``` [Try it online!](https://tio.run/##FYzBCsIwEAV/ZRs8NJiWRLR4aUBRUET8gJhCqEYX0yXY@vvG@GCGOb2nG1/3EFLyQO3g4hnwVhpZ1x@aMJRXrLRqOtTEy7ni0mpt2GF72jHBLpv9kVleFJQGhwQtxDfSBDPIP@DBSAFKwCL7z6rJLZfrnDLPpm/vg3uMqepj/AE "Haskell – Try It Online") --- # [Haskell](https://www.haskell.org/), 54 bytes ``` f 0="" f n=f(div n 16)++mapM id[cycle"HBKD","OAEI"]!!n ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P03BwFZJiStNIc82TSMls0whT8HQTFNbOzexwFchMyU6uTI5J1XJw8nbRUlHyd/R1VMpVlEx739uYmaegq1CQVFmXomCigJQtUKaQrSBjoKhjoIRkARhUzMg28DEAsg0AILY//@S03IS04v/6yYXFAAA "Haskell – Try It Online") [Answer] # [Chip](https://github.com/Phlarx/chip), 174 bytes ``` z---. !+ZZZ^~s Axxx])~-vv/c Ex]xx' ,x]/b Bxxx])~^}~/d Fx]xx'g*-}^a Cxx])v]--/c G]xx'>x~v/d Dxx])x+-]/a H]xx'`}--/b )x)-----' Axx].zv~S Bxx]+^' Cxx]< Dxx]< E]v-' F]< G]< H]' ``` [Try it online!](https://tio.run/##RVBNa8MwDL3rV2ilw81S2WynHkJhXZP2tsNuAYclabsGRmcaY7Sy@K9ndnaYQEK89/TZ1P15bGuLa7TH3sr23BnMMhT5ayFGvBGRhLu0LMvK9/DMzDrx5JxqIWfNLHDJWjWw@WOqwasDFBPz8UBDVcNLJJwmCiW7iK/ZuyDaRpxT0qqGfcTfh6BpABNOKJqI47S8Of8W2@u0ElOzbCrNINcuaIqQ7YLvtRjDzgDm2l3sCWf3csUznC/icfNT93lM8AeZD0hXJBNy9WWsivdOQZpvJPf/hPHx6Rc "Bash – Try It Online") TIO includes a Bash wrapper that converts an integer string to an actual 32-bit integer value. The top half prints out the letters corresponding to the binary data, once the bottom half has detected that we've reached the interesting data (in other words, we skip leading zeroes. To print all leading zeroes, remove the second line that starts with `A` and down. [Answer] # [C (gcc)](https://gcc.gnu.org/), 206 bytes ``` #include<stdio.h> #include<unistd.h> int main(){int a=0;char c;while(read(0,&c,1)){a*=10;a+=c-'0';}c=8;while(c--)if(a&15<<c*4)break;if(c!=7)c++;while(c--)printf("%c%c","HBKD"[a>>c*4+2&3],"OAEI"[a>>c*4&3]);} ``` Uses as requested input, no check done on read return. ``` int a=0;char c; // declares accumilator and input char while(read(0,&c,1)){a*=10;a+=c-'0';} // read input in accumulator c=8;while(c--)if(a&15<<c*4)break;if(c!=7)c++; // goto first not null byte while(c--)printf("%c%c", // print for each byte "HBKD"[a>>c*4+2&3], // fetching right consonant "OAEI"[a>>c*4&3]); // fetching right vowel ``` [Try it online!](https://tio.run/##Tc3fCoIwFAbw@57CFuqmLmZ/KJgTioKiix4gulhHzZFZmNKF@OxrQUXn6uPH93GAngG0HqgSiiZJo0edqNswj3s/aUpl8E2qrK2rVCUm7TtKwTjksrKAP3NVpLhKZYJZ4EAQEtJKT4SMS18AdZnLOxDzTw8oJSrD0gmnUQTehJzM8sINQV/MCPj@X/FemV8ZRjbYgAK0We5W6CDj2Oz8kTM@Bmi/WG@/ZIDwTuuQmXsB "C (gcc) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 20 bytes ``` ṁ!ṙ1*"HBKD""OAEI"B16 ``` [Try it online!](https://tio.run/##yygtzv7//@HORsWHO2caail5OHm7KCn5O7p6KjkZmv3//9/IwMQCAA "Husk – Try It Online") Similiar to the APL answer. # [Husk](https://github.com/barbuz/Husk), 22 bytes ``` ṁz!e"BKDH""AEIO"m‰4B16 ``` [Try it online!](https://tio.run/##yygtzv7//@HOxirFVCUnbxcPJSVHV09/pdxHDRtMnAzN/v//b2RgYgEA "Husk – Try It Online") Idea from Dennis' answer. ]
[Question] [ Two strings are "Caesar equivalent" if the distance (counting up) between the corresponding characters are the same. Yes, I made this term up. Here's an example: "Abc" and "Cde" are equivalent because ``` distance from a-c == 2 distance from b-d == 2 distance from c-e == 2 ``` The capitalization doesn't make any difference. "Hello" and "World" are not Caesar equivalent because ``` distance from h-w == 15 distance from e-o == 10 distance from l-r == 6 distance from l-l == 0 distance from o-d == 15 ``` "Abcd" and "Yzab" are Caesar equivalent because ``` distance from a-y = 24 distance from b-z = 24 distance from c-a = 24 (it wraps around) distance from d-b = 24 ``` You must write a full program that takes two strings from STDIN, and prints a truthy value if they are Caesar equivalent, and a falsy value if they are not. # Valid Input * Since capitalization doesn't matter, it is acceptable if your program requires the input to be all lower-case, all upper-case, or whatever mix you want, as long as this is specified in your answer. * The input will not have spaces or punctuation. * The inputs will be the same length. [Answer] # CJam, ~~17~~ ~~12~~ 11 bytes *1 byte saved by Dennis.* ``` ll.m26f%)-! ``` [Test it here.](http://cjam.aditsu.net/#code=ll.m26f%25)-!&input=abc%0AYZA) Expects the first string to be lower case and the second to be upper case. Prints `1` for Caesar-equivalent strings and `0` otherwise. ## Explanation ``` ll e# Read two lines of input. .m e# Take the differences of corresponding characters. 26f% e# Take the differences modulo 26. )- e# Remove all copies of the last difference from the array. This will e# yield an empty array if and only if all differences are the same. ! e# Logical NOT, which yields 1 for an empty array and 0 otherwise. ``` The reason we require the first string in lower case and the second in upper case is to ensure that the difference is always positive. Otherwise taking the modulo might return something negative and would not necessarily be unique, even for Caesar-equivalent strings. [Answer] # Pyth, 9 bytes ``` }wm=.rzGG ``` The two strings are expected in lowercase, newline separated. [Demonstration.](https://pyth.herokuapp.com/?code=%7Dwm%3D.rzGG&input=abcd%0Ayzab&debug=0) How it works: `.r` is Pyth's rotary translation function. It maps each element in the first argument from its first occurance in the second argument to the next entry in the second argument. In this, case, the second argument is `G`, the lowercase alphabet, so this is equivalent to a Caesar shift of 1. Putting an `=` in front of the function makes it in-place. Thus, `=.rzG` assigns the Caesar shift of `z` by one to `z`. Note that `z` is initialized to the first line of input in Pyth. This expression is used inside a map. `m=.rzGG` applies this transformation to `z` 26 times, once for each element of `G`, and saves the results in a list. This gives the list of all possible Caesar shifts of `z`. Finally, `}w` checks whether the next line of input is in that list. [Answer] # APL (15) ``` 1=≢∪26|-⌿⎕A⍳↑⍞⍞ ``` It needs the letters to be uppercase, and prints either `1` or `0`, like so: ``` 1=≢∪26|-⌿⎕A⍳↑⍞⍞ ABCD YZAB 1 1=≢∪26|-⌿⎕A⍳↑⍞⍞ HELLO WORLD 0 ``` Explanation: * `↑⍞⍞`: read two lines from the keyboard, and arrange the characters in an N×2 matrix. * `⎕A⍳`: for each character, find at which position it occurs in `⎕A` (the uppercase alphabet). * `-⌿`: for each column, subtract the second value from the first value * `26|`: take the mod-26 of each of those numbers. * If the strings are Caesar-equivalent, all numbers in this list are now equal, so: * `≢∪`: find the number of unique values in the list * `1=`: compare that to `1`. [Answer] # Prolog, 56 bytes ``` b([],[],_). b([A|C],[B|D],N):-N is mod(A-B,26),b(C,D,N). ``` Not all combinations of cases are supported. usage ``` b(`abcd`,`yzab`,_). ``` [Try it online here](http://swish.swi-prolog.org/p/AjgqohQx.pl) [Answer] # J, 19 bytes ``` 1=[:#@~.26|-&(3&u:) ``` Letters at the same position should have the same case. After converting both input strings to their codepoint representation with `&(3&u:)` we compare `1` to the length `#` of the nub `~.` of the modulo 26 `26|` of the difference `-` of the two arrays. The nub will be `1` if all Caesar-distances are the same. Usage: ``` 'abcd' (1=[:#@~.26|-&(3&u:)) 'yzab' 1 ``` [Try it online here.](http://tryj.tk/) [Answer] # Julia, ~~91~~ ~~87~~ 83 bytes ``` a=readline() b=readline() show(length(Set([mod(a[i]-b[i],26)for i=1:length(a)]))<2) ``` Ungolfed + explanation: ``` # Read two strings from STDIN a = readline() b = readline() # Get the absolute difference mod 26 of the character values in the strings x = [mod(a[i] - b[i], 26) for i = 1:length(a)] # Construct a set consisting of the elements of x. If the set has only a # single element, the strings are Caesar equivalent. This will print a # boolean value to STDOUT. show(length(Set(x)) < 2) ``` This takes advantage of the fact that strings in Julia can be treated as character arrays and that arithmetic operations can be performed on character values. The input strings can have any mix of capitalization you want, so long as the capitalization at each position matches between the strings. [Answer] # C99, ~~92 bytes with bug~~   ~~101~~ 92 bytes ``` r,i;main(z,a)char**a;{for(;z=a[2][++i];)r|=(a[1][i]-z+*a[2]-*a[1]+52)%26;putchar(49-!!r);} ``` Pretty straightforward; assumes words come as first and second arguments, respectively. Compiled with `-std=c99`. [Answer] # Javascript (*ES7 Draft*), 87 bytes Requires inputs to be the same case. ``` (p=prompt)(![z=(a[c='charCodeAt'](i)-b[c](i)+26)%26 for(i in b=p(a=p()))].some(x=>x^z)) ``` [Answer] # CJam, 13 bytes ``` {r(fm26f%}2*= ``` It requires the first character in each word to be in upper case, others in lower case. [Try it here](http://cjam.aditsu.net/#code=%7Br%28fm26f%25%7D2*%3D&input=Abcd%0AYzab). ([Firefox here](http://cjam.aditsu.net/#code=%7Br%28fm26f%2525%7D2*%3D&input=Abcd%0AYzab).) Too bad the APL variants doesn't support character arithmetics... ### Explanation ``` { r e# Read a word. (f- e# Return each character value minus the first character. 26f% e# Mod 26. }2* e# Repeat 2 times. = e# Check if they are equal. ``` [Answer] # Perl, 80 ***Edit**: A failed optimization had slipped into the golfed code. Now it matches the ungolfed version. (The byte count was correct, though.)* ``` @a=unpack"W*",<>;for(<>=~/./g){$n=ord()-shift@a;$p=!$c++||$p&&$n==$o;$o=$n}say$p ``` Run with Perl version 5.10 (`perl -M5.10.0` or `perl -E …`) for `say()`. Slightly expanded version: ``` @a=unpack"W*",<>; # read first string, split and convert to numbers for(<>=~/./g){ # reads the second string and splits it $n=ord()-shift@a; # convert next character of second string and compare $p= !$c++ || $p && $n==$o; # compare differences (special case for first char) $o=$n } say $p ``` The code outputs `1` (truthy in Perl) if the strings are Caesar equivalent, and the empty string (falsy in Perl) if they are not. If this is too loose an interpretation, I need to add 2 bytes for `say$p+0`, which prints `1` or `0`. Character case must match between inputs. [Answer] # Matlab, ~~49~~ 48 bytes This was a really quick one. Sadly getting a string from stdin is quite expensive. ``` x=@()input('','s');sum(diff(mod(x()-x(),26)))==0 ``` Note that it is, like most if not all answers, case sensitive. EDIT: shaved off one byte by defining an anonymous function! [Answer] ## C, 97 bytes ``` #define D (*a[2]++-*a[1]+++26)%26 d,r;main(int c,char**a){for(d=D;*a[1];r|=d-D);puts(r?"N":"Y");} ``` [Answer] # [R](https://www.r-project.org/), 48 bytes ``` a=scan(,'');`+`=utf8ToInt;!sd((+a[1]-+a[2])%%26) ``` [Try it online!](https://tio.run/##K/r/P9G2ODkxT0NHXV3TOkE7wba0JM0iJN8zr8RasThFQ0M7MdowVhdIGsVqqqoamWn@T0xKrqis4kpJTQOy/v8HAA "R – Try It Online") Standard deviation (`sd`) of the differences between the character codes (mod 26) is zero only if they are all the same. Requires all-same-case input. [Answer] # Scala, 57 bytes ``` (readLine zip readLine map(x=>x._1-x._2%26)toSet).size==1 ``` Little longer than the others, and essentially equivalent, but it is in a vary different style of language! I also have this version(56 bytes): ``` (readLine zip readLine map(_._1-x$1._2%26)toSet).size==1 ``` But I don't know if the x$1 working is coincidence or by design... [Answer] **Python 2, 80 bytes** Takes 2 similarly-cased strings from stdin separated by a space : ``` s,t=raw_input().split();print len(set((ord(c)-ord(d))%26 for c,d in zip(s,t)))<2 ``` Tested on following test cases : ``` tests = [ ("abc", "abc", True), ("abcd", "abc", False), ("abc", "cde", True), ("Abc", "Cde", True), ("abc", "deg", False), ("Hello", "World", False), ("Abcd", "Yzab", True), ("", "", True) ] for s, t, v in tests: if len(s) == len(t): # I didn't read that at first assert v == (len(set((ord(c) - ord(d)) % 26 for c, d in zip(s, t))) < 2) ``` [Answer] # Python 2 - ~~241~~ ~~237~~ ~~188~~ 147 Bytes Takes input as lowercase string enclosed in quotes, space separated. There has to be a better way.. ``` s=[[ord(x)for x in y]for y in input().split()];v=[];v=[v+[(s[1][i]-s[0][i])%26]for i in xrange(0,len(s[0]))];v=sum(v,[]);print sum(v)//v[0]==len(v) ``` Ungolfed (260-odd bytes) ``` strs = [[ord(x) for x in y] for y in raw_input().split()] vals = [] for i in xrange(0, len(strs[0])): if strs[0][i]<strs[1][i]: vals += [strs[1][i]-strs[0][i]] else: vals += [26-(strs[0][i]-strs[1][i])] return sum(vals)//vals[0] == len(vals) ``` [Answer] # R, 83 ~~84~~ Fairly much the same as the other solutions. Convert the strings into a vector of integers. Mod the difference of the vectors by 26. Do a unique over the list as check the length is 1. It expects the case to be the same in corresponding characters in each string. ``` length(unique(((S=strtoi)((R=charToRaw)((I=readline)()),16L)-S(R(I()),16L))%%26))<2 ``` It waits for the two strings to be entered ``` > length(unique(((S=strtoi)((R=charToRaw)((I=readline)()),16L)-S(R(I()),16L))%%26))<2 abcdefghijklmnopqrstuvwxyz opqrstuvwxyzabcdefghijklmn [1] TRUE > length(unique(((S=strtoi)((R=charToRaw)((I=readline)()),16L)-S(R(I()),16L))%%26))<2 Hello World [1] FALSE > length(unique(((S=strtoi)((R=charToRaw)((I=readline)()),16L)-S(R(I()),16L))%%26))<2 Bob Nan [1] TRUE > ``` [Answer] # Matlab/Octave, ~~53~~ 52 ``` x=@()input('','s');isscalar(unique(mod(x()-x(),26))) ``` Input should all be of the same case. Sadly, Matlab is not very good with user input. As an anonymous handle, this could be only 35 bytes: ``` @(a,b)isscalar(unique(mod(a-b,26))) ``` Matlab treats the characters of a string as a vector of numbers. Doing subtraction gets us their difference, and `unique` converts that vector into a vector containing only unique values. If there is only one number, the words are caeser equivalent and isscalar returns 1, otherwise it will return 0. [Answer] # bash, ~~71~~ 48 Using the “standard” Unix program `caesar(6)`. New version (with lots of help from @DigitalTrauma): ``` read a b;seq -f"caesar %g <<<$a" 26|bash|grep $b ``` * Inputs have to be on the same line, separated by spaces * Character case must match between inputs. * Prints `1` for true or nothing for false. If input via command line arguments is allowed, it can be shortened to **39 bytes**: ``` seq -f"caesar %g <<<$1" 26|bash|grep $2 ``` Old version for the record: ``` read a b;for i in `seq 26`;do [ `echo $a|caesar $i` = $b ]&&echo 1;done ``` [Answer] # [><> (Fish)](http://esolangs.org/wiki/Fish), 50 bytes ``` i:3b*(?v88+0.;n1< 0)?vc1.>~ri-&l?!^i-&:&-2d*% ;n0< ``` Expects letters at the same position to have the same case. Explanation * `i:3b*(?v` reads the first word into the stack with `88+0.` providing the looping jump * `~ri-&` removes `~` the separating space from the stack, reverses the stack `r` (first letter will be on top), reads in the first letter of the second word `i`, calculates the offset from the first word's first letter `-` and stores it in the register `&`. * `l?!^i-&:&-2d*%0)?v` reads every next letter of the second word substracting it from the first word's corresponding letter which is at the top of the stack substracts the offset `&:&-` stored in the register and checks if the result is 0 mod 26 `2d*%`. If not prints 0 and terminates `0n;`. `c1.` provides the looping jump. * If reached the end of the second word the program prints 1 and terminates `1n;`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` Oạ/ċ2 ``` [Try it online!](https://tio.run/##y0rNyan8/9//4a6F@ke6jf4fbn/UtOa/J5fCkW4DLoVDax7u2vE/OlopA6gsX0lHQak8vygnRSlWRyFaKTEpOUVJR6myKjEJLgBSkpySqhQbCwA "Jelly – Try It Online") Outputs a positive integer for equivalent, 0 otherwise ## How it works ``` Oạ/ċ2 - Main link. Argument A (a list of strings) e.g. ["abc", "cde"] O - Ordinal. Cast to code point [[97, 98, 99], [99, 100, 101]] / - Reduce the list by... ạ - absolute difference [2, 2, 2] ċ2 - Count the number of 2s in the list 3 ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 14 bytes(SBCS) ``` 1=≢∪26|-⌿⎕UCS⎕ ``` Takes input as a two row matrix and returns truthy or falsey value [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L@h7aPORY86VhmZ1eg@6tn/qG9qqHMwkATJ/lcAgwKuR20T1R2dnNUV1J1dXNW5kIU9UnNy8oES4flFOSmoUkAdLkCZyChHJ3UA "APL (Dyalog Unicode) – Try It Online") ## Explanation ``` 1=≢∪26|-⌿⎕UCS⎕ ⎕UCS⎕ ⍝ Convert all characters to Unicode codepoints -⌿ ⍝ Subtract pairs of matrix along leading axis(x) 26| ⍝ Get residue(modulus) of 26 with each difference(works with negatives) 1=≢∪ ⍝ Check if number of unique remainders is equal to 1. ``` [Answer] # [Pip](https://github.com/dloscutoff/pip) `-r`, 12 bytes ``` $=($-A^g)%26 ``` [Try it online!](https://tio.run/##K8gs@P9fxVZDRdcxLl1T1cjs//@k5JTUtPRErvKKyqrEpLL/ukUA "Pip – Try It Online") ### Explanation With the `-r` flag, `g` is a list of lines from stdin rather than the usual list of command-line arguments. ``` ^g Split each line into a list of characters (^ vectorizes on lists) A Convert each character to its ASCII code (A vectorizes on lists) We now have a list of two lists of numbers. $- Fold on subtraction; since - also vectorizes on lists, this does pairwise subtraction of the character codes, returning a list of differences ( )%26 Take each difference mod 26 (% also vectorizes) $= Fold the list on equals: 1 if all items are equal, 0 otherwise ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~33~~ 18 bytes ``` $=({Aa-Ab}%26MZqq) ``` -15 bytes from Dlosc. [Try it online!](https://tio.run/##K8gs@P9fxVaj2jFR1zGpVtXIzDeqsFDz///EpOQULiBO/f8fAA "Pip – Try It Online") ## Explanation ``` $=({AB((Ab<Aa?-26 0)+Aa-Ab)}MZab) ; a,b → command line args MZab ; Map items of a and b to function, pass as (a,b) { Aa-Ab } ; Subtract codepoints of a and b (Ab<Aa?-26 0)+ ; Add -26 if b > a AB( ) ; Take the absolute value of the whole thing $= ; Check if all items of the mapped list are equal ``` [Answer] # KDB(Q), 35 bytes ``` {0=sum(1_-':)mod[;26](-)."i"$(x;y)} ``` # Explanation ``` "i"$(x;y) / convert to ascii decimal (-). / get differences mod[;26] / mod 26 (1_-':) / difference between the differences 0=sum / sum should be 0 if equivalent { } / lambda ``` # Test ``` q){0=sum(1_-':)mod[;26](-)."i"$(x;y)}["abcd";"yzab"] 1b ``` [Answer] # Java 281 ``` import java.util.*;enum C{E;Scanner s=new Scanner(System.in);public static void main(String[]z){char[]u=E.n(),v=E.n();int i=0,d=(u[0]-v[0]+26)%26;boolean e=true;for(;++i<u.length;)e&=d==(u[i]-v[i]+26)%26;System.out.print(e);}char[]n(){return s.next().toUpperCase().toCharArray();}} ``` expanded: ``` import java.util.*; enum Caesar{ Equivalence; Scanner input=new Scanner(System.in); public static void main(String[]z){ char[]firstString=Equivalence.nextInput(),secondString=Equivalence.nextInput(); int index=0,difference=(firstString[0]-secondString[0]+26)%26; boolean isEqual=true; for(;++index<firstString.length;) isEqual&=difference==(firstString[index]-secondString[index]+26)%26; System.out.print(isEqual); } char[]nextInput(){ return input.next().toUpperCase().toCharArray(); } } ``` I could save 14 bytes if I got rid of converting everything to uppercase, but I feel like it's more complete to leave it in. [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~68~~ 66 bytes ``` $a,$b=$args;(1..$a.Length|%{($a[--$_]-$b[$_]+26)%26}|gu).count-eq1 ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/a@SpmCrUP1fJVFHJclWJbEovdhaw1BPTyVRzyc1L70ko0a1WkMlMVpXVyU@VlclKRpIaRuZaaoamdXWpJdq6iXnl@aV6KYWGv6v5VIDGqbk6OSspKDk4uqmBOUnJacABSKrEpOgIh5Ay/OBQuH5RTkpSv8B "PowerShell Core – Try It Online") ``` (1..$a.Length # Builds an array of the size of one of the input |%{($a[--$_]-$b[$_]+26)%26} # For each of the characters, gets their distance making sure we stay between 0 and 25 |gu # Remove duplicates ).count-eq1 # Returns True if we have a single record ``` [Answer] # [Zsh](https://www.zsh.org/) `-eo extendedglob`, 43 bytes ``` >$2 repeat 25 {1=`tr a-z b-za<<<$1`;ls ^$1} ``` [Try it online!](https://tio.run/##qyrO@K9RnFqioJuar5BaUZKal5Kakp6Tn6SglJiUnKKkoJSWnlGo9N9OxYirKLUgNbFEwchUodrQNqGkSCFRt0ohSbcq0cbGRsUwwTqnWCFOxbD2v6aanb6Wfl5pTg4XSMb@PwA "Zsh – Try It Online") Input from command-line arguments and output via exit code. I'm not doing stdin/stdout, that's idiotic. ]
[Question] [ ## Task Given two positive integers `a`, `b` and a Unicode mathematical inequality symbol `c`, determine if `a c b` is true. You many take the character or its Unicode codepoint for the input `c`. You may output your language's truthy/falsy values, or two distinct values for true and false respectively. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## List of symbols to support ``` Symbol | Hex | Dec | Name --------+--------+--------+------------- < | 003C | 60 | Less than = | 003D | 61 | Equal to > | 003E | 62 | Greater than ≠ | 2260 | 8800 | Not equal to ≤ | 2264 | 8804 | Less than or equal to ≥ | 2265 | 8805 | Greater than or equal to ≮ | 226E | 8814 | Not less than ≯ | 226F | 8815 | Not greater than ≰ | 2270 | 8816 | Neither less than nor equal to ≱ | 2271 | 8817 | Neither greater than nor equal to ``` The last four symbols may look broken in Chrome. They are four symbols `<>≤≥` with slash overstrike, indicating negation. ## Truthy test cases ``` 1 < 2 1 = 1 2 > 1 1 ≠ 2 2 ≠ 1 1 ≤ 1 1 ≤ 2 2 ≥ 1 1 ≥ 1 2 ≮ 1 1 ≮ 1 1 ≯ 1 1 ≯ 2 2 ≰ 1 1 ≱ 2 ``` ## Falsy test cases ``` 1 < 1 2 < 1 1 = 2 2 = 1 1 > 1 1 > 2 1 ≠ 1 2 ≤ 1 1 ≥ 2 1 ≮ 2 2 ≯ 1 1 ≰ 1 1 ≰ 2 2 ≱ 1 1 ≱ 1 ``` [Answer] # JavaScript (ES6), ~~58 45~~ 42 bytes *Saved 3 bytes thanks to @Neil* Expects the Unicode code point for \$c\$. Returns \$0\$ or \$1\$. ``` (a,c,b)=>'14353426'[c%61%9]>>(a>b?2:b>a)&1 ``` [Try it online!](https://tio.run/##VVG7TsMwFN3zFVeRmsSKibAbKhViIwZ29siDYxpoVcWojhjZ@xcM7QrtL/VHQkQV@XqxzktH58ob/amd2a0/@pvOvq6GVgyZpoY2RMiUlfO7eckXaW1mCzZbKikzLZtHft9ITRI2PNQRQMygAh7TKxTArpCDnCCDy/57ivB/gpxDSFDsiJ2jL77sf7ATkN@QoLYTds6TM0mVr698UPgC4VWJIcc3oomHcDzHe9GqYO8pJCh2DsezOFJR0drdszbvmQMhwdjO2e2q2Nq3UUgScJBDCl9yfHJos9zVt4qCq7kqzPjVL3bd9U99RiiMVqkIIcMf "JavaScript (Node.js) – Try It Online") ### How? Each comparison character is assigned a 3-bit mask describing if it should be truthy for `a > b`, `a < b` or `a == b`. ``` char. | code | meaning | > | < | = | mask -------+------+-----------------------------------+---+---+---+------ < | 60 | Less than | 0 | 1 | 0 | 2 = | 61 | Equal to | 0 | 0 | 1 | 1 > | 62 | Greater than | 1 | 0 | 0 | 4 ≠ | 8800 | Not equal to | 1 | 1 | 0 | 6 ≤ | 8804 | Less than or equal to | 0 | 1 | 1 | 3 ≥ | 8805 | Greater than or equal to | 1 | 0 | 1 | 5 ≮ | 8814 | Not less than | 1 | 0 | 1 | 5 ≯ | 8815 | Not greater than | 0 | 1 | 1 | 3 ≰ | 8816 | Neither less than nor equal to | 1 | 0 | 0 | 4 ≱ | 8817 | Neither greater than nor equal to | 0 | 1 | 0 | 2 ``` We store these masks in a 8-character lookup string whose index is computed by applying two consecutive modulos to the code point: ``` code | mod 61 | mod 9 | mask ------+--------+-------+------ 60 | 60 | 6 | 2 61 | 0 | 0 | 1 62 | 1 | 1 | 4 8800 | 16 | 7 | 6 8804 | 20 | 2 | 3 8805 | 21 | 3 | 5 8814 | 30 | 3 | 5 8815 | 31 | 4 | 3 8816 | 32 | 5 | 4 8817 | 33 | 6 | 2 ``` [Answer] # [Python 2](https://docs.python.org/2/), 45 bytes ``` lambda a,o,b:o%83*45%555%16%6+1>>cmp(a,b)+1&1 ``` [Try it online!](https://tio.run/##dZJLboMwFEXnrOJJFbVp3CqmgSIU2EgaVZCEBomfwAyiqgvoLjpIpk2ypW6E@sPHGXTEve9ePx0jVwe2Lwu7u9uU27R496FlyaNnJMFrl0V5vI0gIiWJ/dL0nh8Wjuk4jkld053RMNzkFY5IbM3oPe2aQx6XWQMBfKAl8sGdE0CBEJSLUAibi9@vby49bz6X5qjMQpqTMo40P9JQlZyVUclFGVeaqzIvn4bB6pbtDxxghSgswUa8QLmlQtgQKkGBI6jQlnKcHnU5Fk7T9DSs4nTTVJNnXY4bLtP0yqdrw0iirJlA@6XLoRYMR4NhEk7Cnu4wwhx1RHviGgk0rosux8JVR6QSsayB7RoGaQH9j52B5PYNkMkb5xNfbkW5Fc3@EYjKbentqd5VWbTZ4ZY0rMZ9cdWuLYuXIwIlgZiX86jCacGIOtRUWcowAiRbVc0TLBKLjBbfUlpahIIQaVY@5P/jBPcUltX9AQ "Python 2 – Try It Online") Improved based on @Arnauld's answer, make sure to upvote him! The bitmask here is a different from @Arnauld's answer because bit `0` and `1` are swapped. *As usual*, the lookup table is replaced by some cool magic numbers. # [Python 3](https://docs.python.org/3/), ~~51 48~~ 47 bytes ``` lambda a,o,b:o%83*45%555%16%6+1>>(a>b)+(a>=b)&1 ``` [Try it online!](https://tio.run/##VZJBboJAFIb3nOJt6ECdNA4KNcaZi1hjhlajCQqBYWGaHqC36EK3Va/Ui9A3M8DgBr7/vZ/JB6E4qV1@nDRb/tZk8pB@SJA0p@k892eT52nsx3Hss8RPRkyIQIo0HOGVp@ETa6rTIc2zCjh8kgWZQzKmQLgGhiA0RAh/3z@Is9l4bMLZhqkJFxtiE35NYHZztcFubjYkJtxteP3yPFXWandCgSVhsICIYIFhZBoiEBYYoIJdRgb76XmIfeHippfuKLRz0wFeh9ifcHPTO05XnreVWeVE20MXXY13j/JuIhxE7h16mfNQMXJevcHA6zbEvnAfKjKjmJegNpWC/RHaDzsC4z33wGzW6KfvGHW51s32J9CVx9L6pdwUmXzfBDWtVBm0xWW9CkMsSwo5hRTLB1kE@6Oi9qGqyPYqIEBMqyhxE@gNfVSjhAtCza9qcRuYEIbNPw "Python 3 – Try It Online") --- # [Python 2](https://docs.python.org/2/), ~~47~~ 46 bytes ``` lambda a,o,b:(cmp(a,b)==1-o*6%43%7%3)^o*3%58%3 ``` [Try it online!](https://tio.run/##dZJLbsIwFEXnWcWTqsgONRVO@EQRzkYoRQmQEik/Jc4AVV1Ad9EBTAtsqRuhjp2PGXSUe9@9fjqOXBz5Ic/s@9M238XZuwc1j8auEbHXexKk4S6AgOQk9PA2LXBAQosxOs5Hc3PqmAvTsd7ykWPOXNO5V8c0zJMKGHygJfJgPiGAWCOoEH4jbCF@v76FdN3JRJqTMlNpzsrMpPmRhqrkooxKrsrMpbkps/g0DF7W/HAUACtEYQk2EgUqLG2EDb4SFASCCm0p@@lJl33hPEzP3SpBN0w1edFlv@E6TG9iujaMKEiqAbRduuxqrDvKuok/CHu4Qw9z0hHtgasn0LiuuuwLNx2RSsS8BL6vOMQZtD/2GSS3Z4BMNoKv@QrblOum2T6CpvJY2ryU@yIJtntck4qXuC2u6rVliXJAICcQinIaFDjOOFGHqiKJOUaAZKsoRYKbxCK9xY@UlhYh5iPNypf8fxzhlsKy7n8 "Python 2 – Try It Online") Every operation can be expressed by `(cmp(a,b)==a)^b`. For example, `a<b` iff `(cmp(a,b)==-1)^0`. We then use some dirty magic numbers to compress a and b. # [Python 3](https://docs.python.org/3/), ~~51 49~~ 48 bytes ``` lambda a,o,b:((a<b)+(a<=b)==o*6%43%7%3)^o*3%58%3 ``` [Try it online!](https://tio.run/##VZJLboMwFEXnrOJNkE1iVTHkpwizkTSNTEuUSCQgMIOo6gK6iw6SaZNsqRuhzza/TODc9y7WAZGf1T47BfVOvNapPMYfEiTLWLyiVIaxN8ariD0hstHcnQbuwg28t2wUuLOlG9Tl@RhnaQkCPklIVjCfMCBCA0eINPgIf98/iMvlZGLCxYapCVcbZib8msDt5maD3dxtmJvwsGHx5TiqqNT@jAJrwiEEn2CBY@QafIgscEAFu/QNdtPLELvCtZ9e26PQrp8O8DbE7oR7P33gdOM4O5mWvWhzaNjWRPuoaCdRD37/Dp3MZajo916dwcDrPsSu8BgqcqOYFaCSUsHhBM2HHYPxXjlgNlv003eMulzpZvMT6MpzaftSJHkq3xNasVIVtCmuq43nYVkyyBjEWD7KnB5OitmHyjw9KEqAmFZe4IbqDXtWY0REhJl/1eKOmuB59T8 "Python 3 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~34~~ ~~33~~ ~~24~~ ~~23~~ 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` •1P42•b3ôs61%èŠ.Sè ``` -9 bytes by porting [*@ovs*' Python 3 answer](https://codegolf.stackexchange.com/a/203589/52210), so make sure to upvote him! -6 bytes thanks to *@Grimmy*. Input of the character as codepoint integer. Input-order as `c,b,a`. [Try it online](https://tio.run/##yy9OTMpM/f//UcMiwwATIyCVZHx4S7GZoerhFUcX6AUfXvH/v4WFoSmXEZchAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaVyQvHh9oT/jxoWGQaYGAGpJOPDW4rNDFUPrzi6QC/48Ir/Ov@jlQwVbBSMlHSAtK2CIZA2UrAD04YKjzoXgGWMwCyY2BIkFkx2KVxsKdSMR53r4GII1nokFkzvBrjYRqg7bKBm2EBlbKFqbaF8OzhtBHcnzNYlSC4xgtsPswth/wYkFkx2I5JLDJViAQ). **Explanation:** ``` •1P42• # Push compressed integer 18208022 b # Convert it to binary 1000101011101010100010110 3ô # Split it in parts of size 3: # [100,"010",101,110,101,"010","001","011",0] s # Take the first codepoint input 61% # Take modulo-61 è # Index it into the binary list (0-based and with wraparound) Š # Triple-swap to take the next two inputs .S # Compare them (-1 if a<b; 0 if a==b; 1 if a>b) è # And use that to index into the triplet (where -1 is the last item) # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (sections *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•1P42•` is `18208022`. [Answer] # [Python 3](https://docs.python.org/3/), ~~99~~ 82 bytes *17 bytes saved thanks to @ovs!* Uses the operator similarities `a<b <=> a≱b`, etc. ``` lambda a,o,b:[a<b,a>b,a<=b,a>=b,a==b,a!=b]['<≱>≰≤≯≥≮= ≠'.find(o)//2] ``` [Try it online!](https://tio.run/##XZDBioMwEIbP9SlmTzEQWszeSuKLWA8JRVboGmk92EfIW/Sg162@Ul7ENUIxk0DCfPw/M/OnfXY/pvleKpBwWW7qV18VKGaYPhdKaKby9QrpC/9I/3xJXRZEODvnzk7ODs6@nR2d/ZPg7Iscq7q5poaeTrxcKnOHHuoGigTWQzIQwAn7gITsAxzyHTLfaTfyDZE6xIjMI1bHcMy6KFYjfMeIOk9YnTd1zxbMEaFThl1kqOQYOP4CtPcQp@I4Blo0ijHFiMxznCojSXlODoqBYaDXjfvjo73VXUqTQ3uvmy7tGRBJGFSpJ0U3py81pXT5Bw "Python 3 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~42~~ ~~41~~ 38 bytes Takes in as input two operands \$ a \$ and \$ b \$, and the operator \$ c \$ in codepoint form. Test cases *nicely borrowed* from @newbie. ``` lambda a,c,b:(cmp(a,b)+63)*c%1895%57&1 ``` [Try it online!](https://tio.run/##dZJLbsIwFEXnWcWTKmq7uBUODVBEshGKKieQgpSfEmeAqi6gu@gApgW21I1Qf/Ixg45y77vXT8eRi73Y5pl7vYMoX@@y9znUIn6cwWQMbPbigTd1Yv/1mvA0XHPgNKLhHEdpgTkNyXAyJg/RQBUH3vSeXat9GuZJBT58oAWaw2REAflKMCkCJVwpfr@@pZzNRiNtDsY8a3M0xtPmRxtmkpMxJjkbM9HmYsz003FEWYvtXgIsEYMFuEgWmLRMCRcCIxhIBBO6WnbTgy27wrGfHttVkq6fWvJky27DuZ9e5HTlODFPqh60Wbpoa3571G8nQS/c/g4dzMFGdHuujsDiOtuyK1xsRKYR8xLEphKwy6D5sUPQ3HMHdPIm@dRXWlWuVbN5BKpyW3p7KjdFwqMNrmklStwUl/WKEFnmFHIKoSynvMC7TFBzqCqSncAIkG4VpUywSgjtLL6lJFaE/ABZltNcPtx/4xg3FIRc/wA "Python 2 – Try It Online") --- The idea is the same as @newbie's, generating pseudorandom numbers until they match the output. The `cmp` function returns `-1`, `0`, or `1` if the left argument is less, equal to, or greater than the right argument, respectively. And also because MathJax looks nice, here is the formula in MathJax: $$ ((((\text{cmp}(a,b) + 63) \* c) \bmod 1895) \bmod 57) \bmod 2 $$ [Answer] # [Python 3](https://docs.python.org/3/), ~~68~~ 59 bytes Takes the unicode code point of the operator as input. ``` lambda a,o,b:[a==b,a>b,a<=b,a>=b,a<=b,a>b,a<b,a!=b][o%61%9] ``` [Try it online!](https://tio.run/##TZIxboMwFIZ3TvE6RE5UBuy2aYowF6EMWC1KpARH4A4oygF6iw6wNsmVehH6bAfbg6Xv//1sfSAfe7WVzdNU8/dpXx3ERwVVLGORFhXnIq5yXJkB7kgDrgcuykIu1nTxVk5dfxBy3wGHE8lICuskBsI1UIRcA0P4@/5B3GySxITBhmcTRhteTPg1gdqdiw1252rD2oSbDa/nKFLtl9r2KFAQChkwggMUI9XAILdAARXsJjPo2iFENzD6dpyvQjvfBngJ0d1w9e0N2zKK6mrfedH7pdk8xuejfG5yD8x/g5MZQkXmvZxB4HUN0Q3cQkVqFGUL6rNTsGvg/mMfwXinEeALgS4GgYZ6pkhTVmIrMd@fQdHp4tjuGrWsyUlPnYHncKqXeFbi2dWZrKZ/ "Python 3 – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 50 bytes ``` {⍎('≥≤><',⍵)[⍵⍳⍨'≮≯≰≱',⍵]} ``` [Try it online! (the test cases)](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR719GuqPOpc@6lxiZ6Ou86h3q2Y0kHjUu/lR7wqgxLpHnesfdW541LkRLBlb@///o76pQJ3qIUWlJRmV6lwQbpqCuqGCjYIRCt9WwRCJb6Rgh8I3VHjUuQBFhxFYBF3NEiwi6LqWYqhZimY30CsYajBF1mMRQbdrA4aajQg16m6JOcWp6MGC6hQbNANs0aywRZO3w@AbYQQjumeXYAkQIwzvo3sN0/sbsIig69qIJUAM1QE "APL (Dyalog Unicode) – Try It Online") Dyalog APL supports many of those operators and a simple "eval()" `⍎` will handle them as given. This answer swaps the last four which are not supported `'≮≯≰≱'` with replacements that are supported, e.g. "not less than" becomes "greater than or equal to", then "eval()"'s the resulting string. Output is 1 for true, 0 for false. (NB. on the score: It's only 26 characters which would be competitive, however because it has `≮≯≰≱` characters in it, it does not fit in a pre-existing 8-bit APL character set so must be scored with the UTF-8 byte count instead of the number of characters). [Answer] # [QuadR](https://github.com/abrudz/QuadRS), 34 bytes ``` ⍎⍵ ≮ ≯ ≰ ≱ ≥ ≤ > < ``` [Try it online!](https://tio.run/##KyxNTCn6//9Rb9@j3q1cjzrXAfF6IN4AxBuBeCkQL@Gy47L5/99QASikYAQA "QuadR – Try It Online") Simply replaces the redundant symbols with their simpler equivalents, and then evaluates as APL. [Answer] ## Dyalog APL, 23 bytes. ``` ⎕(⍎'=>≤≥≤><≠'[9|61|⎕])⎕ ``` With [Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m)'s assistance. [Try it online! (the test cases)](https://tio.run/##XZHBasJAEIbveYq5rUJbTA6FgnopFARBsPYkHoKuGgjZZXdjEbwVbBWUXjwWSlHoqdVX6KPsi7SzSUw2XUj4mcz88@0fn4eXo7kfsskvHr3dtTp6@VpzHP3y7EfykYpKGxiHbtUB0Js3SIswZCMKgYQpFfQCYhlEE0gbIYikov4I2BjQL3/GTECv1bkSceQYr@0OF0G7ojdb0mjq1V6vDvhu1vXqnfRvFtfugvFBtWtIEpwxSCXg3zFIXFAOakqBuFAHj2DfPKSm21CZvbFE2CjpSfkRgPtCSUQgQCq4Uq@Xev1RTVcYV8nDQAGLUPhDKnGiDV3sR96fz2S4XwNvcIagMz9EAHRDgCBSzLzohAozybgZ3O4ebu9Br5/SaXeQjQ5ZNKNCAalnk4wn8aJjTE1WWeZZvsXFFZXKulTyU7K4knRJT8RqOifO@BxNqhrgJsqDZqZcwAiy716ii/q@pIueg1U/5I569WXVbf1d0oXP0aqfTD2Dv/NDSQv484J63t7ITRp5rWkpz7pagbcvYXsWaoFkox5Luug5lbBd8gc) Explained: The `⎕` are prompts for numeric input, it takes the numbers on the outsides, and the codepoint of the comparison operator in the middle. Codepoint modulo `|` 61 then 9 produces indices into the string `''[]` which pick the comparison operator to run. This maps the unsupported ones (≮ ≯ ≰ ≱) to their supported equivalents ("not less than" maps to "greater than or equal to", etc). Code demonstrates an unusual APL feature: `1 (⍎'<') 2` where the string `'<'` evaluates `⍎` to a function which can be called in-place like any other `1 f 2` dyadic APL function call. NB. I'm submitting this as a separate answer both because it's a different approach to my other APL answer, and because it does not contain the unsupported comparison characters in it, which means it fits in a pre-existing 8-bit APL character set, and can be scored as 1-byte-per-character instead of UTF-8 byte count, for a much lower score. [Answer] # [Sledgehammer](https://github.com/tkwa/Sledgehammer), 17 bytes 16.75, to be overly specific ``` ⣕⢌⢲⢼⠴⢺⢟⢼⣑⣮⣊⠞⠀⢄⡕⡝⢥ ``` There's no point in trying to read that, so here's the corresponding Mathematica code with a reasonable explanation: ``` ToExpression@StringReplace[ToString@FullForm@ToExpression@Input[],"ot"->"ot@"] ``` The code evaluates the expression first. Unfortunately, the `≱` operator (and a few other similar ones) is not supported, and is kept verbatim. The code then rewrites the expression into a prefix-ish form (`NotGreaterEqual[1, 1]`), and replaces `ot` with `ot@`, turning `NotGreaterEqual[1, 1]` into `Not@GreaterEqual[1, 1]`, a call of the function `Not` on the result of `GreaterEqual`. Of course, since that was a string replacement, the result is then evaluated once again. [Answer] # [Io](http://iolanguage.org/), 90 bytes Port of the Python answer. ``` method(a,o,b,list(a<b,a>b,a<=b,a>=b,a==b,a!=b)at("<≱>≰≤≯≥≮= ≠"findSeq(o)/2)) ``` [Try it online!](https://tio.run/##hZFNCoMwEIX3PUWaVQKBYpYl4yW67SaiUqHV/uQSuUUXuq16pVzEmkLB0oxZZAh8vDePN1UzlWQP5DhdCnNqcqZFIzJxrh6GaZUJnc5Pgf/4AX5sIePaMKqcHVNnB2dbZ3tnO2dfQJx90rKq80NxYw3fSc6nkpGECEIVnacknFzvVW3O9eYLwIPkF0gP0gD4KPyWfzO5QGFVG0Fhww5XdVj0uQxctYL6CAonHHDViLWusOgKMwMsAGCKdBVI/LLhStvIISTedri3lbaHCAobjpFDLND0Bg "Io – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 80 bytes ``` \d+ $* ≠ <> ≤|≯ <= ≥|≮ => ≰ > ≱ < ^(1+)(<.?1\1|.?>(?!\1)|<?=>?\1$) ``` [Try it online!](https://tio.run/##PU47CsMwDN11ChVScBoIyLNsX8SUFtqhS4fSMRfILTokaz5XykVcR3a8vKf3kN7T5/l9ve/hrG4IwT8aqC6w9T9gG2notn4GNnEc4ziB2d0FdlyB4aqoqRW3jjx1rbPKnTzVHTtjnaeqDoGQUQOhQQKNNiJhjI@eFk56KJz8MetRrmJx1gfPhdP@kvUqXSxXLJ6RDSOzzajzDyl7KF06d6TMo2MpnPy1dNEf "Retina 0.8.2 – Try It Online") Link includes test suite. Takes input as `acb`, but the test suite deletes spaces to make the input more readable. Explanation: ``` \d+ $* ``` Convert to unary. ``` ≠ <> ≤|≯ <= ≥|≮ => ≰ > ≱ < ``` Replace the Unicode operators with ASCII-based logical operators. The `=>` is reversed to make the final condition golfier. ``` ^(1+)(<.?1\1|.?>(?!\1)|<?=>?\1$) ``` Match the first number, then check whether one of the relations can be fulfilled. * If the character after the first number is a `<`, then after an optional `>` or `=`, then to fulfil this relation the second number needs to equal 1 or more than the first number. * If after an optional `<` or `=`, there is a `>` before the second number, then to fulfil this relation the second number must not be at least equal to the first number. * If after an optional `<` there is an `=` before an optional `>`, then to fulfil this relation the second number must be equal to the first number. [Answer] # [C (gcc)](https://gcc.gnu.org/), 46 bytes ``` f(a,c,b){a="14353426"[c%61%9]>>(a>b?2:b>a)&1;} ``` [Try it online!](https://tio.run/##lZNRa4MwEMff@ymC4Iglpd41id3K3AfZ9hAdboVVSuceRulnd1rjlnvqBUQTyI//XbxfvXqv675vpFO1qrKze0xAb8xGo02e69RCev9altKV1RM@VKXL7mB36Q9u38rsvFgvRXf67j5@xHK9EMfTvu0amaRvYnpW5fB@aRMlQAmbK4FKNHJeZ9nuJgPXz8SM61vMEGDRM/OakbPd5kF1fsfImk7OaX7Hy9P/nfkdm0PCIY8zJM/w7jLgMI4DHXLA7g/IvURwpD8wMRwSjvffwZL@LDuvIHmFzxtEatznF9cjCDxiORFMqWXO6OgbBu5x7uXPV2T6CoGvwPd1PIcBg2zHgTjOdIDMcoSrZLZyw60TiOOg2TNJXI1wwBJ3bAyHhGPWWZA6ixh3gLhz5S59/ws "C (gcc) – Try It Online") Port of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [JavaScript answer](https://codegolf.stackexchange.com/a/203591/9481). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `D`, 16 bytes ``` 4ɾ8813+C`≥≤><`ĿĖ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=D&code=4%C9%BE8813%2BC%60%E2%89%A5%E2%89%A4%3E%3C%60%C4%BF%C4%96&inputs=123%2045%E2%89%B1&header=&footer=) Luckily, Vyxal supports all but the last four characters as operations. ``` Ė # Evaluate... Ŀ # The input, with characters in... C # The charcodes of 4ɾ # 1...4 8813+ # + 8813 Ŀ # Replaced... `≥≤><` # with the cooresponding character ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes ``` Nθ≔I§”←⧴LH⎚G₂ⅉυ”℅SηNζ⁼§⟦‹θζ⁼θζ›θζ⟧η÷η³ ``` [Try it online!](https://tio.run/##TY5NCsIwFIT3nuLR1QtE6I9ddVVUpCAquBQXsQ1tIEabpEV6A2/h2bxITKWIy49hvpmyYbq8Melcoe6d3XXXC9fYkmyWGyNqhUtmLOa2UBV/YAAQhwDJIgWAME6TCAIKe10JxSR@DUerhaqREEKh8Zp/7eD54GOL67Zj0vy8py03BlsKg29N2UQbzZkdL414Hp0UCmVXohcVx4ZC4qcy5yJ4P18Qu3kvPw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as `a c b` and outputs a Charcoal boolean, i.e. `-` for true, nothing for false. Explanation: ``` Nθ ``` Input `a`. ``` ≔I§”←⧴LH⎚G₂ⅉυ”℅Sη ``` Input `c` and cyclically look up its ordinal in the compressed string `__20__345___02531_` (the `_`s are arbitrary; the linked code uses spaces) and save its value. ``` Nζ ``` Input `b`. ``` ⁼§⟦‹θζ⁼θζ›θζ⟧η÷η³ ``` Make a list of the comparisons `a<b`, `a=b`, `a>b`, cyclically index using the `c` value, and negate the result if the `c` value is less than `3`. ]
[Question] [ ["First they came..."](https://en.wikipedia.org/wiki/First_they_came_...) is a poem by [Martin Niemöller](https://en.wikipedia.org/wiki/Martin_Niem%C3%B6ller): ``` First they came for the Socialists, and I did not speak out- Because I was not a Socialist. Then they came for the Trade Unionists, and I did not speak out- Because I was not a Trade Unionist. Then they came for the Jews, and I did not speak out- Because I was not a Jew. Then they came for me-and there was no one left to speak for me. ``` Your task is to output the above. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! # Rules * You may include extra whitespace that does not affect appearance. A single trailing newline is allowed. * Otherwise, the output must match exactly, including the location of newlines. * As per meta standards, you may output a list of strings. However, you must include the empty lines. Note that I personally believe this is not a dupe because of how the poem is laid out - it needs some creativity to golf. Meta discussion about whether this is a dupe or not can be found [here](https://codegolf.meta.stackexchange.com/q/13767/58826). [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~103~~ ~~102~~ 101 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` →∑‘¾ο╤Ε9‘}ψ⁴‘¹"4¡‘Q°‘:¹¹I{ū_:¹"Eā/}l6⁸SÆ□⁴↔b⅜╬I℮;YΥηκ*█⅞F^Κ⅜⁸{x⅔⁵⅟╚?Z‘O}"Ι╚╬√⅔δηvΧχ⁷⁾Η<υL┼!Ο'μΠ⁵╝⁷‘⁾ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTIwJXUyMTkyJXUyMjExJXUyMDE4JUJFJXUwM0JGJXUyNTY0JXUwMzk1OSV1MjAxOCU3RCV1MDNDOCV1MjA3NCV1MjAxOCVCOSUyMjQlQTEldTIwMThRJUIwJXUyMDE4JTNBJUI5JUI5SSU3QiV1MDE2Ql8lM0ElQjklMjJFJXUwMTAxLyU3RGw2JXUyMDc4UyVDNiV1MjVBMSV1MjA3NCV1MjE5NGIldTIxNUMldTI1NkNJJXUyMTJFJTNCWSV1MDNBNSV1MDNCNyV1MDNCQSoldTI1ODgldTIxNUVGJTVFJXUwMzlBJXUyMTVDJXUyMDc4JTdCeCV1MjE1NCV1MjA3NSV1MjE1RiV1MjU1QSUzRloldTIwMThPJTdEJTIyJXUwMzk5JXUyNTVBJXUyNTZDJXUyMjFBJXUyMTU0JXUwM0I0JXUwM0I3diV1MDNBNyV1MDNDNyV1MjA3NyV1MjA3RSV1MDM5NyUzQyV1MDNDNUwldTI1M0MlMjEldTAzOUYlMjcldTAzQkMldTAzQTAldTIwNzUldTI1NUQldTIwNzcldTIwMTgldTIwN0U_) Explanation (here I replaced the compressed strings with `..` to save space): ``` ..‘.‘..‘ push "socialist", "trade unionist" and "jew" ¹ wrap in an array: ["socialist", "trade unionist", "jew"] "..‘..‘ push "first" and "then" : duplicate the then ¹ wrap in an array: ["first","then","then"] ¹ wrap those two in an array: [["socialist", "trade unionist", "jew"], ["first","then","then"]] I rotate clockwise: [[first,socialist], [then,trade unionist], [then,jew]] { } for each do, pushing the array ū uppercase the 1st letter of each word in the array - ["First", "Socialist"] _ splat the contents on the stack "First", "Socialist" : duplicate the 2nd one "First", "Socialist", "Socialist" ¹ wrap in an array ["First", "Socialist", "Socialist"] "..‘ push "ŗ they came for the ŗs, and I did not speak out-\nBecause I was not a ŗ." with ŗ replaced with its appropriate item in the array O output that "..‘ push "then they came for me-and there was no one left to speak for me." ⁾ uppercase the 1st letter of it implicitly output it in a new line ``` [Answer] # [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), 229 bytes Kind of boring, still doable on a C64 with a *somewhat* decent amount of bytes :) ``` 00 C0 A9 17 8D 18 D0 A2 2C 86 FE A6 FE A0 C0 BD B6 C0 20 1E AB C6 FE 10 F2 60 C6 49 52 53 54 20 00 D4 48 45 4E 20 00 54 48 45 20 00 54 48 45 59 20 43 41 4D 45 20 00 46 4F 52 20 00 53 50 45 41 4B 20 00 41 4E 44 20 C9 20 44 49 44 20 4E 4F 54 20 00 4F 55 54 2D 0D 00 C2 45 43 41 55 53 45 20 C9 20 57 41 53 20 4E 4F 54 20 41 20 00 4D 45 2D 41 4E 44 20 54 48 45 52 45 20 57 41 53 20 4E 4F 20 4F 4E 45 20 4C 45 46 54 20 54 4F 20 00 4D 45 2E 00 2E 0D 00 53 2C 20 00 D3 4F 43 49 41 4C 49 53 54 00 D4 52 41 44 45 20 D5 4E 49 4F 4E 49 53 54 00 CA 45 57 00 0D 00 8C 35 3A 6B 2A 1F B4 90 B0 56 50 3A 41 93 B0 25 35 2A 1F B4 90 A1 56 50 3A 41 93 A1 25 35 2A 1F B4 90 97 56 50 3A 41 93 97 25 35 2A 18 ``` ### [Online demo](https://vice.janicek.co/c64/#%7B"controlPort2":"joystick","primaryControlPort":2,"keys":%7B"SPACE":"","RETURN":"","F1":"","F3":"","F5":"","F7":""%7D,"files":%7B"came.prg":"data:;base64,AMCpF40Y0KIshv6m/qDAvbbAIB6rxv4Q8mDGSVJTVCAA1EhFTiAAVEhFIABUSEVZIENBTUUgAEZPUiAAU1BFQUsgAEFORCDJIERJRCBOT1QgAE9VVC0NAMJFQ0FVU0UgySBXQVMgTk9UIEEgAE1FLUFORCBUSEVSRSBXQVMgTk8gT05FIExFRlQgVE8gAE1FLgAuDQBTLCAA009DSUFMSVNUANRSQURFINVOSU9OSVNUAMpFVwANAIw1OmsqH7SQsFZQOkGTsCU1Kh+0kKFWUDpBk6ElNSoftJCXVlA6QZOXJTUqGA=="%7D,"vice":%7B"-autostart":"came.prg"%7D%7D) Usage: `SYS49152` **Explanation:** As this contains mostly data, instead of a meaningless disassembly listing, here's the [`ca65`](http://cc65.github.io/cc65/)-style assembly source that creates this machine code: ``` .segment "LDADDR" .word $c000 ; load address .code lda #$17 ; upper/lower mode sta $d018 ; store in VIC register ldx #revpoemsize ; initialize ... stx $fe ; ... counter loop: ldx $fe ; load current position ldy #$c0 ; highbyte of strings always same lda revpoem,x ; load lowbyte from table jsr $ab1e ; output 0-terminated string dec $fe ; decrement position bpl loop ; >=0 ? -> repeat rts ; done first: .byte "First ", 0 then: .byte "Then ", 0 the: .byte "the ", 0 came: .byte "they came ", 0 for: .byte "for ", 0 speak: .byte "speak ", 0 didnot: .byte "and I did not ", 0 out: .byte "out-", $d, 0 wasnot: .byte "Because I was not a ", 0 noone: .byte "me-and there was no one left to ", 0 me: .byte "me.", 0 period: .byte ".", $d, 0 comma: .byte "s, ", 0 socialist: .byte "Socialist", 0 unionist: .byte "Trade Unionist", 0 jew: .byte "Jew", 0 p: .byte $d, 0 revpoem: .byte <me, <for, <speak, <noone, <came, <then, <p .byte <period, <jew, <wasnot, <out, <speak, <didnot .byte <comma, <jew, <the, <for, <came, <then, <p, <period .byte <unionist, <wasnot, <out, <speak, <didnot, <comma .byte <unionist, <the, <for, <came, <then, <p, <period .byte <socialist, <wasnot, <out, <speak, <didnot, <comma .byte <socialist, <the, <for, <came, <first revpoemsize = * - revpoem - 1 ``` [Answer] # [Python 3](https://docs.python.org/3/), 209 bytes ``` t='they came for ' s='First ' for i in'Socialist','Trade Unionist','Jew':s+=t+f'the {i}s, and I did not speak out-\nBecause I was not a {i}.\n\nThen ' print(s+t+'me-and there was no one left to speak for me.') ``` [Try it online!](https://tio.run/##LY6xDoJAEER7v2K71SA0diY0Fibaih3NBZawEfbI7RJCjN@OnNJNZjJvZpit9XJaFsvRWpqhcj1B4wPgTnO8clBbZTQYWPDhK3Ydq@ERi@Bqgqewl79xpwnPmuSWNBEGb/7oEZzUcIOaaxBvoAO5F/jR0lIuVLlRaU0np7/UxU5WSilFS7IOD4HF9ppYgj2lEbWCA20F8ELQUWNgfiPHpz1leFiWLw "Python 3 – Try It Online") -5 thanks to [Felipe Nardi Batista](https://codegolf.stackexchange.com/users/66418/felipe-nardi-batista). [Answer] # [Perl 6](https://perl6.org), 193 bytes ``` say join ' they came for ','First',«Socialist "Trade Unionist" Jew».map({"the {$_}s, but I did not speak out- because I was not a $_. Then"}),'me- and there was no one left to speak for me.' ``` [Try it online!](https://tio.run/##LY5BCoMwFAX3nuIhQlqILnuEQrutXctXv5hWE0kiIuKJeoTuvJjV4vIxj2E6ts1lXR2NeBmlIeBrHlFQy6iMhZDiqqzzQi6fhykUNcp5hKmlkvHUyuhth7jzsHyTlrrTFG4CTFE2O4m897ihVCW08XAd0xum93GQc0G94w0O5P6QEGVJEKQ163A@S9FyDNLlnmP5eMFoRsOVhzeHbW9sORHr@gM "Perl 6 – Try It Online") [Answer] ## [Perl 5](https://www.perl.org/), 185 bytes ``` print join" they came for ",First,(map"the ${_}s, and I did not speak out- Because I was not a $_. Then",Socialist,"Trade Unionist",Jew),"me-and there was no one left to speak for me." ``` [Try it online!](https://tio.run/##LY69CsIwGEX3PsUldFBIu/kCDoKu1rl8NF9ptPkhSSkiPntMpePlwDnXc5hPOfugbcLTaSuQJn5jIMMYXYCQFx1ikgdDXhSE@tN/owRZhSuUVrAuIXqmF9ySmurMAy2RC1wp/iGh7tuq6ia2Qt7doGnWxSi6QIrxsNrZsoW88XqUwnCzuUsq8K6As4yZx4Tk9tR2zXArcv4B "Perl 5 – Try It Online") Thanks to @[Massa](https://codegolf.stackexchange.com/users/52273/massa) for -3 bytes! [Answer] # C, 248 bytes *Thanks to @Zacharý for saving 9 bytes.* ``` p(x,y){printf("%s they came for the %ss, and I did not speak out-\nBecause I was not a %s.\n\n",x,y,y);}f(){p("First","Socialist");p("Then","Trade Unionist");p("Then","Jew");puts("Then they came for me-and there was no one left to speak for me.");} ``` [Try it online!](https://tio.run/##XY/BDoIwDIbvPEWzxGQkwAtw82CiV/XGpRlFFqUj24gSw7NjEU70tP5/@/ebyR/GzHOvP9mYfntvOTZaHQLElkYw2BE0zi8dHELIALmGM9S2BnYRQk/4BDfEvOIjGRwCifvG8HdRVoqKK1aZpEt@OTVajmh1sj5ElamrMxZfVt5pKfKtJZlVN481wZ2t4711offSDzGs0g6zo3wBFNHThgGOCV7URIhu410nCwmaZvkvdGhZp8k3ASkhLJNp/gE) [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 248 246 242 bytes ``` a=>{string b=@", and I did not speak out- Because I was not a ",c=" they came for ",d="Socialist",e="Trade Unionist";return$@"First{c+d}s{b+d}. Then{c+e}s{b+e}. Then{c}the Jews{b}Jew. Then{c}me-and there was no one left to speak for me.";} ``` Actual newlines saved me a few bytes. [Try it online!](https://tio.run/##TZHBasMwDIbvfgphdmgh6QtkKWWDwsYGg3bsMHZQHbU1S@xhKSsl5NkzOylr/4MEn2T/smw4Nz7Q0LJ1B9icWagplIIoUyMzvAV/CNiMpBtjEguKNfDrbQWvaN2MJcQLPr8Aw4Hn/33XE0nr1pn7qTODKS9hHyGUoAYsl90EYVeudAboKniCKlo4L8A/hN/gW8nVAxlsmWLxhDwWEXRmSg1ypDMYbAj2PkRWlXrjjcXasuiMSr0NWBG8O@tdQkUgaYO7W@m1DSyd6buq526X0kKp7ZFcYjQxumHRCZ7plHhMVx6t83Hy2BDoMiB4R1DTXkD85SFpvoYWuuiH4mZFCh69Y1/T4iNYoRfraJY2NNN6Pr98TFKvpqiGPw) Saved 2 bytes thanks to *Business Cat* [Answer] # [Python 3](https://docs.python.org/3/), 203 bytes ``` print('First',*[f'the {s}s, and I did not speak out-\nBecause I was not a {s}.\n\nThen'for s in['Socialist','Trade Unionist','Jew']],'me-and there was no one left to speak for me.',sep=' they came for ') ``` [Try it online!](https://tio.run/##LY0xD4IwEEb/ym2nBlicXRxMdBUnYGjoERrhrmlLCDH@9kqR9d5979kl9MLnGK0zHA54M84HzE5Vh6En@Pivz0Cxhjtoo4ElgLek3iBTyGu@UqsmTyudld@oSpui5prLnhg7ceDBcIVPaY0aTLJj6ZQmeLER/h8eNGPTZDhSnmJr2tGuBGGCgboAQfZ2ko5UYObJXjB9L9CqkTaAxxh/ "Python 3 – Try It Online") [Answer] # [Befunge-93](https://github.com/catseye/Befunge-93), 348 bytes ``` ".em rof kaeps ot tfel eno on saw ereht dna-em rof emac yeht nehT"52*:v v"d not speak out-"*25"Because I was not a "< p5-2*89p1-2*89"vvJew."< > "id I dna ">",sweJ>v"67+2p66+5p v ^p2-2*89"vTrade Unionist."< >"tsriF">:#,v>",stsinoinU edarTv"67+3pv ^ p3+66p40"^_Socialist."< >"nehT"52*: v>",stsilaicoS@"67+3p >" eht rof emac yeht " ``` [Try it online!](https://tio.run/##VZBPT4NAEMXv/RQv4w1Ko1RQm4YYDyb2WnqtWWGwm9LdDbss8dMjIDbpHGaSyXu/@fPFVau@ue9pxRc0usJZsLHQDq7iGqw0tIIVHbjhk0OpRDQr@SIK/IxNxaeckjjY@IWnEmpwW8PiDN26iII4oTcuRGsZH@iEnQQCtAVgkigOnl/Mw1TI@x13K9ouMpAsB/kwD5TR0na8yzylT2Fs0jRMDMbwUz6aeHbnjSgZByW1ktZNHHK2ke@Ube6WfuQ4K5WW6gAuRZNPxLWZOeM@6zBNzeM9HT/3upCivnKuR@KfUwtZ6P3rH2IiZITxH7ffob7/BQ "Befunge-93 – Try It Online") [Answer] # Befunge, ~~293~~ ~~274~~ 270 bytes ``` 62574732594932584832001v_@#:\0\!< 0-*84g+3/"P"\%"P"::+p00<_|#:-1g0 84!-"*":g+3/"P"\%"P"::+1\<+1_$#:^#-2\,-** &First0 they came for %the Qs, and I did not speak out-*Because I was not a (.** ThenOme-and there was no one left to speak for me.*$Jew*Socialist/Trade Unionist ``` [Try it online!](http://befunge.tryitonline.net/#code=NjI1NzQ3MzI1OTQ5MzI1ODQ4MzIwMDF2X0AjOlwwXCE8CjAtKjg0ZyszLyJQIlwlIlAiOjorcDAwPF98IzotMWcwCjg0IS0iKiI6ZyszLyJQIlwlIlAiOjorMVw8KzFfJCM6XiMtMlwsLSoqCiZGaXJzdDAgdGhleSBjYW1lIGZvciAldGhlIFFzLCBhbmQgSSBkaWQgbm90IHNwZWFrIG91dC0qQmVjYXVzZSBJIHdhcyBub3QgYSAoLioqClRoZW5PbWUtYW5kIHRoZXJlIHdhcyBubyBvbmUgbGVmdCB0byBzcGVhayBmb3IgbWUuKiRKZXcqU29jaWFsaXN0L1RyYWRlIFVuaW9uaXN0&input=) This is a different approach to the existing Befunge solution. It uses a kind of linked list to store a dictionary of the common phrases, and then just has a simple list of values on the stack representing the order in which the phrases should be output. [Answer] # [Retina](https://github.com/m-ender/retina), 176 bytes ``` Socialists, Trade Unionists, Jews,1me-and there was no one left to2for me. ( .+?)s, 1the$& and I did not2out-¶Because I was not a$1.¶¶Then ^ First 1 they came for 2 speak ``` [Try it online!](https://tio.run/##JY3BCoJAFEX37yvuQqJIBf2BoEVQ22wbPPSJQzoTM0@kH/MD/LFJcXu451wvaizHSHi62nBvgoYUledG8LLG2R08ZAppMUjGtoF24gUTB1gHZwW9tAp1Zes8BsnpiPx8OYWUinWaHLBJdzSmWQUt3ajZMl@l5jHIyveQgpMiX@Zlrjqx9Kab8UGpoO3uh5oHwdankhC@wh/E@Ac "Retina – Try It Online") Explanation: The `1` and `2` are just repeated strings which are long enough to be worth deduplicating. The `First` is added later to make it easier to select the placeholder for the repetitive portion, "they came for the [group]s, and I did not speak out-Because I was not a [group]. Then", which is expanded by the second stage. [Answer] # JavaScript (ES6), ~~231~~ ~~227~~ ~~223~~ 221 bytes ``` _=>`First${t=" they came for "}the Socialist${a=`s, and I did not speak out- Because I was not a `}Socialist${t=`. Then`+t}the ${(u="Trade Unionist")+a+u+t}the Jew${a}Jew${t}me-and there was no one left to speak for me.` ``` --- ## Try it ``` o.innerText=( _=>`First${t=" they came for "}the Socialist${a=`s, and I did not speak out- Because I was not a `}Socialist${t=`. Then`+t}the ${(u="Trade Unionist")+a+u+t}the Jew${a}Jew${t}me-and there was no one left to speak for me.` )() ``` ``` <pre id=o> ``` [Answer] # Java 8, ~~250~~ 236 bytes ``` o->{String t=" they came for ",r="First";for(String s:"Socialist,Trade Unionist,Jew".split(","))r+=t+"the "+s+"s, and I did not speak out-\nBecause I was not a "+s+".\n\nThen";return r+t+"me-and there was no one left to speak for me.";} ``` [Try it here.](https://tio.run/##LZC9bsMwDIT3PsVBkw3/PEANd@hQoAWaDkmnpoMiM40SmzIkOkEQ5NlduRUgDccjD@R31GdduZH42J1m0@sQ8K4t3x4Ay0J@rw1htUhgLd7yD0z2sTuSEbi8ifV7/PEF0WINVmC0mF31dEvt0irIga4weiDsnYcqfaterA@imqiz1Bge1doZq3sbpNx43RE@2Tpe5BtdVB3G3kqmSpXnvmilUDEWqgiFCiU0d3hFZzuwE4SR9AlukmrLz2T0FCi6Fx3@XP0/VW95y5sDsWo8yeQZvoipA1VLWAz3lEbgmNDTXiAuZS@HDFSr5j43/wTGaddHAgnE2cVVhogynff1DZ0njtcgNNRxu3qMlmRcm4ynvs8T0Pv8Cw) [Answer] # JavaScript (ES6), ~~210~~ ~~207~~ ~~206~~ 203 bytes A different approach to [my other solution](https://codegolf.stackexchange.com/a/139919/58974) so figured it was worth editing it out to its own answer now that the challenge has been reopened. ``` _=>`First${["Socialist","Trade Unionist","Jew"].map(x=>t+`the ${x}s, and I did not speak out- Because I was not a ${x}. Then`,t=` they came for `).join``+t}me-and there was no one left to speak for me.` ``` --- ## Try it ``` o.innerText=( _=>`First${["Socialist","Trade Unionist","Jew"].map(x=>t+`the ${x}s, and I did not speak out- Because I was not a ${x}. Then`,t=` they came for `).join``+t}me-and there was no one left to speak for me.` )() ``` ``` <pre id=o> ``` [Answer] # [Gaia](https://github.com/splcurran/Gaia), ~~179~~ 175 bytes ``` ⇓“the ”3ṁ“s, and I did not speak out-¶Because I was not a ”2ṃ“.¶¶Then “ they came for First”“Socialist“Trade Unionist“Jew”↓¦⇑“me-and there was no one left to speak for me.”]$ ``` [Try it online!](https://tio.run/##LU47DoJAEO05xRSWQqE3sDDRViwtJjDIRtg17BJihzGR2tBi6xFIaLkJXARnlfL93xkFTtNY1WPZmJhgLN/robsz0ktAGcIOQhGCVAb0lfACKjdu324owFwTqwXqn4o2uhq6B0e9vu1bPybpMACuvUGAKUGkMnC2ItOGvSwdVCAwERY2foYhwVEKJf/Engrretb9Z6xeTKTk2kNcl9E8C0oSJBQZMGr@ZzdS8jh6WkzTFw "Gaia – Try It Online") ### Explanation 3 functions are defined here (1 per line). The bottom one is called first. `¶` gets replaced by newlines. ``` ⇓“the ”3ṁ“...”2ṃ“.¶¶Then First helper function. Argument: s ⇓ Push "Then they came for " “the ” Push "the " 3ṁ Bring s to the top “...” Push "s, and I did not speak out-¶Because I was not a " 2ṃ Push a copy of s “.¶¶Then Push ".¶¶Then" “ they came for Helper function. No arguments. “ they came for Push " they came for " First”“..“..“..”↓¦⇑“...”]$ Main function. First” Push "First" “..“..“..” Push the list ["Socialist" "Trade Unionist" "Jew"] ↓¦ Call the first helper function on each. ⇑ Push "Then they came for " “...” Push "me-and there was no one left to speak for me." ]$ Wrap the stack in a list and join with no separator. ``` [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), ~~149~~ ~~132~~ 129 bytes ``` 00000000: 9d4d b515 0241 14cc af8a c991 1e70 0991 .M...A.......p.. 00000010: 02fe bbfd e7b7 cb1a 523d ee0e d9f8 7453 ........R=....tS 00000020: 631d 5cc2 2b84 5432 2265 760c 6315 a654 c.\.+.T2"ev.c..T 00000030: a4d6 d92a 480a 0c20 5201 a91c ec8c 2987 ...*H.. R.....). 00000040: f2ae 1634 3924 6f79 6b2e c8ee 4dba 14eb ...49$oyk...M... 00000050: 4130 4958 3ed9 9e18 128c a94c 95fc e3e0 A0IX>......L.... 00000060: b6fd fa65 c88b 1fa7 7795 e77b 25d7 488a ...e....w..{%.H. 00000070: 9d68 f898 8792 8c82 2307 a78e bb87 647d .h......#.....d} 00000080: 03 . ``` [Try it online!](https://tio.run/##jZE7i5YxEIV7f8XBS6HCkMskmQgK262gzbrFFja5THZBRQtXEfG3f877fu9i6xRhQsgzZ87p971/1tv7L6eTO@oV6uSJnnyCC@zheQy0JQ2jVrtqcXBbB3pPRBd0rm9Ej84EbwwXlqL3NaGlF4zuG1KIdlWnmHUJCqdojKOuXm/n9w8HIxgjRz@RxggIXRiJo3UhJ5Tsxvaa0HJiYNBHeknX4bH@oEF0fTCiMRrPbONCA4trcCM40@E8WvUDOmQgVCm7jheXRLja1Tx/2IWNsUJT@BwZsQZGXqUi96AYogqevZlH2ncG16dff32yZrPmYCRjsI8OXJMg6qyo6gU@2PRWeaCmZWKiOuDCvb15c7bkHf1jZGP0bHYuW9kGS4dfraCUmszi0hHSLLakxbTp0O3vT6Lfz@jygVH2bLNgSRVIqQEyxDyNrqAV2QIzKzKXaYy7s4gn@zn/HAzZsrXY/qvodPoL "Bubblegum – Try It Online") Boring Bubblegum answer. Already beaten by SOGL, so that's good. Credit for -17 bytes goes to [Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings) -3 bytes by [ovs](https://codegolf.stackexchange.com/users/64121/ovs) [Answer] # SQL 269 bytes ``` declare @ char(18)='They came for the ',@a char(49)='s, and I did not speak out- Because I was not a ' print'First '+@+'Socialist'+@a+'Socialist. '+@+'Trade Unionist'+@a+'Trade Unionist. '+@+'Jew'+@a+'Jew. '+@+' me-and there was no one left to speak for me.' ``` [Answer] # PowerShell, 211 202 198 bytes -13 bytes thanks to @Veskah ``` $a,$b='First',' they came for' 'Socialist','Trade Unionist','Jew'|%{"$a$b the $_`s, and I did not speak out- Because I was not a $_. ";$a='Then'} "$a$b me-and there was no one left to speak for me." ``` [Try it online!](https://tio.run/##LY7LDoIwFET3/YobUtMN8AOGjQsT3YprvdBLaCwtaUuIUb@9lsd2zszJjHYm53vSOkaOOW8qcVbOB5ELCD29ocWBoLNOMHGzrUKtVlg7lAR3o6zZgivN4nv4ZBx5syyBP54@BzQSLiCVBGMD@JHwBXYKBTtRi5OnBGf0K8Q0KVl25FiJuicjfmyzDVQsmiR1tLfBGgJNXYBgd2v6mJplFuMf "PowerShell – Try It Online") I'm sure this can be golfed down a little bit. [Answer] # [Proton](https://github.com/alexander-liao/proton), 219 bytes ``` t='they came for'for i:'Socialist','Trade Unionist','Jew'print(i[0]=='S'? 'First':'Then',t,'the',i+'s, and I did not speak out- Because I was not a',i+'. ')print('Then',t,'me-and there was no one left to speak for me.') ``` [Try it online!](https://tio.run/##RY89C4NADIZ3f0W2VHpKZ0EKHQrtqp1Kh0MjhtaL3EWkv976BR2yvE/yvKT3ouKmSXPUlr5Q2Y6gEY/zAGdYSMX2w0HRYOltTfBwLG4L7jRi79npgZ@nV55jgWfAK/uZZli25NCoWcRo@IjBgHU13KDmGpwohJ7sG2TQJLpQZYdAMxxtWKFdb9II463i7@soWTyz1tO@DuIIPtQoqOza5YGOUoyn6Qc "Proton – Try It Online") [Answer] ## Python 2, 246 bytes First time I tried compressing the string an returning it. Aparently it takes more bytes than other approaches. Is there anything left to golf? ``` import zlib,base64 print zlib.decompress(base64.b64decode('eJyd0DEOwjAMBdA9p/gHoD0EAxJdgQNYiatGtDaKU1XcvikUdSkDjLb/f4NPMVlG7vgJTwOj1bRMuKiP1EfLdgBJwBkhBohm2IPpDh1z5Y7saTQux4nsdaStWDt37Vh27JtElT/oT++73PD0K1oq+97A1QKVZeI1DxVGz215mK7uO1nPf1Zu5g==')) ``` [Try it online!](https://tio.run/##JcnNboIwAADg@55iNzUsQhFsPHiAlDBBBCay6Q1s@Yd2UAR5eZbF6/exJ89oI89zXjPa8vepyuOPOOrIVnljbd68ZI3JndasJV23fOU63ir/iMlyQawnlpDhDoXm6FjbMTH9pEgytNHCqX@65hE3OYrsC/i5P/Lygs8lKo6xmCgnzwkrEz5SKxjcAsRfTm/nHjCSI051a9DLTKdZLR88hjIwqVfYRYHfj0rT4ejMvxHfwDCTocWNKhBpIAhw4yHJBvRX2EEN@HZ4IweAxtCcZKDWNuxd0HgJuPVqut8vVqt5/gM) [Answer] # [Röda](https://github.com/fergusq/roda), 204 bytes ``` {t="Then"c=" they came for";["First","Socialist",t,"Trade Unionist",t,"Jew"]|[`$_$c the ${_}s, and I did not speak out- Because I was not a $_2. `];[`$t$c me-and there was no one left to speak for me.`]} ``` [Try it online!](https://tio.run/##Nc6xDoJADAbgnadoGkZwcCUsDia6qpMh0NyVcFHuzF0JMciz42Fwa/r//VLvNC09GQvTMkmJ144tqhJBOn6Dop6hdR6LOx6ND4IZXpwy9DTrLBlePWmGmzXO/ldnHrH63Ju0TtXKQDrVc8iArIYTaKPBOoHwYnqAGyRPDqxoCBzDkcIvJEjr/S5JmqqIjkSn53y9j5znrQbOMjy5FRC3cfHV2Nw11bzMyxc "Röda – Try It Online") [Answer] # PHP, 194 bytes ``` First<?=$t=" they came for ";foreach([Socialist,"Trade Unionist",Jew]as$s)echo"the ${s}s, and I did not speak out- Because I was not a $s. Then$t"?>me-and there was no one left to speak for me. ``` [Try it online](http://sandbox.onlinephpfunctions.com/code/cd19f6d7c9331a710412f62c0f13803f4d78e3b6). [Answer] # [C (gcc)](https://gcc.gnu.org/), 244 bytes ``` f(c){for(c=0;c<3;printf("%s they came for the %ss, and I did not speak out-\nBecause I was not a %2$s.\n\n",c++?"Then":"First",c^2?c?"Trade Unionist":"Socialist":"Jew"));puts("Then they came for me-and there was no one left to speak for me.");} ``` [Try it online!](https://tio.run/##XY9Pa8MwDMXv@RTCLGDTppT2Vm8Udhhs1223MDCKvJo1crAcyij97Kn751SdpN97Qk/Y/CJOk9dojj4mjS9Li89rO6TA2WtVC@Qd/QO6nqAYLhPUInNw3ME7dKEDjhlkIPcHccxNy6@EbhQq6sHJVXVQr55k0XLLao6z2VZ97YjVRr2FJLmgn9UWC0yuI/jmEDkUvFGfEYPb3/oPOihj7DBm0df1h2A9NZdIBSa6H4bIBHvyGXK8J7w5F8rY01Q@hN4F1qY6VlDKa2Or03QG "C (gcc) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 208 bytes ``` print(' they came for '.join(["First"]+[f"the {i}s, and I did not speak out-\nBecause I was not a {i}.\n\nThen"for i in['Socialist','Trade Unionist','Jew']]+['me-and there was no one left to speak for me.'])) ``` [Try it online!](https://tio.run/##LY09DoJAEEavMqFZiELjDSxMtBUroNjAEEZhhuwOIcR49hWU9vt5b1y0Ez6FMDpijQ1ohwvUdkBoxYHJnkIcF9GFnNeoOhRttC7gTR9/BMsNXKGhBlgU/Ij2BTJpWvIZazt5XNvZ@l9rt09Wcsl5hxxtcALiwtylJtuTV3M0ubMNwoNJ@B/ccDbVajUDppttdTvcmSCM0GOroLLLN@qAmamSJIQv "Python 3 – Try It Online") -1 thanks to @Step Hen [Answer] # Clojure, 285 bytes ``` (fn[](doseq[i(range 4):let[c["Socialist""Trade Unionist""Jew"""]f #(if(< i 3)% %2)]](println(if(= i 0)"First""Then")"they came for"(str(f(str"the "(c i)"s, ")"me-")(f"and I did not speak out-\n""and there was no one left to speak for me.")(f(str"Because I was not a "(c i)".\n")""))))) ``` This was a fun little challenge. I ended up almost entirely rewriting most of it a couple of times because I realized I was doing something overly roundabout. There are still a couple areas that could probably be touched up, but I'm pretty happy with how it turned out, even if I'm only "compressing" the original by 54 bytes. [repl.io](https://repl.it/KWof/0) See the pre-golfed code for an explanation: ``` (defn ftc [] ; Loop over the lines numbers for reference (doseq [i (range 4) :let [; Added a dummy last "class" since "me-" wasn't necessary, ; and only having 3 elements was causing OOB errors. classes ["Socialist" "Trade Unionist" "Jew" ""] ; A helper function that executes either its first or second argument ; depending on if the current line is one of the first 3 lines. if-first-three-lines #(if (< i 3) % %2)]] ; An implicit space is inserted between each of the args to println (println ; Decide on the opener (if (= i 0) "First" "Then") "they came for" ; Start string concatenation because the implicit space ; begins complicating things. (str ; Decide which "class" the line belongs to (if-first-three-lines (str "the " (classes i) "s, ") "me-") ; Decide on the line ending (if-first-three-lines "and I did not speak out-\n" "and there was no one left to speak for me.") ; Then pick the trailer (if-first-three-lines (str "Because I was not a " (classes i) ".\n") ""))))) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~153~~ ~~150~~ ~~149~~ 147 bytes ``` `{=` ey ¯´ f `}´-d tre °s no e ¤ft speak f ´.`i`Sáû\E TÎè UÍát Jew`·rÈ+U+`e {Y}s, d I ¹d not speak t- Be¯«e I °s not a {Y}. Tn`}`Fir¡ ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=YHs9YCCQZXkgr7QgZo4gYH20LYRkIHSUcmUgsHMgbm8gjWUgpGZ0IJEgc3BlYWsgZo4gtC5gaWBT4ftcRQpUzuggVc3hiXQKSmV3YLdyyCtVK2CQZSB7WX1zLCCEZCBJILlkIG5vdCBzcGVhayCMdC0KQmWvq2UgSSCwcyBub3QgYSB7WX0uCgpUlG5gfWBGaXKh&input=) 1 byte saved thanks to [Oliver](https://codegolf.stackexchange.com/users/61613/oliver) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~124~~ 119 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .•RYÁ Wö∍®Ø’áÅÚ)’Òü•'x¡™vy„€Û‚½#NĀ虓ÿ€»‹é€‡€€ ÿs,€ƒ Iƒ§€–¡´€Ä-“©¶y“ƒ« I€¥€–€… ÿ.“.ª¶¶}®19£“€á-and€Ç€¥€¸€µ…¸€„¡´€‡€á.“J ``` [Try it online.](https://tio.run/##NU47CsJQELxKwEIEDVh6hFhY2IilooWNFgHRQnhKRBub2GgMwov4FysNikpgV3KQvUjcF7WZHWZ3ZqdlVqqNehTpJLxiGftaCX0aT@CMMxJzlDhEJ6WYjU8@SXZAkuW1uySWNDjhgoQDr0ThLXDHOgkXA9bhQeKOe2YkpMLBScPATPMMbc0IbdjGuylIuKgcK8NW2IPPwS6vj5qhYtbfqxg3nMAtXR0O4IPfg3M2BysWlF9mKs2aIqO/DW4KruyLGff9/fo2Qqmy8lH0AQ) **Explanation:** ``` .•RYÁ Wö∍®Ø’áÅÚ)’Òü• # Push compressed string "socialistxtrade unionistxjew" 'x¡ '# Split it on "x": ["socialist","trade unionist","jew"] ™ # Convert each word to Titlecase: ["Socialist","Trade Unionist","Jew"] v # Loop `y` over each of these strings: y # Push string `y` „€Û‚½ # Push dictionary string "first then" # # Split on spaces: ["first","then"] N # Push the index of the loop Ā # Truthify it (0 remains 0; every other number becomes 1) è # Use it to index into the list ™ # Titlecase it “ÿ€»‹é€‡€€ ÿs,€ƒ Iƒ§€–¡´€Ä-“ # Push dictionary string "ÿ they came for the ÿs, and I did not speak out-" # where the "ÿ" are automatically filled with the strings at the top of the stack © # Save it in the register (without popping) ¶ # Push a newline "\n" y # Push string `y` again “ƒ« I€¥€–€… ÿ.“ # Push dictionary string "because I was not a ÿ." # where the "ÿ" is automatically filled again with the string .ª # Sentence case it: "because" becomes "Because" ¶¶ # Push two newline characters "\n\n" } # After the loop: ® # Push the string from the register: # "Then they came for the Jews, and I did not speak out-" 19£ # Only leave the first 19 characters: "Then they came for " “€á-and€Ç€¥€¸€µ…¸€„¡´€‡€á.“ # Push dictionary string "me-and there was no one left to speak for me." J # Then join everything on the stack together (and output implicitly) ``` [See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why: * `.•RYÁ Wö∍®Ø’áÅÚ)’Òü•` is `"socialistxtrade unionistxjew"` * `„€Û‚½` is `"first then"` * `“ÿ€»‹é€‡€€ ÿs,€ƒ Iƒ§€–¡´€Ä-“` is `"ÿ they came for the ÿs, and I did not speak out-"` * `“ƒ« I€¥€–€… ÿ.“` is `"because I was not a ÿ."` * `“€á-and€Ç€¥€¸€µ…¸€„¡´€‡€á.“` is `"me-and there was no one left to speak for me."` [Answer] # [Text](https://esolangs.org/wiki/Text), 348 bytes ``` First they came for the Socialists, and I did not speak out- Because I was not a Socialist. Then they came for the Trade Unionists, and I did not speak out- Because I was not a Trade Unionist. Then they came for the Jews, and I did not speak out- Because I was not a Jew. Then they came for me-and there was no one left to speak for me. ``` This is the shortest possible version in its language, and is on par with the Befunge-93 answer at time of writing. ]
[Question] [ The [pigeonhole principle](https://en.wikipedia.org/wiki/Pigeonhole_principle) states that > > If *N* items are put into *M* boxes, with *N* > *M*, then at least one box must contain more than one item. > > > For many, this principle has a special status compared to other mathematical enouncements. As E.W. Dijkstra [wrote](https://www.cs.utexas.edu/users/EWD/transcriptions/EWD09xx/EWD980.html), > > It is surrounded by some mystique. Proofs using it are often regarded as something special, something particularly ingenious. > > > ## The challenge The purpose of this challenge is to illustrate the pigeonhole principle using ASCII art representations. Specifically: 1. Take as input `N` (number of items) and `M` (number of boxes), with `N` non-negative and `M` positive. `N` may be smaller than `M` (even if the principle does not apply in that case). 2. Randomly select one of the possible assignments of items to boxes. Each assignment should have a non-zero probability of being picked. 3. Produce an ASCII art representation of the assignment as follows: * There are `M` lines, each corresponding to a box. * Each line starts with a non-whitespace character, such as `|`. * Following that character is another non-whitespace character, such as `#`, repeated as many times as there are items in that box. Consider for example `N = 8`, `M = 5`. If the selected assigment of items to boxes is `4`, `1`, `0`, `3`, `0`, the representation is ``` |#### |# | |### | ``` A different run (resulting in a different assignment) of the same program could give ``` |# |## |# |# |### ``` There is some flexibility regarding the representation; see below. ## Specific rules The code should **theoretically run for any values** of `N` and `M`. In practice it may be restricted by memory size or data type limitations. Since observing the output is not sufficient to determine if all assignments have **non-zero probability**, each submission should explain how the code achieves that, if not obvious. The following **representation variations** are allowed: * Any pair of different, non-whitespace characters can be chosen. They must be consistent across program executions. * 90-degree rotations of the representation are acceptable. Again, the choice must be consistent. * Trailing or leading whitespace is allowed. As an example with a different representation format, for `N = 15`, `M = 6` the results of two executions of the program could be ``` VVVVVV @@@@@@ @@ @@@ @ @@ @ ``` or ``` VVVVV @@@ @ @@@ @ @ @ @ @ @ @ @ ``` Likewise, `N = 5`, `M = 7` could give, using another variation of the representation, ``` * * * * * UUUUUUU ``` or ``` *** ** UUUUUUU ``` or ``` * * * * * UUUUUUU ``` Note how the principle is not applicable in this case, because `N` <`M`. ## General rules [Programs or functions](http://meta.codegolf.stackexchange.com/a/2422/36398) are allowed, in any [programming language](http://meta.codegolf.stackexchange.com/a/2073/36398). [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. Input can be taken by any [reasonable means](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods); and with any format, such as an array of two numbers or two different strings. Output means and format are also flexible. For example, the output can be a list of strings or a string with newlines; returned as function output argument or displayed in STDOUT. In the latter case it is not necessary to worry about line wrapping caused by limited display width. Shortest code in bytes wins. [Answer] ## Mathematica, 68 bytes ``` Print/@(10^RandomSample@RandomChoice[IntegerPartitions[+##,{#}]-1])& ``` An unnamed function that takes two integer arguments, the number of boxes, followed by the number of items. It first computes all possible partitions of `N+M` into exactly `M` positive parts, and subtracts `1` from each partition afterwards. This gives us all possible partitions of `N` into `M` non-negative parts (which `IntegerPartitions` wouldn't generate otherwise). Then pick a random partition and shuffle it. This guarantees all possible ordered partitions with zeros are allowed. Finally, convert each bin of the partition to an output line by raising 10 to the corresponding power (such that each line becomes `1000...` with `k` zeros). An example output might look like: ``` 100 10000 1 10 10 ``` [Answer] # Python 2, 77 86 bytes ``` from random import* n,m=input() exec'c=randint(0,n);n-=c;print 10**c;'*~-m print 10**n ``` Generates a number in [0, n], prints that many items and substracts it from n. It does this m times. This makes it very unlikely anything makes it to the last box, but the question only asked that every output be *possible*, not *equally likely*. [Answer] ## Batch, 164 bytes ``` @for /l %%i in (1,1,%1)do @set h%%i=1 @for /l %%j in (1,1,%2)do @call set/ab=%%random%%%%%%%1+1&call set/ah%%b%%*=10 @for /l %%i in (1,1,%1)do @call echo %%h%%i%% ``` I think 7 consecutive `%` signs might be a new personal best! Note: this produces odd output should it ever assign more than 9 items to the same box; if that's a problem, then for 180 bytes: ``` @for /l %%i in (1,1,%1)do @set h%%i=1 @for /l %%j in (1,1,%2)do @call set/ab=%%random%%%%%%%1+1&call call set h%%b%%=%%%%h%%b%%%%%%0 @for /l %%i in (1,1,%1)do @call echo %%h%%i%% ``` Yes, that's 28 `%`s in total on the second line. [Answer] # C, 102 bytes ``` n,m;main(x){srand(time(0));for(scanf("%d %d",&n,&m);m--;n-=x)printf("|%0*s\n",x=m?rand()%(n+1):n,"");} ``` Takes input on stdin, e.g.: ``` echo "5 4" | ./pigeonhole ``` Won't generate each output with equal probability, but is capable of generating all possible combinations. ### Breakdown: ``` n,m; main(x){ srand(time(0)); // Seed random number generator for(scanf("%d %d",&n,&m); // Parse input values into n and m m--; // Loop through each bucket (count down) n-=x) // Subtract number assigned to bucket from total printf( // Output a formatted string using padding "|%0*s\n", // (turns out %0s will actually zero-pad a string!) x=m?rand()%(n+1):n, // Calculate a number of items for this bucket ""); } ``` Relies on GCC's handling of the undefined behaviour of `%0s` — normally `%0` will zero-pad an integer or float, but it can only pad (never truncate), so it's not possible to print a blank. But the behaviour for strings isn't defined, and GCC decided to make it zero-pad the same way, so this zero-pads an empty string to be able to write zero-or-more `0`s. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes ``` =þṗX¥S⁵* ``` This is a dyadic link that takes **M** as its left and **N** as its right argument. Output is an array of integers, where **0** represents pigeons and **1** represents holes. [Try it online!](https://tio.run/nexus/jelly#@297eN/DndMjDi0NftS4Vev/4eWRCg93bH/UMEfBOTEnRyEnMy9bITEvRaE4tSCxKLEkVSGpEiSYmpaamlKs9/@/6X@Lr3n5usmJyRmpAA "Jelly – TIO Nexus") ### How it works ``` =þṗX¥S⁵* Main link. Left argument: m. Right argument: n ¥ Combine the two links to the left into a dyadic chain and call it with arguments m and n. ṗ Compute the n-th Cartesian power of [1, ..., m], i.e., generate all vectors of length n that consist of elements of [1, ..., m]. X Pseudo-randomly choose one of those vectors with a uniform distribution. =þ Equal table; for each k in [1, ..., m] and each vector to the right, compare the elements of the vector with k. Group the results by the vectors, yielding a 2D Boolean matrix. R Range; map 1 to [1], 0 to []. S Take the sum of all columns. ⁵* Raise 10 to the resulting powers. ``` [Answer] # Python 2, ~~102~~ ~~99~~ ~~97~~ 90 bytes `m-1` times, chose a random amount `x` between `0` and `n`, inclusive and subtract it from n. Then print a `1` and `'0'*x`. Finally, print `1` and the rest of `0`s. Not at all equal chances, but all configurations are possible. ``` from random import* n,m=input() exec'x=randrange(n+1);n-=x;print 10**x;'*(m-1) print 10**n ``` (Reused code from the broken Python answer.) [Answer] # Haskell, ~~114~~ 94 bytes ``` import System.Random n#m=map(10^).take m.until((==n).sum.take m)tail.randomRs(0,m)<$>newStdGen ``` A bit of a brute force approach: Generates an infinite list of random numbers, takes n numbers of the start of the list, sums them up, and checks if they're equal to m. If not, take the first element off the list and repeat. [Try it online!](https://tio.run/nexus/haskell#nYxBC4IwGIbv/YrhgjloIw9WxOa1S130aBJDJ0l@m@ikAv92Z5MO0qFT7/F5eZ6xgsa2DiXPzmngsTKFhYXBMJSCOXXTCCSoxj8rFpGB7FOCyfAQLA04V1lGecl746ra96U0lHc98JI6VdW8/aTizl@vgIplZPQ9ccVBmxFUZZBEhUVT@XRBTe8S1x4nJgTa4XCB5s2X533RH1oQ4s0/Xoi348tYlqv8qt8 "Haskell – TIO Nexus") Note: 73 bytes without the import EDIT: Saved some bytes with the 10^ trick ([Try the new version online!](https://tio.run/nexus/haskell#lcyxCsIwFIXhvU9xMQ4JaGiHqkPj6qJLuyuhDRjsvQnpLeKDO1cREXHzjD98Z/IYQ2JobgM71LWlLmBGAg3aKIv8qDTbiwPUI7HvpTSGlB5GfGfF1vc6vVg9yHyBqppvyV0b7naOJrSewEAX4Pl3OEFMnhhMVcFGlBl8FkduOO0JZrOv@muKUqz@RqVYT3cKy9a2Z/cA "Haskell – TIO Nexus")) [Answer] ## REXX, 74 bytes ``` arg n m m=m-1 o.=@ do n a=random(m) o.a=o.a||# end do a=0 to m say o.a end ``` Output (8 5): ``` @# @### @ @# @### ``` Output (8 5): ``` @# @# @ @#### @## ``` [Answer] # C, ~~175~~ 138 bytes *Thanks to @Dave for saving 37 bytes!* ``` i;f(n,m){char**l=calloc(m,8);for(i=0;i<m;)l[i]=calloc(n+1,1),*l[i++]=124;for(i=n+1;--i;)*strchr(l[rand()%m],0)=35;for(;i<m;)puts(l[i++]);} ``` [Try it online!](https://tio.run/nexus/c-gcc#NYzBCoMwEETvfoWXwm6MoG0FYZsvEQ8hVVxIYonpSfzsnm3Qdk7DvJnZmUbw0uFqJh2EsMpoa2cDTrZI4xyAVUX8cIS24/5PfVHLGqVIWVH0qr7ef90EqCyZUCwxmCmA7YL2T8CL62WF6tYcxfPx9Y4LnBdI284@5k6zB8zWLE9ajmlkN0CFSEc2Qiub5Lf94@fSaDMNXw) [Answer] # AHK, 66 bytes ``` 2-=1 Loop,%2%{ Random,r,0,%1% Send,|{# %r%}`n 1-=r } Send,|{# %1%} ``` I followed the same principal that [orlp](https://codegolf.stackexchange.com/a/114959/38183) did using random numbers from 0 to N and then subtracting it from N. Unfortunately, I couldn't save bytes by using 10^r because of the way the Send function works. Alas and alack. Here are some outputs for n=8, m=5: ``` |## |##### |## |## |# |## |## |# |##### | |### |# |# |## | |### |### | |### | | | |# | | | |# |### | |##### ``` [Answer] ## CJam, ~~30~~ ~~31~~ 21 bytes ``` :B1a*:C\{CBmrAt.*}*N* ``` Input is two numbers `n m` on the stack. Uses `1` for the column character and `0` for the repeated character. Explanation: ``` :B e# Store m in B (without deleting it from the stack) 1a e# Push 1 and wrap it in an array: [1] * e# Repeat the array m times :C e# Store this array in C (without deleting) \{ e# Do n times: CBmrAt e# Create an array of 1s with a random element replaced with 10. .* e# Vectorized multiplication: multiply the respective elements in the arrays. e# Effectively, we multiply a random value in the array by 10 (and add a 0 to the end). }* e# End loop. N* e# Join with newlines. ``` [Answer] # [Röda](https://github.com/fergusq/roda), 79 bytes ``` f n,m{a=[0]*m i=0{{n-- a[i%m]++}if randomBoolean i++}while[n>0] a|[`|`.."#"*_]} ``` [Try it online!](https://tio.run/nexus/roda#DcixCoMwEADQPV9xKF3USJZCFzv0N0LQwyZ44F1ECh2SfHbn2De@GkAGTjhZ4zpWNJmURGuFlm7s@r5QgBPlHfkV4@5RFP3zu9HurTyNU5jtkpdxbNqmm12pjCSQIMBjgDtkOE6SD8xQ6k@iXnHd/AU "Röda – TIO Nexus") This creates an array of zeroes and increments them at random places. [Answer] # PHP, 100 bytes ``` list($z,$m,$n)=$argv;$a=array_fill(0,$n,z);while($m>0){$a[rand(0,$n-1)].=a;$m--;}echo join("\n",$a); ``` **Breakdown :** ``` list($z,$m,$n)=$argv; // assigns the input vars to $m and $n $a=array_fill(0,$n,z); // creates an array $a of $n elements containing 'z' while($m>0){ // randomly populate array $a $a[rand(0,$n-1)].=a; // $m--; // } // echo join("\n",$a); // output $a contents separated by a new line ``` Outputs for `m=7` and `n=5` : First execution : ``` za zaa za za zaa ``` Second execution : ``` za zaa zaaa z za ``` [Try it online!](https://eval.in/766990) [Answer] # JavaScript, 105 bytes ``` x=>y=>{s=[];for(;x>1;y-=t)s[--x]="|"+"#".repeat(t=Math.random()*(y+1)|0);s[0]="|"+"#".repeat(y);return s} ``` [Try it online!](https://tio.run/nexus/javascript-node#ZcpBCsIwEIXhvaeQuJmxJKSuhDC9gSeoXYSaWkUzkkRosB7bda07xcX73@braBqoylQ9ItWN6TiAGarSZEkJYy3l0JAYRSFWQgV3czZBop1NvQrWH/gKuIZclDhqNLHWfzijCS7dg1/G59Syj3xx6sJH6KDUOE@jOvPJg9h7gcXczy9@5XaGm2@H08uzbG3buzc) Due to the method of assigning the rows, this will tend to place more towards the bottom, although there is a small chance that the top will get some. [Answer] # Ruby, 52 bytes ``` ->(n,m){r=Array.new(m){?|};n.times{r[rand m]+=?#};r} ``` Creates an anonymous function which takes two integers as arguments and returns an array of Strings: ``` >> puts ->(n,m){r=Array.new(m){?|};n.times{r[rand m]+=?#};r}.call 7,5 |# |# |## |## |# ``` [Answer] ## Python 2, 81 bytes ``` from random import* def f(n,m):l=['#']*m;exec('l[randrange(m)]+="o";'*n);return l ``` Returns a list of strings. [Answer] ## Javascript (ES7), 75 bytes ``` (N,M)=>{for(r='';M;M--,N-=x=~~(Math.random()*(N+1)),r+=10**x+` `);return r} ``` I thought I was clever for coming up with the powers of 10 idea only to realize that most answers were already using that. [Answer] ## AWK, 78 bytes ``` {srand();for(;n++;)c[k]=c[k=int($2*rand())]"#"}END{for(;j<$2;)print"|"c[j++]} ``` Takes 2 arguments, first the number of items, then the number of boxes. Starts by seeding the random number generator so each run is different. Then simply builds up strings in an array, Example usage: ``` awk '{srand();for(;n++;)c[k]=c[k=int($2*rand())]"#"}END{for(;j<$2;)print"|"c[j++]}' <<< "12 5" Example output: |## |### |## |## |### ``` [Answer] ## MATLAB, ~~103~~ 94 bytes ``` function a(m,n) d=@(p)disp(char([1,~(1:p)]+48));for i=1:m-1;p=randi([0,n]);d(p);n=n-p;end;d(n) ``` ### With Formatting ``` function a(m,n) for i=1:m-1 d=@(p)disp(char([1,~(1:p)]+48)); % inline function for displaying p=randi([0,n]); % picking a random number b/w 0 and n d(p); % '1' represents the box/pigeonhole, with '0's denoting entries n=n-p; end d(n); % writing the remaining entries/zeros ``` ### Sample Output ``` >> a(4,7) 10 10000 10 10 ``` There are trailing whitespaces since each array entry is displayed with a tab between them, but this should be acceptable as per specs. This seems like a very simplistic implementation to me, so I'm sure this could be improved. Thanks to @Luis Mendo for suggestions. [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~62~~ 54 bytes ``` @(n,m)strcat(62,(sum(randi(m,1,n)==(1:m)',2)>=1:n)*42) ``` Anonymous function that takes two numbers and outputs a 2D array of chars with `>` for boxes and `*` for objects. All results are equally likely. [Try it online!](https://tio.run/nexus/octave#BcExCoAwDAXQ4/gjcUjRDoWKVwlV0CERWj26c32vb3A2ak8t@iAGRnsNVX2/YCzslDMkGQ0caM2SnMY5UFdvkIUj9c/vqWg5jx8 "Octave – TIO Nexus") [Answer] # TI-Basic, ~~63~~ 62 bytes ``` Prompt N,M For(A,1,M N→B If M-A randInt(0,N→B ":→Str0 For(C,1,B Ans+"X→Str0 End Disp Ans N-B→N End ``` > > Each assignment should have a non-zero probability of being picked. > > > This criteria made this program much easier to write. Example I/O: ``` prgmPIDGEON N=?5 M=?2 :XXXX :X ``` Explanation: ``` Prompt N,M # 5 bytes, input number of items, number of boxes For(A,1,M # 7 bytes, for each box N→B # 4 bytes, on last box, make sure the sum is met by adding N items If M-A # 5 bytes, if not last box randInt(0,N→B # 8 bytes, add random number of items from 0 to N to box A ":→Str0 # 6 bytes, first character For(C,1,B # 7 bytes, add B items to the box Ans+"X→Str0 # 8 bytes End # 2 bytes Disp Ans # 3 bytes, print this box N-B→N # 6 bytes, subtract the items used in this box End # 1 byte, move on to next box ``` [Answer] ## MATLAB, ~~73~~ ~~64~~ 58 bytes ### Update#3 I do need the sorting, it seems, since otherwise I get negative integers. I did replace `disp(sprintf(...))` with `fprintf(...)` now, though, so the answer remains 58 bytes. ``` @(m,n)fprintf('%i\n',10.^diff([0;sort(randi(n,m-1,1));n])) ``` ### Update#2: I realized I didn't need to sort the array, and in fact sorting would actually reduce the average of numbers in the array. So I deleted the `sort(...)` part. Note that the output remains the same, so I am not updating the "sample output". ``` @(m,n)disp(sprintf('%i\n',10.^diff([0;randi(n,m-1,1);n]))) ``` ***Finally closing in on the Octave answer by Luis! :D*** ### Update#1: ``` @(m,n)disp(sprintf('%i\n',10.^diff([0;sort(randi(n,m-1,1));n]))) ``` Instead of converting to string, I just display numbers directly. I could reduce to 58 bytes, by removing the `disp(...)`, but then I get the extra `ans =` with just sprintf, and don't know if that's acceptable. ### Initial code: ``` @(m,n)disp(strjust(num2str(10.^diff([0;sort(randi(n,m-1,1));n])),'left')) ``` Thanks to some suggestions by [Luis](https://codegolf.stackexchange.com/users/36398/luis-mendo), I got rid of the loop in [my previous answer](https://codegolf.stackexchange.com/a/115148/67708). Now I first create a vertical array of `m` random numbers adding up to `n` (`diff([0;sort(randi(n,m-1,1));n])`), then use them as exponents of 10, convert them to a string, left-justify them, and display them. I could technically get rid of the disp(...) to save another 6 bytes, but then an "ans" gets printed which may violate specs. There may also be a way around to changing them to string and left-justifying to get the desired end format, so I'm open to suggestions. ### Sample output: ``` >> a=@(m,n)disp(strjust(num2str(10.^diff([0;sort(randi(n,m-1,1));n])),'left')); >> a(4,6) 1000 10 100 1 ``` ***Note***: I have changed my function to an anonymous function here, based on suggestions. In the sample output, I have assigned that to `a` in order to demonstrate. I hope this does not violate specs, but if it does please let me know and I will change it. [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 29 bytes ``` ('|')\rep\[:randin'#'push@.]* ``` [Try it online!](https://tio.run/nexus/stacked#MzRVMPuvoV6jrhlTlFoQE21VlJiXkpmnrqxeUFqc4aAXq/U/v7Tk/9e8fN3kxOSMVAA "Stacked – TIO Nexus") Behaves by constructing an array of `M` singletons containing `'|'`, then adding `'#'` to a randomly chosen array `N` times. [Answer] # [Python 2](https://docs.python.org/2/), 80 95 89 88 bytes ``` from random import* n,m=input() while m:x=randint(0,n);print'1'+'0'*[n,x][m>1];m-=1;n-=x ``` [Try it online!](https://tio.run/##FcqxCsMgGEXhPU@RTU0VYggUKvZFJENIUxT6X0UMtQ/e2abT@YaTPsVHTK09c6Q@r3icCZRiLkMHSTYgHYWL7u3Da@/pVu1/Cih8lBAm5ZNMswsb2eAg6@LorhdDymoDZWtr/Cpn8UVU27r5/Qc "Python 2 – Try It Online") * Added 15 Bytes: Previous edit was a bit flawed, some piegons were left out. * Saved 6 Bytes: replaced if else by [n,x][m>1] * Saved 1 Byte: import \* [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes ``` ≔EN⟦⟧θFN⊞‽θ#Eθ⁺|⪫ιω ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DN7FAwzOvoLTErzQ3KbVIQ1NHIToWSBRqWnOl5RcpoEpqKgSUFmdoBCXmpeTnahQC1SkpKwFVBhRl5pWAzSrUUQjIKS3WUKpR0lHwys/M08jUUSjXBALr//9NuSz@65blAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` N Input `M` E Map over implicit range ⟦⟧ Empty array ≔ θ Assign resulting nested array to `q` N Input `N` F Loop over implicit range θ Nested array `q` ‽ Random element # Literal string ⊞ Append to array θ Nested array `q` E Map over array ι Current element ω Empty string ⪫ Join | Literal string ⁺ Concatenate Implicitly print on separate lines ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 19 bytes ``` Ṅ'L⁰≤;℅₅⁰εð*ƛ0;JÞ℅↵ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=j&code=%E1%B9%84%27L%E2%81%B0%E2%89%A4%3B%E2%84%85%E2%82%85%E2%81%B0%CE%B5%C3%B0*%C6%9B0%3BJ%C3%9E%E2%84%85%E2%86%B5&inputs=8%0A5&header=&footer=) ``` Ṅ # The partitions of the first number ' ; # Filtered by... L⁰≤ # Length is less than or equal to the second input ℅ # Choose a random item of this ₅ # Get length ⁰εð* # Subtract from second input, and get that many spaces ƛ0; # Fill with 0s J # Append this to the current string Þ℅ # Get a random permutation of this ↵ # 10 to the power of each item of this ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), ~~17 (15?)~~ 16 (14?) [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` @¶Xx}a@ô öVãApX ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=QLZYeH1hQPQg9lbDo0FwWA&input=OCA1) If we don't have to allow for the possibility of all `N` items ending up in the same box then we can save 2 bytes: ``` @¶Xx}a@öVãApX ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=QLZYeH1hQPZWw6NBcFg&input=OCA1) ``` @¶Xx}a@ô öVãApX :Implicit input of integers U=N & V=M @ :Left function, taking an array X as argument ¶ : Is U equal to Xx : X reduced by addition } :End function a :Get the first result of the right function that returns true when passed through the left one @ :Right function ô : Range [0,U] öV : Get V random elements (or V random elements in [0,U) if ô is omitted) à :End function £ :Map each X A : 10 pX : Raised to the power of X :Implicit output joined with newlines ``` ]
[Question] [ A string is *pairable* if it can be split into subtrings, each of which is a string repeated twice consecutively. For example, `aabaaababbbaba` is pairable as: ``` aaba aaba b b ba ba ``` Given a non-empty string of `a`'s and `b`'s, output a Truthy value if it's pairable and a Falsey value if it isn't. **Pairable:** ``` aa abaaba bbababbb aabaaababbbaba babababa bbbbbbbbbbbb aaababbabbabbbababbaabaabaababaaba aaaabaab ``` **Not pairable:** ``` a ba baab abaabaaba bbbbbbbbbbbbbbb baababbabaaaab aaaaabbaaaaa ``` I encourage you to come up with non-regex-based solutions even when there's already a shorter regex answer in your language. You can mark them as "no regex". By regex, I mean a built-in string pattern matching subsystem. --- **Leaderboard:** ``` var QUESTION_ID=98252,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/98252/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] # Python 2, ~~68~~ 63 bytes ``` f=lambda s,n=1:s==2*s[:n]or''<s[n:]>-f(s,n+1)<f(s[n:])*f(s[:n]) ``` Returns *True* or *False*. Test it on [Ideone](http://ideone.com/WIiCZx). [Answer] # [Retina](http://github.com/mbuettner/retina), 11 bytes ``` ^((.+)\2)+$ ``` [Try all the test cases.](http://retina.tryitonline.net/#code=JWBeKCguKylcMikrJA&input=YWEKYWJhYWJhCmJiYWJhYmJiCmFhYmFhYWJhYmJiYWJhCmJhYmFiYWJhCmJiYmJiYmJiYmJiYgphYWFiYWJiYWJiYWJiYmFiYWJiYWFiYWFiYWFiYWJhYWJhCmEKYmEKYmFhYgphYmFhYmFhYmEKYmJiYmJiYmJiYmJiYmJiCmJhYWJhYmJhYmFhYWFiCmFhYWFhYmJhYWFhYQ) The first two bytes make it multi-line. Pretty literal interpretation of the rules, obviously uses regex, like all Retina programs will. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ẆŒPẋ€€2F€ċ ``` Not exactly efficient... [Try it online!](http://jelly.tryitonline.net/#code=4bqGxZJQ4bqL4oKs4oKsMkbigqzEiwrhu7TDh-KCrMW84bu0S-KCrFk&input=&args=YWEKYWFiYgphYmFiCmEKYmEKYmFhYgpiYmJiYg) ### How it works ``` ẆŒPẋ€€2F€ċ Main link. Argument: s (string) Ẇ Window, generate the array of all substrings of s. ŒP Powerset; generate all subarrays of substrings of s. ẋ€€2 Repeat each substring in each subarray twice. For example, ["ab", "a", "b"] becomes ["abab", "aa", "bb"]. F€ Flatten the subarrays by concatenating their strings. ċ Count how many times s appears in the generated strings. ``` [Answer] ## Haskell, ~~72~~ 69 bytes (no regex) ``` g(a:b:c)|a==b=g c g x=x==[] any(g.words.concat).mapM(\c->[[c],c:" "]) ``` A brute-force approach. [Try it on Ideone](http://ideone.com/VqybtA). Thanks to BlackCap for -3 bytes. ## Explanation The helper function `g` takes a list of strings, and checks that it consists of pairs of identical strings, like `["aa","aa","bba","bba","ab","ab"]`. The (anonymous) main function splits a string in all possible ways, and checks that at least one splitting results in a list that `g` accepts. ``` g(a:b:c) g on list with elements a, b and tail c, |a==b in the case that a==b, =g c recurses to the tail c. g x= g on any other list x x==[] checks that x is empty. This includes the case where a is not equal to b, resulting in False. any(g.words.concat).mapM(\c->[[c],c:" "]) The main function: mapM(\c->[[c],c:" "]) Replace each letter c with either "c" or "c " in all possible ways, return list of results. any( ). Check that at least one result satisfies this: concat Concatenate the 1- or 2-letter strings, words. split again at each space, g. apply g. ``` [Answer] # Python 2, 60 bytes ``` f=lambda s,t='':''<s>f(s[1:],t+s[0])|f(t and s)*f(t)>-(s==t) ``` I hope this is correct. It runs pretty slowly and the `and` doesn't look optimal. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒṖµœs€2ZEµ€S ``` Two bytes longer than [my other answer](https://codegolf.stackexchange.com/a/98259/12012), but this approach is a lot more efficient and handles all but one of the test cases. [Try it online!](http://jelly.tryitonline.net/#code=xZLhuZbCtcWTc-KCrDJaRcK14oKsUwrhu7ThuaPigJzigJ3Dh-KCrOKCrEc&input=&args=YWEKYWJhYWJhCmJiYWJhYmJiCmFhYmFhYWJhYmJiYWJhCmJhYmFiYWJhCmJiYmJiYmJiYmJiYgoKYQpiYQpiYWFiCmFiYWFiYWFiYQpiYmJiYmJiYmJiYmJiYmIKYmFhYmFiYmFiYWFhYWIKYWFhYWFiYmFhYWFh&debug=on) ### How it works ``` ŒṖµœs€2ZEµ€S Main link. Argument: s (string) ŒṖ Generate all partitions of s. µ µ€ Map the monadic chain between the µ's over the partitions. œs€2 Split each string in the partition into two chunks of equal length. Z Zip/transpose, collecting the first halves in one array and the second halves in another. E Test the arrays of halves for equality. S Return the sum of the results, counting the number of different ways s can be paired. ``` [Answer] # Pyth - No Regex - ~~13~~ 12 bytes Checks if any of the partitions are made up of all string that are equals to each other when chopped in two. ``` sm.AqMcL2d./ ``` [Test Suite](http://pyth.herokuapp.com/?code=sm.AqMcL2d.%2F&test_suite=1&test_suite_input=%27aa%27%0A%27abaaba%27%0A%27bbababbb%27%0A%27aabaaababbbaba%27%0A%27babababa%27%0A%27bbbbbbbbbbbb%27%0A%27a%27%0A%27ba%27%0A%27baab%27%0A%27abaabaaba%27%0A%27bbbbbbbbbbbbbbb%27%0A%27baababbabaaaab%27%0A%27aaaaabbaaaaa%27&debug=0). [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 14 bytes (no regex) ``` lye~l:1j@2zcc? ``` [Try it online!](http://brachylog.tryitonline.net/#code=bHllfmw6MWpAMnpjYz8&input=ImFhYmFhYWJhYmJiYWJhIg) This is too slow for some of the test cases ### Explanation ``` ly The list [0, …, length(Input)] e~l A list whose length is an element of the previous list :1j Append itself to this list @2zc Split in half, zip and concatenate so that the list contains pairs of consecutive identical elements c? The concatenation of that list must result in the Input ``` [Answer] ## JavaScript (ES6), no regexp, ~~75~~ 74 bytes ``` f=s=>!s|[...s].some((_,i)=>i&&s[e='slice'](0,i)==s[e](i,i+=i)&&f(s[e](i))) ``` Returns `1` for pairable otherwise `0`. Edit: Saved 1 byte thanks to @edc65. [Answer] ## Python, 58 bytes ``` f=lambda s,p='':s>''and(f(p)>-(s==p)<f(s))|f(s[1:],p+s[0]) ``` This is based on the [Dennis's recursive method](https://codegolf.stackexchange.com/a/98260/20260). The Boolean negation trick is taken from there as well. The new idea is to recurse over partitions `(p,s)` of the original string by starting with `('',s)` and repeatedly moving the first character of `s` to be the last character of `p`. This allows for the parts to be referred to directly without string slicing. But, because the partition starts with `p` empty, we must be careful to avoid infinite loops of `f(s)` calling `f(s)`. [Answer] # JavaScript (ES6), 24 bytes ``` x=>/^((.+)\2)+$/.test(x) ``` Probably doesn't get shorter than this. [Answer] # PHP, 40 Bytes prints 0 for false and 1 for true ``` <?=preg_match("#^((.+)\\2)+$#",$argv[1]); ``` [Answer] # Python, ~~66~~ 64 bytes Thanks @Zgarb for -1 byte! ``` f=lambda x,s=1:x>x[:s]and(x==2*x[:s])|f(x[:s])&f(x[s:])|f(x,s+1) ``` Returns `True` or `False`. [Try it online!](https://repl.it/EQHk/3) Any help golfing this would be appreciated. [Answer] ## Racket 230 bytes ``` (let((sl string-length)(ss substring))(if(odd?(sl s))(printf ".~n")(begin(let p((s s))(if(equal? s "")(printf "!") (for((i(range 1(add1(/(sl s)2)))))(when(equal?(ss s 0 i)(ss s i(* 2 i)))(p(ss s(* 2 i)(sl s)))))))(printf ".~n")))) ``` Prints a '!' for each way in which the string is pairable. Prints a '.' at the end. Ungolfed: ``` (define (f s) (let ((sl string-length) ; create short names of built-in fns (ss substring)) (if (odd? (sl s)) (printf ".~n") ; odd length strings cannot be pairable; end here. (begin (let loop ((s s)) ; start testing here (if (equal? s "") (printf "!") ; if no remaining string, it must be pairable (for ((i (range 1 (add1 (/(sl s)2))))) ; ch lengths varying from 1 to half of string length (when (equal? (ss s 0 i) ; ch if substrings are same (ss s i (* 2 i))) (loop (ss s (* 2 i) (sl s) )))))) ; if yes, loop to check remaining string. (printf ".~n"))))) ; End of testing. ``` Testing: ``` (println "Following should be pairable") (f "bbaabbaa") ; should produce 2 '!' since 2 ways are possible. (f "aa") (f "abaaba") (f "bbababbb") (f "aabaaababbbaba") (f "babababa") ; should be pairable in 2 ways. (f "bbbbbbbbbbbb") ; should be pairable in many ways. (f "aaababbabbabbbababbaabaabaababaaba") (f "aaaabaab") (println "Following should be unpairable") ; (f "a") (f "ba") (f "baab") (f "abaabaaba") (f "bbbbbbbbbbbbbbb") (f "baababbabaaaab") (f "aaaaabbaaaaa") ``` Output: ``` "Following should be pairable" !!. !. !. !. !. !!. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!. !. !. "Following should be unpairable" . . . . . . ``` [Answer] # Perl, 16 +2 = 18 bytes (with regex) Run with the `-nl` flags. `-E` is free. ``` say/^((.+)\2)+$/ ``` Run as: ``` perl -nlE 'say/^((.+)\2)+$/' ``` Returns a list of the capture groups (a truthy) if pairable, null string if not pairable. Explanation The `-nl` flags will run the code in a loop (`-n`), putting the input (with trailing newline removed because of `-l`) into the variable `$_` each time, then evaluating the code each time input is entered, until the program is manually terminated. The `-E` flag lets you evaluate code on the command line, and enables the `say` command. ``` say/^((.+)\2)+$/ /^((.+)\2)+$/ #The regex engine (.+)\2 #Find any set of at least one character, followed by itself ( )+ #Do this at least one time /^ $/ #Make sure that this matches the entire string from start to end say #Output the result of the regex ``` If a match is found (e.g. if the string is pairable), then the regex returns a list of the capture groups, which evaluates to a truthy, which is then passed to `say`, and output. If no match is found, then the regex returns the empty string, which evaluates to falsy, which is then passed to `say`, and output. Sample: ``` $ perl -nlE 'say/^((.+)\2)+$/' aaababbabbabbbababbaabaabaababaaba baababaababaaba #Truthy baababbabaaaab #Falsy bbababbb bbb #Truthy aabaaababbbaba bababa #Truthy abaabaaba #Falsy ``` [Answer] # GNU Prolog, ~~49~~ 46 bytes Probably works in other variants too, although they don't all represent strings the same way; GNU Prolog's representation is a useful one for this problem. It's unclear whether this counts as using regex or not. It's not using any regex-like feature, but the entire semantics of the language are similar to those of regex. New version (uses the recursion trick seen in some other answers): ``` s(X):-append(A,B,X),(A=B;A\=X,B\=X,s(A),s(B)). ``` Older version: ``` s(X):-X=[];append(A,B,X),B\=X,append(C,C,A),s(B). ``` This is a predicate (Prolog's equivalent of a function) called `s`, not a complete program. Use it like this: ``` | ?- s("aa"). true ? yes | ?- s("aaababbabbabbbababbaabaabaababaaba"). true ? yes | ?- s("baababbabaaaab"). no | ?- s("bbbbbbbbbbbbbbb"). no ``` An interesting feature of the older solution is that if you ask the interpreter "are there more solutions?" via use of `;` at the `true ?` prompt (rather than asking "is there any solution" via pressing return at the prompt, like I did above), it returns "true" a number of times equal to the number of different ways the string can be expressed in the given form (e.g. it returns "true" twice with `s("aaaa").`, as this can be parsed as `(a a)(a a)` or as `(aa aa)`). Prolog programs are often reversible (allowing `s` to *generate* a list of strings with the given property). The older one isn't (it goes into an infinite loop), but that's because of the golfed method I used to ensure that C is nonempty; if you rewrite the program to specify C as nonempty explicitly, it generates strings of the form "aa", "aabb", "aabbcc", and so on (Prolog being Prolog, it doesn't specify identities for the characters that make them up, just a specification of which characters are the same). The newer one generates strings of the form "aa", "abab", "abcabc", and so on; this is an infinite loop in its own right, and thus never hits the point at which it'd get stuck due to failing to detect a zero-length string. [Answer] ## Brainfuck, 177 bytes ``` +[<<<<,]>>>>[>+[>+[[>>]<+<[<<]>+>-]<[>+<-]>>>,>>[>>]+<<[<+>>-<-]<[>+<-]>>[,>[-<< <<]<[<<<<]>]<[[<<]>]>>]>>[[>+>>>]>>>[>]<<<<[>+[-<<<,<]<[<<<[[<<<<]>>]<]>]>>]<[[- >>>>]>>[<]<]<<]<. ``` Formatted: ``` +[<<<<,] >>>> [ >+ [ >+ [ [>>] <+<[<<] >+>- ] <[>+<-]> >>,>>[>>] +<<[<+> >-<-] <[>+<-]> > [ not equal ,>[-<<<<] <[<<<<] > ] < [ equal [<<] > ] >> ] >> [ mismatch [>+>>>] >>>[>] <<<< [ backtrack >+[-<<<,<] < [ not done yet <<< [ [<<<<] >> ] < ] > ] >> ] < [ match [->>>>] >>[<] < ] << ] <. ``` Expects input without a trailing newline. Prints `\x00` for false and `\x01` for true. [Try it online.](http://brainfuck.tryitonline.net/#code=K1s8PDw8LF0-Pj4-Wz4rWz4rW1s-Pl08KzxbPDxdPis-LV08Wz4rPC1dPj4-LD4-Wz4-XSs8PFs8Kz4-LTwtXTxbPis8LV0-PlssPlstPDw8PF08Wzw8PDxdPl08W1s8PF0-XT4-XT4-W1s-Kz4-Pl0-Pj5bPl08PDw8Wz4rWy08PDwsPF08Wzw8PFtbPDw8PF0-Pl08XT5dPj5dPFtbLT4-Pj5dPj5bPF08XTw8XTwu&input=YmFhYmFhYWE) This implements depth-first search. In particular: check for repeated prefixes of increasing length starting from the current suffix, then move to the next suffix if a match is found, otherwise backtrack. At the beginning, the string is reversed and a sentinel `\x01` is placed at the end. The tape is divided into 4-cell nodes. The memory layout of a node is: `c h x 0` where `c` is the character, `h` is a flag for whether the character is in the first half of a repeated prefix, and `x` is a flag to keep track of the current pair of characters being compared. The `h` flags stay in place while the `x` flags form a moving window. If the string is pairable, the pointer lands next to the sentinel at the end of the main loop; otherwise, the pointer falls off the left side of the string while backtracking. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` ~c~jᵐ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vy65Luvh1gn//yslJiYlgnBSEhAnKgEA "Brachylog – Try It Online") Note that this algorithm can take a *very* long time, especially on falsey cases, since it checks every possible partition of the input string. ### Explanation ``` ~c Reversed concatenate: find a list that, when concatenated, results in the input string This examines all partitions of the input ~jᵐ Map reversed juxtapose: for each string in that list, is it the result of concatenating a string to itself? ``` For an input string like `"ababcc"`, `~c` tries different partitions until it comes to `["abab", "cc"]`, at which point `~j` succeeds for both items of the list, `ᵐ` outputs `["ab", "c"]`, and the predicate succeeds. [Answer] # [R](https://www.r-project.org/), 31 bytes ``` grepl("^((.+)\\2)+$",scan(,"")) ``` [Try it online!](https://tio.run/##VUzLCoAwDLv3M4qHjQ0Pfs8QUhEvIjL/n7muTrENfSbJpWx5PXfHs3Nj8ClNPgwcrwWHi8zeF4AgqCCRWkWEdIPN7Q7LSviCHobBlECHGaqUdKT38fNQG@k2QCO21haUGw "R – Try It Online") Based on Retina answer. # [R](https://www.r-project.org/), 129 bytes And here’s an original, non-regex answer: ``` o=(y=utf8ToInt(scan(,"")))<0;for(i in 2*1:(sum(y>0)/2))for(j in 1:(i/2)){w=i:(i-j+1);v=w-j;if(all(y[w]==y[v]))o[c(v,w)]=T};all(o) ``` [Try it online!](https://tio.run/##bYnLCsMgFER/JWR1b5vQJKtSe7vvPjtxoQFBSSPkoUjpt1ul2w4MM5yzpuQIIh27vo7uueywTXKBpq4R8d4x7VYwlVmq4dTfYDteEB8dXgbEYmwxmZsC3oFMvq0998g8hdYyo0HOM0QeBFHkXiA6PoFvAgoaP6xIh0kqJUt@o8rk/oPpCw "R – Try It Online") [Answer] # [Lithp](https://github.com/andrakis/node-lithp), 57 characters ``` #S::((? (!= (null) (match S "^((.+)\\2)+$")) true false)) ``` Sample usage: ``` % pairable_strings.lithp ( (def f #S::((? (!= (null) (match S "^((.+)\\2)+$")) true false))) (print (f "aa")) (print (f "aabaaababbbaba")) (print (f "aaababbabbabbbababbaabaabaababaaba")) (print (f "ba")) ) # ./run.js pairable_strings.lithp AtomValue { value: 2, type: 'Atom', name: 'true' } AtomValue { value: 2, type: 'Atom', name: 'true' } AtomValue { value: 2, type: 'Atom', name: 'true' } AtomValue { value: 3, type: 'Atom', name: 'false' } ``` ]
[Question] [ # Challenge Given an input of an all-lowercase string `[a-z]`, output the total distance between the letters. ## Example ``` Input: golf Distance from g to o : 8 Distance from o to l : 3 Distance from l to f : 6 Output: 17 ``` ## Rules * Standard loopholes forbidden * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") - shortest answer in bytes wins. * The alphabet can be traversed from either direction. **You must always use the shortest path.** (i.e the distance between `x` and `c` is 5). ![1](https://i.stack.imgur.com/RyIZy.jpg) # Test cases ``` Input: aa Output: 0 Input: stack Output: 18 Input: zaza Output: 3 Input: valleys Output: 35 ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~11~~ 8 bytes ``` OIæ%13AS ``` Saved 3 bytes thanks to @[Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender). [Try it online!](http://jelly.tryitonline.net/#code=T0nDpiUxM0FT&input=&args=J2dvbGYn) or [Verify all test cases.](http://jelly.tryitonline.net/#code=T0nDpiUxM0FTCsOH4oKs&input=&args=Wydnb2xmJywgJ2FhJywgJ3N0YWNrJywgJ3phemEnLCAndmFsbGV5cydd) ## Explanation ``` OIæ%13AS Input: string Z O Ordinal. Convert each char in Z to its ASCII value I Increments. Find the difference between each pair of values æ%13 Symmetric mod. Maps each to the interval (-13, 13] A Absolute value of each S Sum Return implicitly ``` [Answer] ## Haskell, ~~57~~ 56 bytes ``` q=map$(-)13.abs sum.q.q.(zipWith(-)=<<tail).map fromEnum ``` Usage example: `sum.q.q.(zipWith(-)=<<tail).map fromEnum $ "valleys"` -> `35`. How it works: ``` q=map$(-)13.abs -- helper function. -- Non-pointfree: q l = map (\e -> 13 - abs e) l -- foreach element e in list l: subtract the -- absolute value of e from 13 map fromEnum -- convert to ascii values zipWith(-)=<<tail -- build differences of neighbor elements q.q -- apply q twice on every element sum -- sum it up ``` Edit: @Damien saved one byte. Thanks! [Answer] # [MATL](http://github.com/lmendo/MATL), ~~14~~, 10 bytes ``` dt_v26\X<s ``` [Try it online!](http://matl.tryitonline.net/#code=ZHRfdjI2XFg8cw&input=J3ZhbGxleXMn) *Thanks [@Suever](https://codegolf.stackexchange.com/users/51939/suever) for saving 4 bytes!* Explanation: ``` d % Take the difference between consecutive characters t_ % Make a copy of this array, and take the negative of each element v % Join these two arrays together into a matrix with height 2 26\ % Mod 26 of each element X< % Grab the minimum of each column s % Sum these. Implicitly print ``` Previous version: ``` d26\t13>26*-|s ``` [Answer] ## Python 3, ~~69~~ 68 bytes ``` lambda s:sum([13-abs(13-abs(ord(a)-ord(b)))for a,b in zip(s,s[1:])]) ``` Breakdown: ``` lambda s: sum( ) [ for a,b in zip(s,s[1:])] 13-abs(13-abs(ord(a)-ord(b))) ``` [Answer] # Java, ~~126~~ ~~120~~ 117 bytes ``` int f(String s){byte[]z=s.getBytes();int r=0,i=0,e;for(;++i<z.length;r+=(e=(26+z[i]-z[i-1])%26)<14?e:26-e);return r;} ``` Thanks to @KevinCruijssen for pointing out a bug in the original version and suggesting to make the for-loop empty. The use of `(26 + z[i] - z[i - 1]) % 26)` is inspired from a comment by @Neil on another answer. `(26 + ...)%26` serves the same purpose as `Math.abs(...)` because of `...? e : 26 - e`. **Ungolfed**: ``` int f(String s) { byte[]z = s.getBytes(); int r = 0, i = 0, e; for (; ++i < z.length; r += (e = (26 + z[i] - z[i - 1]) % 26) < 14 ? e : 26 - e); return r; } ``` [Answer] ## JavaScript (ES6), ~~84~~ ~~82~~ 79 bytes Saved 3 bytes thanks to Cyoce: ``` f=([d,...s],p=parseInt,v=(26+p(s[0],36)-p(d,36))%26)=>s[0]?f(s)+(v>13?26-v:v):0 ``` **Explanation:** ``` f=( [d,...s], //Destructured input, separates first char from the rest p=parseInt, //p used as parseInt v=(26+p(s[0],36)-p(d,36))%26 //v is the absolute value of the difference using base 36 to get number from char ) )=> s[0]? //If there is at least two char in the input f(s) //sum recursive call + //added to (v>13?26-v:v) //the current shortest path : //else 0 //ends the recursion, returns 0 ``` **Example:** Call: `f('golf')` Output: `17` --- Previous solutions : 82 bytes thanks to Neil: ``` f=([d,...s],v=(26+parseInt(s[0],36)-parseInt(d,36))%26)=>s[0]?f(s)+(v>13?26-v:v):0 ``` 84 bytes: ``` f=([d,...s],v=Math.abs(parseInt(s[0],36)-parseInt(d,36)))=>s[0]?f(s)+(v>13?26-v:v):0 ``` [Answer] ## Ruby, 73 bytes ``` ->x{eval x.chars.each_cons(2).map{|a,b|13-(13-(a.ord-b.ord).abs).abs}*?+} ``` [Answer] # PHP, 93 Bytes ``` for(;++$i<strlen($s=$argv[1]);)$r+=13<($a=abs(ord($s[$i-1])-ord($s[$i])))?$a=26-$a:$a;echo$r; ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 12 bytes ``` SÇ¥YFÄ5Ø-}(O ``` **Explanation** ``` SÇ # convert to list of ascii values ¥ # take delta's YF } # 2 times do Ä5Ø- # for x in list: abs(x) - 13 (O # negate and sum ``` [Try it online!](http://05ab1e.tryitonline.net/#code=U8OHwqVZRsOENcOYLX0oTw&input=dmFsbGV5cw) [Answer] # Perl, 46 bytes Includes +3 for `-p` (code contains `'`) Give input on STDIN without final newline: ``` echo -n zaza | stringd.pl ``` `stringd.pl`: ``` #!/usr/bin/perl -p s%.%$\+=13-abs 13-abs ord($&)-ord$'.$&%eg}{ ``` [Answer] ## Racket 119 bytes ``` (λ(s)(for/sum((i(sub1(string-length s))))(abs(-(char->integer (string-ref s i))(char->integer(string-ref s(+ 1 i))))))) ``` Testing: ``` (f "golf") ``` Output: ``` 17 ``` Detailed version: ``` (define(f s) (for/sum((i(sub1(string-length s)))) (abs(-(char->integer(string-ref s i)) (char->integer(string-ref s(+ 1 i))))))) ``` [Answer] # C#, 87 85 bytes **Improved** solution - *replaced Math.Abs() with the add & modulo trick to save 2 bytes:* ``` s=>{int l=0,d,i=0;for(;i<s.Length-1;)l+=(d=(s[i]-s[++i]+26)%26)>13?26-d:d;return l;}; ``` **Initial** solution: ``` s=>{int l=0,d,i=0;for(;i<s.Length-1;)l+=(d=Math.Abs(s[i]-s[++i]))>13?26-d:d;return l;}; ``` **[Try it online!](https://ideone.com/4KtV7g)** Full source, including test cases: ``` using System; namespace StringDistance { class Program { static void Main(string[] args) { Func<string,int>f= s=>{int l=0,d,i=0;for(;i<s.Length-1;)l+=(d=Math.Abs(s[i]-s[++i]))>13?26-d:d;return l;}; Console.WriteLine(f("golf")); //17 Console.WriteLine(f("aa")); //0 Console.WriteLine(f("stack")); //18 Console.WriteLine(f("zaza")); //3 Console.WriteLine(f("valleys"));//35 } } } ``` [Answer] # Actually, 21 bytes Based partially on [cia\_rana's Ruby answer](https://codegolf.stackexchange.com/a/93654/47581). There was a bug with `O` (in this case, map ord() over a string) where it would not work with `d` (dequeue bottom element) and `p` (pop first element) without first converting the map to a list with `#`. This bug has been fixed, but as that fix is newer than this challenge, so I've kept `#` in. **Edit:** And the byte count has been wrong since September. Whoops. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=TyM7ZFhAcFjimYAtYEE7w7psLWttYE3Oow&input=InZhbGxleXMi) ``` O#;dX@pX♀-`A;úl-km`MΣ ``` **Ungolfing** ``` Implicit input string. The string should already be enclosed in quotation marks. O# Map ord() over the string and convert the map to a list. Call it ords. ; Duplicate ords. dX Dequeue the last element and discard it. @ Swap the with the duplicate ords. pX Pop the last element and discard it. Stack: ords[:-1], ords[1:] ♀- Subtract each element of the second list from each element of the first list. This subtraction is equivalent to getting the first differences of ords. `...`M Map the following function over the first differences. Variable i. A; abs(i) and duplicate. úl Push the lowercase alphabet and get its length. A golfy way to push 26. - 26-i k Pop all elements from stack and convert to list. Stack: [i, 26-i] m min([i, 26-i]) Σ Sum the result of the map. Implicit return. ``` [Answer] # Java 7,128 bytes ``` int f(String s){char[]c=s.toCharArray();int t=0;for(int i=1,a;i<c.length;a=Math.abs(c[i]-c[i++-1]),t+=26-a<a?26-a:a);return t;} ``` # Ungolfed ``` int f(String s){ char[]c=s.toCharArray(); int t=0; for(int i=1,a; i<c.length; a=Math.abs(c[i]-c[i++-1]),t+=26-a<a?26-a:a); return t; } ``` [Answer] # Pyth, 20 bytes ``` Lm-13.adbsyy-M.:CMQ2 ``` A program that takes input of a quoted string on STDIN and prints the result. [Try it online](https://pyth.herokuapp.com/?code=Lm-13.adbsyy-M.%3ACMQ2&test_suite=1&test_suite_input=%22aa%22%0A%22stack%22%0A%22zaza%22%0A%22valleys%22&debug=0) **How it works** ``` Lm-13.adbsyy-M.:CMQ2 Program. Input: Q L def y(b) -> m b Map over b with variable d: -13 13- .ad abs(d) CMQ Map code-point over Q .: 2 All length 2 sublists of that -M Map subtraction over that yy y(y(that)) s Sum of that Implicitly print ``` [Answer] ## dc + od, 65 bytes ``` od -tuC|dc -e'?dsN0sT[lNrdsNr-d*vdD[26-]sS<Sd*vlT+sTd0<R]dsRxlTp' ``` **Explanation:** Because in *dc* you can't access a string's characters, I used *od* to get the ASCII values. These will be processed in reverse order from the stack (LIFO container) like so: ``` dsN0sT # initialize N (neighbor) = top ASCII value, and T (total) = 0 [lNrdsNr- # loop 'R': calculate difference between current value and N, #updating N (on the first iteration the difference is 0) d*vdD[26-]sS<S # get absolute value (d*v), push 13 (D) and call 'S' to subtract #26 if the difference is greater than 13 d*vlT+sT # get absolute value again and add it to T d0<R]dsR # repeat loop for the rest of the ASCII values xlTp # the main: call 'R' and print T at the end ``` **Run:** ``` echo -n "golf" | ./string_distance.sh ``` **Output:** ``` 17 ``` [Answer] # C, ~~82 86 83~~ 76 bytes ``` t,u;f(char*s){for(t=0;*++s;u=*s-s[-1],t+=(u=u<0?-u:u)>13?26-u:u);return t;} ``` Assumes input string is at least one character long. This doesn't require `#include<stdlib.h>` Edit: Argh, sequence points! [Try it on Ideone](https://ideone.com/mLjkOm) [Answer] # C, 70 bytes ~~76 bytes~~ ``` k,i;f(char *s){for(i=0;*++s;i+=(k=abs(*s-s[-1]))>13?26-k:k);return i;} ``` [Answer] # Scala, 68 bytes ``` def f(s:String)=(for(i<-0 to s.length-2)yield (s(i)-s(i+1)).abs).sum ``` Criticism is welcome. [Answer] # C#, 217 bytes Golfed: ``` IEnumerable<int>g(string k){Func<Char,int>x=(c)=>int.Parse(""+Convert.ToByte(c))-97;for(int i=0;i<k.Length-1;i++){var f=x(k[i]);var s=x(k[i+1]);var d=Math.Abs(f-s);yield return d>13?26-Math.Max(f,s)+Math.Min(f,s):d;}} ``` Ungolfed: ``` IEnumerable<int> g(string k) { Func<Char, int> x = (c) => int.Parse("" + Convert.ToByte(c)) - 97; for (int i = 0; i < k.Length - 1; i++) { var f = x(k[i]); var s = x(k[i + 1]); var d = Math.Abs(f - s); yield return d > 13 ? 26 - Math.Max(f, s) + Math.Min(f, s) : d; } } ``` Output: ``` aa: 0 stack: 18 zaza: 3 valleys: 35 ``` 'a' is 97 when converted to bytes, so 97 is subtracted from each one. If the difference is greater than 13 (ie, half of the alphabet), then subtract the differences between each character (byte value) from 26. A last minute addition of "yield return" saved me a few bytes! [Answer] # Python 3, 126 bytes With list *in*comprehension. ``` d=input() print(sum([min(abs(x-y),x+26-y)for x,y in[map(lambda x:(ord(x)-97),sorted(d[i:i+2]))for i in range(len(d))][:-1]])) ``` [Answer] # PHP, 79 bytes ``` for($w=$argv[1];$w[++$i];)$s+=13-abs(13-abs(ord($w[$i-1])-ord($w[$i])));echo$s; ``` [Answer] # Java, 109 bytes ``` int f(String s){int x=0,t,a=0;for(byte b:s.getBytes()){t=a>0?(a-b+26)%26:0;t=t>13?26-t:t;x+=t;a=b;}return x; ``` ]
[Question] [ ## Goal The goal of this challenge is: given a string as input, remove duplicate pairs of letters, if the second item in the pair is of opposite capitalization. (i.e. uppercase becomes lowercase and vice-versa). Pairs should be replaced from left to right. For example, `aAa` should become `aa` and not `aA`. [[![examples](https://i.stack.imgur.com/8NhxA.png)](https://i.stack.imgur.com/8NhxA.png)](https://docs.google.com/document/d/15ssImRglljvwauUm8JhmCuzr-l79o4pVF94mDiTFUZg/edit?usp=sharing) ## Inputs & outputs: ``` Input: Output: bBaAdD bad NniIcCeE Nice Tt eE Ss tT T e S t sS Ee tT s E t 1!1!1sStT! 1!1!1st! nN00bB n00b (eE.gG.) (e.g.) Hh3lL|@! H3l|@! Aaa Aa aaaaa aaaaa aaAaa aaaa ``` The input consists of printable ASCII symbols. *You shouldn't remove duplicated digits or other non-letter characters.* ## Acknowledgement This challenge is the opposite of @nicael 's ["Duplicate & switch case"](https://codegolf.stackexchange.com/q/84943/15214). Can you reverse it? Thank you for [all contributors](https://codegolf.meta.stackexchange.com/a/9552/15214) from the sandbox! ## Catalogue The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the snippet: ``` ## [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` <style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><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="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{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><script>var QUESTION_ID = 85509; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 36670; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "//api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "//api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(42), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script> ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṛŒsḟḟȧµ\ ``` [Try it online!](http://jelly.tryitonline.net/#code=4bmbxZJz4bif4bifyKfCtVw&input=&args=J05uaUljQ2VFJw) or [verify all test cases](http://jelly.tryitonline.net/#code=4bmbxZJz4bif4bifyKfCtVwKw4figqxq4oG3&input=&args=J2JCYUFkRCcsICdObmlJY0NlRScsICdUdCBlRSBTcyB0VCcsICdzUyBFZSB0VCcsICcxITEhMXNTdFQhJywgJ25OMDBiQicsICcoZUUuZ0cuKScsICdIaDNsTHxAIScsICdBYWEnLCAnYWFhYWEnLCAnYWFBYWEn). ### How it works ``` ṛŒsḟḟȧµ\ Main link. Argument: s (string) µ Convert all links to the left into a chain (unknown arity) and begin a new chain. \ Do a cumulative reduce by the chain to the left. Left argument: r (previous result or first character) Right argument: c (next character) ṛ Set the return value to c. Œs Swap c's case. ḟ Remove c from r (if present). This yields an empty string if c and r are identical (repeated letter with the same case or non-letter) and r otherwise. Note that r will be empty if the previous character has been removed. ḟ Remove the resulting characters (if any) from c with swapped case. This yields c with swapped case if the result to the right does not contain c; otherwise, it yields the empty string. ȧ Flat logical AND with c. Replace swapped case c with c; do not modify an empty string. ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 18 bytes ``` (.)(?!\1)(?i)\1 $1 ``` [Try it online!](http://retina.tryitonline.net/#code=KC4pKD8hXDEpKD9pKVwxCiQx&input=YkJhQWRECk5uaUljQ2VFClR0IGVFIFNzIHRUCnNTIEVlIHRUCjEhMSExc1N0VCEKbk4wMGJCCihlRS5nRy4pCkhoM2xMfEAhCkFhYQphYWFhYQphYUFhYQ) ### Explanation This a single (and fairly simple) substitution which matches the relevant pairs and replaces them with only the first character. The pairs are matched by activating case-insensitivity halfway through the pattern: ``` (.) # Match a character and capture it into group 1. (?!\1) # Use a negative lookahead to ensure that the next character *isn't* the same # as the character we just captured. This doesn't advance the position of the # regex engine's "cursor". (?i) # Now activate case-insensitivity for the remainder of the pattern. \1 # Match the second character with a backreference to the first. With the i # modifier activated, this will match if the two characters only differ # by case. ``` The substitution simply writes back the character we already captured in group `1` anyway. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 44 bytes ``` .v|.l1|hA,?bhB(@uA;A@uB),?bb&~b.hA|?b&~b.h~h? ``` Brachylog has no regular expressions. ### Explanation ``` .v Input = Output = "" | OR .l1 Input = Output = string of one character | OR hA, A is the first char or the Input ?bhB B is the second char of the Input ( @uA B uppercased is A ; OR A@uB A uppercased is B ), ?bb& Call recursively on Input minus the first two elements ~b.hA Output is the result of that call with A appended before it | OR b& Call recursively on Input minus the first element ~b.h~h? Output is the result of that call with the first element of Input appended before it ``` [Answer] # C#, ~~87~~ 75 bytes ``` s=>System.Text.RegularExpressions.Regex.Replace(s,@"(.)(?!\1)(?i)\1","$1"); ``` With the [mighty regex](https://codegolf.stackexchange.com/a/85510/15214) from Martin Ender. C# lambda where the input and the output are `string`. 12 bytes saved by Martin Ender and TùxCräftîñg. --- # C#, ~~141~~ 134 bytes ``` s=>{var r="";for(int i=0,l=s.Length;i<l;i++){var c=s[i];r+=c;if(char.IsLetter(c)&i+1<l&&(c|32)==(s[i+1]|32)&c!=s[i+1])i++;}return r;}; ``` C# lambda where the input and the output are `string`. The algorithm is naive. This is the one I use as reference. Code: ``` s=>{ var r = ""; for(int i = 0; i < s.Length; i++) { r+=s[i]; if (char.IsLetter(s[i]) & i+1 < s.Length) if (char.ToLower(s[i])==char.ToLower(s[i+1]) & char.IsLower(s[i])!=char.IsLower(s[i+1])) i += 1; } return r; }; ``` 7 bytes thanks to Martin Ender! --- [Try them online!](https://dotnetfiddle.net/bmsVVY) [Answer] ## Perl, ~~40~~ 24+1=25 bytes Use the same regex as Martin. Use the `-p` flag ``` s/(.)(?!\1)(?i)\1/\1/g ``` Test it on [ideone](http://ideone.com/BvvFDQ) [Answer] # Python 3, ~~64~~ ~~59~~ 58 bytes ``` r=input() for c in r:r=c[c.swapcase()==r!=c:];print(end=r) ``` Test it on [Ideone](http://ideone.com/QSZNDd). [Answer] # C, 66 bytes ``` l;main(c){for(;~(c=getchar());)l=l^c^32|!isalpha(c)?putchar(c):0;} ``` [Answer] # Pyth, ~~24~~ 20 bytes 4 bytes thanks to @Jakube. This still uses regex, but just for tokenizing. ``` shM:zj\|+s_BVGrG1\.1 ``` [Test suite.](http://pyth.herokuapp.com/?code=shM%3Azj%5C%7C%2Bs_BVGrG1%5C.1&test_suite=1&test_suite_input=bBaAdD%0ANniIcCeE%0ATt+eE+Ss+tT%0AsS+Ee+tT%0A1%211%211sStT%21%0AnN00bB%0A%28eE.gG.%29%0AHh3lL%7C%40%21%0AAaa%0Aaaaaa%0AaaAaa&debug=0) ``` shM:zj\|+s_BVGrG1\.1 input as z s_BVGrG1 generate ['aA', 'Aa', 'bB', 'Bb', ..., 'zZ', 'Zz'] + \. add "." to the back of the array j\| insert "|" between every element of the array, forming a new long string, which will be our tokenizer: "aA|Aa|bB|Bb|cC|Cc|...|yY|Yy|zZ|Zz|." the "." at the end is to capture the remaining characters :z 1 return all matches of z against that regex this is effectively a tokenizer hM take the first character of each token s join all the transformed tokens together, and then implicitly print to STDOUT. ``` * 24-byte version [here](https://codegolf.stackexchange.com/revisions/85514/2). [Answer] ## JavaScript (ES6), ~~71~~ 68 bytes ``` s=>s.replace(/./g,c=>l=c!=l&&c>'0'&&parseInt(c+l,36)%37<1?'':c,l='') ``` Explanation: ``` s=>s.replace(/./g,c=> Loop over each character in the string l= Save result for next loop c!=l&& Check whether characters differ c>'@'&& Check minimum character code parseInt(c+l,36)%37<1 Check if characters have same value ?'':c, If so then delete this character l='') Initial empty previous character ``` Given `c>'@'`, the only way for `parseInt(c+l,36)` to be a multiple of 37 is for both `c` and `l` to have the same value (they can't have zero value because we excluded space and zero, and if they have no value then the expression will evaluate to `NaN<1` which is false) is for them to be the same letter. However, we know that they're not the same letter case-sensitively, so they must be the same case-insensitively. Note that this algorithm only works if I check every character; if I try to simplify it by matching on letters it will then fail on things like `"a+A"`. Edit: Saved 3 bytes thanks to @edc65. [Answer] # [MATL](https://github.com/lmendo/MATL), 21 bytes ``` "Kk@k=K@XK=>?4XKx}K&h ``` [Try it online!](http://matl.tryitonline.net/#code=IktrQGs9S0BYSz0-PzRYS3h9SyZo&input=J2JCYUFkRCc). Or [verify all test cases](http://matl.tryitonline.net/#code=YCAgICAgICAgICAgICAgICAgICAgICAgICAlIFdoaWxlIGxvb3AgdG8gcmVhZCBhbGwgaW5wdXRzCiJLa0BrPUtAWEs9Pj80WEt4fUsmaCAgICAgJSBBY3R1YWwgY29kZQpdXURUICAgICAgICAgICAgICAgICAgICAgICUgRW5kIGlmLCBlbmQgZm9yIGxvb3AsIGRpc3BsYXksIGVuZCB3aGlsZSBsb29w&input=J2JCYUFkRCcKJ05uaUljQ2VFJwonVHQgZUUgU3MgdFQnCidzUyBFZSB0VCcKJzEhMSExc1N0VCEnCiduTjAwYkInCicoZUUuZ0cuKScKJ0hoM2xMfEAhJwonQWFhJwonYWFhYWEnCidhYUFhYSc). ### Explanation This processes each character in a loop. Each iteration compares the current character with the previous character. The latter is stored in clipboard K, which is initiallized to `4` by default. The current character is compared with the previous one twice: first case-insensitively and then case sensitively. The current character should be deleted if and only if the first comparison was true and the second was false. Note that, since clipboard K initially contains 4, the first character will always be kept. If the current character is deleted clipboard K should be reset (so the next character will be kept); otherwise it should be updated with the current character. ``` " % Take input string implicitly. For each char from this string: K % Push previous char, initiallized to number 4 k % Convert to lower case. For numbers it rounds down @ % Push current char k % Convert to lower case. = % True if current and previous chars are (case-insensitively) equal K % Push previous char @ % Push current char XK % Update clipboard K with current char. This doesn't affect the stack = % True if current and previous chars are (case-sensitively) equal >? % If first comparison was true and second was false 4XKx % Reset clipboard K to 4 } % Else K % Push previous char &h % Concatenate horizontally to gradually build the output string ``` [Answer] # C, ~~129~~ ~~127~~ ~~125~~ ~~107~~ ~~106~~ ~~105~~ ~~93~~ ~~92~~ ~~90~~ ~~88~~ ~~85~~ ~~78~~ 73 bytes ``` c;d;f(char*s){for(;c=*s;s+=isalpha(putchar(c))*d*!((d^=c)&95)&&d)d=*++s;} ``` A C port of my [C# answer](https://codegolf.stackexchange.com/a/85512/15214). My C may be a bit bad. I don't use the language a lot anymore. Any help is welcome! * 1 byte saved thanks to Lowjacker's [trick](https://codegolf.stackexchange.com/a/2240/15214): `a!=b` = `a^b` * 1 byte saved thanks to Walpen's [trick](https://codegolf.stackexchange.com/questions/2203/tips-for-golfing-in-c#comment13149_2240): `a&&b` = `a*b` * 12 bytes saved by Lynn's [trick](https://codegolf.stackexchange.com/a/84965/15214) and inspired here by TùxCräftîñg * 1 byte saved thanks to Joey Adams's [trick](https://codegolf.stackexchange.com/a/2230/15214) and inspired here by orlp: Moving variable to global * 2 bytes saved by SEJPM by resolving my `(c|32)==(d|32)` bitwise problem * 5 bytes saved by Pietu1998 * 5 bytes saved by ceilingcat Code: ``` c;d;f(char*s) { for(;putchar(c=*s);) s+=isalpha(c)*(d=*++s)&&(!((c^d)&95)&&c^d); } ``` [Try it online!](https://tio.run/##bc1Ba4MwFAfwc/0U0YMkkbWOskMJQuMm22D0oufBaxJroEuLSXfp@tmdFSzUhnd5f3783xNPOyG6TjDJaiwaaKkl5/rQYiYyaplNMm1hf2wAH0/u6lgQQiUNMZbfmSDx6oXEsSQyo0li2aXTxqEf0Ab/HrQk6BzMahxtc@DyLSIsmPVnLI6GtYeN0Z/iVRUeqhxSBSotcpVHbYkK5afnsB9buir0oNmk6Tb3AFbFfPc@Jx76aJb7r7/19BwaEDj0AS0WCGBaBD7SVDiMLf7YAuD81ryGx683v8eB8pHyO2qVO7UGpSy4dP8 "C (gcc) – Try It Online") [Answer] # Java 7, 66 bytes ``` String c(String i){return i.replaceAll("(.)(?!\\1)(?i)\\1","$1");} ``` Used [Martin Ender's regex from his Retina answer](https://codegolf.stackexchange.com/a/85510/52210). **Ungolfed & test code:** [Try it here.](https://ideone.com/DNjdH1) ``` class Main{ static String c(String i){ return i.replaceAll("(.)(?!\\1)(?i)\\1", "$1"); } public static void main(String[] a){ System.out.println(c("bBaAdD")); System.out.println(c("NniIcCeE")); System.out.println(c("Tt eE Ss tT")); System.out.println(c("sS Ee tT")); System.out.println(c("1!1!1sStT!")); System.out.println(c("nN00bB")); System.out.println(c("(eE.gG.)")); System.out.println(c("Hh3lL|@!")); System.out.println(c("Aaa")); System.out.println(c("aaaaa")); System.out.println(c("aaAaa")); } } ``` **Output:** ``` bad Nice T e S t s E t 1!1!1st! n00b (e.g.) H3l|@! Aa aaaaa aaaa ``` [Answer] # JavaScript (ES6), ~~61 bytes~~, 57 Bytes `s=>s.replace(/./g,c=>l=c!=l&/(.)\1/i.test(l+c)?'':c,l='')` Thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil) for saving 5 bytes. [Answer] # JavaScript (ES6) 70 ``` (s,p,q)=>s.replace(/./g,c=>p!=c&q===(d=parseInt(c,36))?q='':(q=d,p=c)) ``` ``` f=(s,p,q)=>s.replace(/./g,c=>p!=c&q===(d=parseInt(c,36))?q='':(q=d,p=c)) ; [['bBaAdD','bad'] ,['NniIcCeE','Nice'] ,['Tt eE Ss tT','T e S t'] ,['sS Ee tT','s E t'] ,['1!1!1sStT!','1!1!1st!'] ,['nN00bB','n00b'] ,['(eE.gG.)','(e.g.)'] ,['Hh3lL|@!','H3l|@!'] ,['Aaa','Aa'] ,['aaaaa','aaaaa'] ,['aaAaa','aaaa']] .forEach( x=> { var i=x[0],k=x[1],r=f(i) console.log(k==r?'OK':'KO',i,r) } ) ``` [Answer] ## Convex, 18 bytes ``` V±V.+'.+'|*\ô{0=}% ``` [Try it online!](http://convex.tryitonline.net/#code=VsKxVi4rJy4rJ3wqXMO0ezA9fSU&input=&args=YkJhQWRE) Similar approach as [@Leaky Nun's Pyth answer](https://codegolf.stackexchange.com/a/85514/36670). It constructs the array `["aA" "bB" ... "zZ" "Aa" "Bb" ... "Zz" '.]`, joins by the `'|` character, and tests the input based on that regex. Then it takes the first character of each match. [Answer] Haskell, 70 Bytes ``` import Data.Char f (a:b:c)|g a/=g b=a:f c|0>1=a:b:f c f a=a g=isUpper ``` ]
[Question] [ **Monday Mini-Golf:** A series of short [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenges, posted (hopefully!) every Monday. A **Fibonacci-like sequence** is obtained using the same method as the famous [Fibonacci sequence](https://en.wikipedia.org/wiki/Fibonacci_number); that is, each number *F(n)* is found by adding the previous two numbers in the sequence (*F(n) = F(n-1) + F(n-2)*), or by subtracting the next two numbers (*F(n) = F(n+2) - F(n+1)*). The main difference is that these sequences can start with any two numbers. The zero-indexing of these sequences is disputable, but for now, we're going to use this rule: * The 0th number in a Fibonacci-like sequence is the last number which is smaller than the preceding number. As an example, the Fibonacci sequence could be written as `1, 0, 1, 1, 2, 3, 5...`, so the 0th number in the sequence is the lone `0`. # Challenge The goal of the challenge is to write a program or function that takes in three integers, in any format: * *A* and *B*, the two numbers with which to start generating a sequence. * *N*, the length of the resulting sequence to output. And outputs the first *N* numbers of the sequence, starting at the 0th. # Details * *A*, *B*, and *N* may be taken in any order and format, as long as they are visibly separated. If you use a different order/format, please specify what it is. * You may assume that *A*, *B*, and *N* are always positive integers. * You may assume that *N* is no more than 100, and the resulting sequence will not contain `x >= 2^31`. * If *A* is larger than *B*, then *B* is the 0th number in the sequence. * The output must be separated by spaces, commas, and/or newlines. * A trailing space or newline is allowed, but *not* a trailing comma. # Test-cases ### Example 1: ``` 8 13 10 ``` Working backward from `8 13` until we find a number larger than the previous, we get `13 8 5 3 2 1 1 0 1`. Thus, `0` is the 0th number in this sequence. Working forward from this, we print out `0` and the next 9 members: ``` 0 1 1 2 3 5 8 13 21 34 ``` ### Example 2: ``` 23 37 5 ``` Again working backward to find the 0th number, we find `37 23 14 9 5 4 1 3`. The 0th number this time is `1`, so we print it out, along with the next 4 members: ``` 1 4 5 9 14 ``` ### Example 3: ``` 4 3 8 ``` With this one, we don't have to work backward to find the 0th number, because `3` is smaller than `4`: ``` 3 7 10 17 27 44 71 115 ``` ### Example 4: ``` 29 47 11 ``` Result: ``` 1 3 4 7 11 18 29 47 76 123 199 ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest valid code in bytes wins. Tiebreaker goes to earlier posted submission. ~~The winner will be chosen next Monday, Sep 28. Good luck!~~ **Edit:** Congrats to your winner, @Jakube, using Pyth for an amazing **23 bytes!** [Answer] # Pyth, 23 bytes ``` AQWgHGA,-HGG)VvwHA,H+GH ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?input=%5B8%2C%2013%5D%0A10&test_suite=0&test_suite_input=%5B8%2C%2013%5D%0A10%0A%5B23%2C%2037%5D%0A5%0A%5B4%2C%203%5D%0A8%0A%5B29%2C%2047%5D%0A11&code=AQWgHGA%2C-HGG%29VvwHA%2CH%2BGH&input_size=2) or [Test Suite](http://pyth.herokuapp.com/?input=%5B8%2C%2013%5D%0A10&test_suite=1&test_suite_input=%5B8%2C%2013%5D%0A10%0A%5B23%2C%2037%5D%0A5%0A%5B4%2C%203%5D%0A8%0A%5B29%2C%2047%5D%0A11&code=AQWgHGA%2C-HGG%29VvwHA%2CH%2BGH&input_size=2) Quite unusual style of Pyth programming. Sometimes functional programming has its downsides. ### Explanation: ``` AQWgHGA,-HGG)VvwHA,H+GH Q = input list of the two starting numbers AQ G, H = Q (unpacking Q) WgHG while H >= G: A,-HGG G, H = [H - G, G] ) end while vw read a number from input V for N in range(^): H print H A,H+GH G, H = [H, G + H] ``` [Answer] # [Retina](https://github.com/mbuettner/retina), ~~65~~ 54 bytes ``` +`(1*),\1(1*) $2,$1 +`(1*)(,1*);1\B $1$2$2$1; ^1*,|;1 <empty> ``` Here, `<empty>` represents an empty trailing line. Run the code as a single file with the `-s` flag. The input format is ``` A,B;N ``` where the numbers are [represented in unary](https://codegolf.meta.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary). The output is a comma-separated list, also in unary. For instance: ``` 8 13 10 ``` would be ``` 11111111,1111111111111;1111111111 ``` and yield ``` ,1,1,11,111,11111,11111111,1111111111111,111111111111111111111,1111111111111111111111111111111111 ``` ## Explanation ``` +`(1*),\1(1*) $2,$1 ``` First, we reduce `A` and `B` to the 0th and -1st element. The `+` tells Retina to keep repeating this regex substitution until either the regex stops matching or the substitution doesn't modify the string. The regex captures `A` into group 1 with `(1*)`, and then makes sure that `B` is at least as big as `A` while capturing `B-A` with `\1(1*)` into group 2. This ensures that this loop terminates once `A>B`. The substitution simply turns `A,B` into `B-A,A` by setting the match to `$2,$1`. ``` +`(1*)(,1*);1\B $1$2$2$1; ``` Now we've already got the first number of the required output in the string (as well as the one before it, which we'll need to get rid off later). This substitution now adds another number as the sum of the last two numbers while taking a `1` from `N`. Because we already have one number we want this to happen only `N-1`. We do this by ensuring with `\B` that there is still at least `;11` at the end of the string. If we call the last two values of the sequence `C` and `D`, then the regex captures `C` into group 1 and `,D` into group two. We write those back with `$1$2`. Then we also write `$2$1` which translates to `,D+C`. Note that we *don't* write back the single `1` we matched in `N`, thereby decrementing it. ``` ^1*,|;1 <empty> ``` Finally, we need to get rid of -1st element of the sequence, as well the leftover `;1` from `N`, which we simply do by matching either of those and replacing it with the empty string. [Answer] # Python 2, ~~93~~ ~~87~~ ~~67~~ ~~61~~ 60 bytes ``` i,j,l=input() while j/i:i,j=j-i,i exec"i,j=j,i+j;print i;"*l ``` Gets the input (as a literal python list `[8,10,13]`) Works out the 0th term Then prints out the sequence of additions until the length has been reached [Answer] # CJam, ~~26~~ 23 bytes *Thanks to Dennis for saving 3 bytes.* ``` q~{_@\-_g)}g\@{_@+_p}*t ``` Takes input in order `N B A` (separated by any kind of white space). Prints the result as a newline-separated list and [terminates with an error](http://meta.codegolf.stackexchange.com/a/4781/8478). [Test it here.](http://cjam.aditsu.net/#code=q~%7B_2%24%3E%7D%7B1%24-%5C%7Dw%40%7B_p_%40%2B%7D*%5D%3B&input=11%2029%2047) ## Explanation This goes one step further when finding the 0th element. That is, it terminates once one of the values is negative. ``` q~ e# Read and evaluate input, pushing N, B and A on the stack. { e# do while... _@\- e# B, A = A, B-A _W> e# Check if A is still non-negative. }g \@ e# Reorder N B A into A B N. { e# Run the following N times... _@+ e# A, B = B, A+B _p e# Print B. }* t e# The last A, B are still on the stack. We remove them by trying to e# execute a ternary operator: it pops the first two values but then e# terminates the program with an error, because there is no third value. ``` [Answer] # [Labyrinth](https://github.com/mbuettner/labyrinth), ~~58~~ ~~54~~ ~~49~~ ~~46~~ 44 bytes *Thanks to Sp3000 for suggesting the use of bitwise negation, which saved two bytes.* ``` ??#"{= ; - @"~~:} ~"" ? "}}:= ( + {{\!: ``` Input format is `B A N`. The output is a newline separated list. # Explanation *(Slightly outdated. The basic idea is still the same, but the layout of the code is different now.)* This uses the same idea as my CJam answer (so credits still go to Dennis): when backtracking the sequence we don't stop until we get a negative value (which leaves us with the -1st and -2nd element of the sequence). Then, we start adding them *before* printing the first value. This uses a couple of nifty Labyrinth golfing tricks. Let's go through the code in sections: ``` ?" } ``` The IP starts on the `?` going right (which reads `A`). On the `"` (a no-op) it hits a dead end, so it turns around, executing the `?` again (reading `B`). Lastly, `}` moves `B` over to the auxiliary stack. The dead end saves a byte over the naive ``` ? ? } ``` Now the loop which finds the beginning of the sequence: ``` )(:{ " - " "`?... =}"" ``` The `)(` (increment-decrement) is a no-op, but it's necessary to ensure that the top of the stack is positive on the junction (such that the IP turns east). `:` duplicates `A`, `{` moves `B` back to the main stack, `-` computes `A-B`. What we really want is `B-A` though, so ``` negates the value. This is now a four-way junction. For negative results, the IP takes a left-turn towards the `?`, reading `N` and moving to the next part of the program. If the result is zero, the IP keeps moving south, takes a turn in the corner, and remains in the loop. If the result is positive, the IP takes a right-turn (west), turns in the corner, and takes another right-turn (west again) so it also remains in the loop. I think this might become a common pattern, to distinguish negative from non-negative (or positive from non-positive) values: ``` v " """>negative non-negative <""" ``` At least I haven't been able to find a more compact/useful layout for this case yet. Anyway, while `A` is non-negative, the loop continue, `}` moves `A` to the auxiliary stack and `=` swaps `A` and `B`. Once `A` is negative, `?` reads `N` and we move into the second loop: ``` }:=+: } ! ?"({{\ ``` We know that `N` is positive, so we can rely on the IP taking a left-turn (north). The loop body is now simply: ``` }}:=+:!\{{( ``` In words: moves both `N` and `A` onto the auxiliary stack. Duplicate `B`, swap the copy with `A` and add `A` to the other copy of `B`. Duplicate it again to print the current value of `B`. Print a newline. Move `B` and `N` back to the main stack and decrement `N`. While `N` is positive, the IP will take a right-turn (north) continuing the loop. Once `N` reaches zero, the code terminates in a rather fancy way: The IP keeps moving straight ahead (west). The `?` tries to read another integer, but we've already reached EOF, so it actually pushes `0` instead. ``` tries negating that, but that's still zero. So the IP still moves west, takes a turn in the corner, and then keeps moving downwards onto the `@` which terminates the program. I wonder if I could place the `@` in an even cheaper position (it currently costs 3 whitespace characters) by turning the three `"` around the ``` into compound no-ops (like `)(`), but I haven't been able to make that work yet. [Answer] # C, ~~105~~ ~~102~~ 100 bytes ``` main(a,b,n,t){for(scanf("%d%d%d",&a,&b,&n);t=b-a,t>=0;a=t)b=a;for(;n--;b=t)t=a+b,printf("%d ",a=b);} ``` *Thanks to @C0deH4cker for golfing off 2 bytes!* Try it online on [Ideone](http://ideone.com/fTsvnb). [Answer] # Matlab / Octave, 115 ~~125~~ bytes ``` function x=f(x,n) while x(2)>=x(1) x=[abs(x(1)-x(2)) x];end x=x([2 1]);for k=1:n-1 x=[x(1)+x(2) x];end x=x(n:-1:1); ``` The function should be called as `f([8 13],10)`. Example (Matlab): ``` >> f([8 13],10) ans = 0 1 1 2 3 5 8 13 21 34 ``` Or [try it online (Octave)](http://ideone.com/or90cq). [Answer] # Haskell, ~~67 65~~ 56 bytes ``` a#b|a>b=b:scanl(+)(a+b)(a#b)|1>0=(b-a)#a n%a=take n.(a#) ``` *Thanks to @nimi for suggestions* This defines a ternary infix function `%`, which is invoked in the format `(n%a)b`, for example: ``` > (10%8)13 [0,1,1,2,3,5,8,13,21,34] ``` ### Explanation The binary infix function `#`, defined on the first line, takes in two integers `a` and `b` and returns the infinite Fibonacci-like sequence where `a` and `b` occur as consecutive elements. ``` a#b -- Define a#b: |a>b= -- if a>b, then a#b is b: -- the sequence that starts with b and scanl(+) (a#b) -- continues with the sums of prefixes of a#b (a+b) -- plus the additional term a+b; |1>0=(b-a)#a -- otherwise, it's (b-a)#a. ``` The function `%` simply takes the first `n` elements of `a#b`. [Answer] # ><>, ~~33~~ 31+1 for -v = 32 bytes ``` &:{:@(?v:}-$& -1;!?:&<$+{oan::$& ``` Input must be pushed on stack using -v since parsing decimal numbers is non-trivial in ><>. ## Explanation : I will represent the stack after each (group of) operation. It starts with [F(n), F(n+1), N] The first lines goes down the serie to its 0th term : ``` & removes N from the stack to put it into a register. [F(n), F(n+1)] :{:@ move the stack and duplicate items to get [F(n+1), F(n), F(n+1), F(n)] (?v compares the two top items of the stack and branch to the second line if F(n+1) < F(n) [F(n+1), F(n)] :} move the stack and duplicate its top to get [F(n), F(n+1), F(n)] - substracts the two top items and put the result on top of the stack [F(n), F(n+1) - F(n)] $ switchs the top two values of the stack. [F(n+1) - F(n), F(n)] & retrieve the value from the register. iteration complete, since [F(n+1) - F(n), F(n), N] can also be read as [F(n-1), F(n), N] ``` The second line goes up the serie until it has printed N terms : ``` < changes the code pointer direction to the left [F(0), F(-1)] & retrieves the stored value back from the stack [F(0), F(-1), N] :?!; copies N to compare it to 0, stops if it is [F(0), F(-1), N] 1- decreases it [F(0), F(-1), N-1] & stores it back [F(0), F(-1)] $:: makes the stack [F(-1), F(0), F(0), F(0)] n{ prints the top of the stack then left shifts it [F(0), F(0), F(-1)] ao displays a line feed (ascii character 0x0a) [F(0), F(0), F(-1)] + adds the two top values [F(0), F(-1) + F(0)] $ switch the two top values. iteration complete since [F(-1) + F(0), F(0)] which can be read as [F(1), F(0)] ``` [Answer] # Java, ~~113~~ ~~78~~ 76 bytes Credit goes to ETHproduction for [providing](https://codegolf.stackexchange.com/a/58493/32700) the algorithm I use in this answer. ``` (a,b,n)->{for(;a<=b;b-=a)a=b-a;for(;n-->0;b+=a,a=b-a)System.out.println(b);} ``` Try [here](http://ideone.com/6B30A9). **Explanation:** ``` (a,b,n)->{ for (;a<=b;b=b-a)a=b-a; //Compute previous terms while a <= b for (;n-->0;b=a+b,a=b-a) //Compute and print next terms while n > 0 System.out.println(b); //Print term } ``` ### Original approach, ~~113~~ 93 bytes Looks more golfy ;) ``` String a(int a,int b,int n){return n<0?a+" "+a(b,a+b,n+1):n>0?a>b?a(b,a+b,-n):a(b-a,a,n):"";} ``` Try it out [here](http://ideone.com/szN4vY). **Explanation:** ``` String a(int a, int b, int n){ return n < 0 ? //If n < 0 a + " " + a(b, a + b, n + 1) //Return a + next terms and increment n. : //Else n > 0 ? //If n > 0 a > b ? //If a > b a(b, a + b, -n) //Negate n and return terms. : //If a <= b a(b - a, a, n) //Generate previous term. : //If n == 0 "" //Return nothing. ; } ``` [Answer] # Javascript (ES6), ~~83~~ ~~73~~ 63 bytes This might have been golfed to the max. We'll see. ``` (a,b,n)=>{while(a<=b)b-=a=b-a;for(;n--;console.log(a=b-a))b+=a} ``` ### Ungolfed: ``` function f(a,b,n) { // repeat until we find the 0th item... while (a <= b) { // if a = 5, b = 8: a = b - a; // a = (8 - 5) = 3 b = b - a; // b = (8 - 3) = 5 } // repeat n times... while (n-- > 0) { // if a = 5, b = 8: b += a; // b = (8 + 5) = 13 a = b - a; // a = (13 - 5) = 8 console.log(a); // print out each item } } ``` [Answer] ## Mathematica 112 Will golf it eventually ``` z[a_, b_, n_] := ( f[0] := Min[a, b]; f[1] := Max[a, b]; f[x_] := f[x - 1] + f[x - 2]; f /@ Range[n] ) ``` [Answer] # CJam, 40 bytes ``` l~:A;{_@_@)<}{_@\-\}w\{A(:A0>}{_p_@+}w\; ``` Baby steps. This is my first CJam program ever, so I'm proud it works at all. It takes input in the same form as in the examples. I've now seen I could reduce it to 33 bytes using the `{ ... }*` construct. ``` l~:A;{_@_@)<}{_@-z\}w\A{_p_@+}*;; ``` And I could even reduce it by one more by using the ternary operator to clean the stack and produce an error. [Answer] # Ruby, 141 bytes ``` def u a,b,n,z="" n<1 ? z.chop : u(b,a+b,n-1,z+"#{a} ") end def d a,b,z=0 a.abs>b ? z : d(b-a,a,[a,b]) end def f a,b,n x,y=d a,b u x,y,n end ``` ## Execution f function produces the desired output, argument names match the variable names from the question ``` f(8,13,10) # returns => "0 1 1 2 3 5 8 13 21 34" ``` ## Nothing clever: * u (*up*) function computes n elements in the fibonacci sequence starting with a,b using recursion * d (*down*) function finds the 0th and 1st element given two end elements using recursion * f (*fibonacci*) function puts the two together [Answer] # Mathematica, 59 bytes ``` If[#>#2,LinearRecurrence[{1,1},#2+{0,#},#3],#0[#2-#,#,#3]]& ``` [Answer] # Ruby, ~~81~~ ~~75~~ 73 ``` a,b,n=23,37,5;while(c=b-a)<a;b,a=a,c;end;p a;[*2..n].map{b=c+a;c,a=a,b;p b} ``` Shortened by 6 Bytes when replacing for-loop with range.map ``` a,b,n=23,37,5;while(c=b-a)<a;b,a=a,c;end;p a;[*2..n].map{p b=c+a;c,a=a,b} ``` Saved another 2 bytes by moving print statement [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` Ḋ;_/Ɗ>/¿+⁹С/Ṗ ``` [Try it online!](https://tio.run/##AS0A0v9qZWxsef//4biKO18vxoo@L8K/K@KBucOQwqEv4bmW////WzQ3LCAyOV3/MTE "Jelly – Try It Online") [Answer] # Common Lisp, 91 bytes ``` (lambda(a b n)(do((x a(- y x))(y b x))((> x y)(dotimes(k n)(print y)(psetf y(+ y x)x y))))) ``` [Try it online!](https://tio.run/##LU3bCoMwDP2VgyBLGYN1dege5r/UVaFMbbF9sC/@umumSSDh5Fw@ow1@p9E5j8EtII0Os4CdcSFqIBXkXYAeCqrGM18VFBpGXqhqSCkEjANl8aQjIoqtzG1wzLvFVhY4XZmYw/TUGX0mkXFEKzTdkLAKQSnDvKnFisT/aKc@0JfJfrFzZNSHPg5IdP2rmMi1H55i/wE) [Answer] ## Pyke, 24 bytes ``` DA/IDA-],X_r)QVDsRe R]); ``` [Try it here!](http://pyke.catbus.co.uk/?code=DA%2FIDA-%5D%2CX_r%29QVDsRe%0AR%5D%29%3B&input=10%0A8%2C13) ]
[Question] [ A number is a Chen prime if it satisfies two conditions: * It is prime itself * Itself plus two is either a prime or a semi-prime. A prime is a number where it has exactly two divisors and those divisors consist of itself and one. A semi-prime is a number which is the product of two primes. (Note that 12 = 2\*2\*3 is not semi-prime, but 25 = 5\*5 is). Your task is to determine if a number is a Chen prime. You should output any truthy value for yes and any falsy value for no. The input will be any integer greater than or equal to one. It may also be taken as a string, character array, or an array or digits. ## Examples: ``` 101 -> truthy 223 -> falsy 233 -> truthy 1 -> falsy ``` This is OEIS [A109611](https://oeis.org/A109611). This is, in part, inspired by [Am I a Sophie Germain prime?](https://codegolf.stackexchange.com/questions/131604/am-i-a-sophie-germain-prime) which, unfortunately, got closed as a duplicate, so I'm posting a somewhat related challenge which isn't a duplicate. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes ``` ṗ+₂ḋl≤2 ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@HO6dqPmpoe7ujOedS5BChgZGwMAA "Brachylog – Try It Online") ### Explanation ``` ṗ Input is prime ḋ The prime factorization of… +₂ … Input + 2… l≤2 … has 2 or less elements ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` p¹ÌÒg3‹* ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/4NDOwz2HJ6UbP2rYqfX/v5GxMQA "05AB1E – Try It Online") ### Explanation ``` p¹ÌÒg3‹* Argument n p Push isPrime(n) ¹ÌÒ Push list of prime factors of (n+2) g3‹ Length of list is lower than 3 * Multiplication of boolean values, 0 if either is 0 (false) ``` [Answer] # Pyth, 10 bytes ``` &P_Q>3lP+2 ``` [Try it online!](https://pyth.herokuapp.com/?code=%26P_Q%3E3lP%2B2&input=233&debug=0) **How?** ``` &P_Q>3lP+2 # input: Q +2 # Q + 2 P # prime factors >3l # length lower than 3? P_Q # Q is prime? & # and both results ``` [Answer] # [ArnoldC](https://lhartikk.github.io/ArnoldC/), 1339 bytes ``` LISTEN TO ME VERY CAREFULLY q I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE p GIVE THESE PEOPLE AIR HEY CHRISTMAS TREE c YOU SET US UP 0 HEY CHRISTMAS TREE d YOU SET US UP 0 HEY CHRISTMAS TREE l YOU SET US UP p STICK AROUND l GET TO THE CHOPPER d HERE IS MY INVITATION p I LET HIM GO l ENOUGH TALK BECAUSE I'M GOING TO SAY PLEASE d BULLSHIT GET TO THE CHOPPER c HERE IS MY INVITATION c GET UP 1 ENOUGH TALK YOU HAVE NO RESPECT FOR LOGIC GET TO THE CHOPPER l HERE IS MY INVITATION l GET DOWN 1 ENOUGH TALK CHILL I'LL BE BACK c HASTA LA VISTA, BABY IT'S SHOWTIME HEY CHRISTMAS TREE p YOU SET US UP 0 GET YOUR ASS TO MARS p DO IT NOW I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY HEY CHRISTMAS TREE n YOU SET US UP 0 GET YOUR ASS TO MARS n DO IT NOW q p HEY CHRISTMAS TREE g YOU SET US UP 42 GET TO THE CHOPPER g HERE IS MY INVITATION n YOU ARE NOT YOU YOU ARE ME 2 ENOUGH TALK BECAUSE I'M GOING TO SAY PLEASE g GET TO THE CHOPPER p HERE IS MY INVITATION p GET UP 2 ENOUGH TALK GET YOUR ASS TO MARS n DO IT NOW q p GET TO THE CHOPPER g HERE IS MY INVITATION 5 LET OFF SOME STEAM BENNET n ENOUGH TALK BECAUSE I'M GOING TO SAY PLEASE g TALK TO THE HAND "t" BULLSHIT TALK TO THE HAND "f" YOU HAVE NO RESPECT FOR LOGIC BULLSHIT TALK TO THE HAND "f" YOU HAVE NO RESPECT FOR LOGIC YOU HAVE BEEN TERMINATED ``` [Try it online!](https://tio.run/##pVRNj9pADL3nV1hcuPTQstsf4ASTsZiM0/EElGPFqlwQy1b9/9QTdouWDSpojxk/@73nj/z8vX/ePW2OR8@aKEASaAhWFHuoMNKi876Hl4IhEM2hly5C5SU50tNHKZIUMLzGGkkSq77yBIei5hVBhhK0JK29IcfCkZV20egaVEiRCDaFJYNSgk6ha@HrGOjpFtDuAnQoNHG1BIzSmcZdUVvIPJoqS5W2pWiFHUUCVmh64LDihIklWC6DN7jjBmqxXArS1Q4S@mVRUoWdGeNpDnKoc1XFHswmalZbWuvUcRqj3Fyh3Axg0/3tHVn25NCaGQQiaUtVgoVE8FJzNVZ/d6X@yf9c1uGCoXLsfcFT76EkKNFaZhpRE4JHWFmL8Ys9l33BaaqgTtaJGxobweHDnDLnsB2oOiwYRjXYXICTWVpbn9cYBhOoywwFhLILlQNZwI@ONIs/bdkZOjTETDf2rmuza8GmoTljIt@PKdvfpmx/VgYvpnOk0vai0uNsbArbK1M46bDrMoqBH96@7fRmd63Zdoz3cHWhX7frPcdNTbjD3vciX40sFqBihuy3go1tVQj2ur/TXYa98bo8/8mfyfmyPkZ/Tf5zLJ/J/RctKf8pKTYcbNnmx@Ps4eEv "ArnoldC – Try It Online") (This is my first post on codegolf.SE, please let me know if this is formatted incorrectly. I realize this byte count is not competitive, this is just for fun.) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` +2ÆfL<3aÆP ``` [Try it online!](https://tio.run/##y0rNyan8/1/b6HBbmo@NceLhtoD/JoYGh9sPT0j7DwA "Jelly – Try It Online") [Answer] # [Python](https://docs.python.org/) with [sympy](http://www.sympy.org), ~~69~~ 56 bytes -13 bytes thanks to alephalpha (by upgrading to sympy 1.1 and using `primeomega(n+2)` to replace `sum(factorint(n+2).values())`) *...taking over from Gryphon's deleted submission.* ``` from sympy import* lambda n:primeomega(n+2)<3*isprime(n) ``` An unnamed function returning `True` for Chen primes and `False` otherwise. Counts the factors of `n+2` by summing its prime factor's multiplicities. Note that `3` is multiplied by `isprime(n)` before the `<` comparison is made, so for non-prime `n` the code tests if `n+2` has less than `0` factors (always yielding `False`), while for prime `n` it checks whether `n+2` is prime or semi-prime. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 29 bytes The `3*isprime(n)` trick is stolen from [Jonathan Allan 's answer](https://codegolf.stackexchange.com/a/131738/9288). ``` n->bigomega(n+2)<3*isprime(n) ``` [Try it online!](https://tio.run/##DYoxDoAgDAC/0jhRhQR0Ff6CCZAOFIL@v3a54e5mXuTalApR2KWH2uilZcPHife10zsX9WIYpY5lGCIEC8F7Cxr4U7OBS4qqD6L8 "Pari/GP – Try It Online") [Answer] # Java 8, ~~85~~ ~~84~~ 83 bytes ``` n->{int a=n+2,b=0,c=0,i=1;for(;i++<n;b+=n%i<1?1:0)c+=a%i<1?1:0;return n>1&b<2&c<3;} ``` -1 bytes thanks to *@OlivierGrégoire* by using an iterative approach instead of recursive. **Explanation:** [Try it here.](https://tio.run/##hY7BbsIwEETv@Yq9FDkyRHFyq2P6BeXCsephbUxlGtaR4yBVKN@eLi09Vkg7h9kZ6c0JL7iJg6fT4XNxPY4jvGKgawEQKPt0ROdhd7MANsbeI4ETHAGVmr8zi2/MmIODHRAYWGizvd4qaEg2a2vqtWMFo/QxJqGDlB1pKw09hU69qOe6dNLgn9HJ5ykR0FatbNesXNfqedEFY4bJ9oy50y4xHODMa8U@p0Afb@@A5e/U/deY/bmKU64GjnJPgionVK3Kn9n/NpqmfdRoHzXujLmYl28) ``` n->{ // Method with integer parameter and boolean return-type int a=n+2, // Start `a` at the input + 2 b=0,c=0, // Start `b` and `c` at 0 i=1; // Start `i` at 1 for(;i++<n; // Loop from 1 to `n` (and raise `i` immediately by 1) b+=n%i<1? // If the input is divisible by `i` 1 // Raise `b` by 1 : // Else: 0) // Leave `b` as is c+=a%i<1? // If the input + 2 is divisible by `i`: 1 // Raise `c` by 1 : // Else: 0; // Leave `c` as is // End of loop (implicit / single-line body) return n>1 // Return if the input is larger than 1 &b<2 // And `b` is now smaller than 2 &c<3; // And `c` is now smaller than 3 } // End of method ``` [Answer] # Mathematica, 28 bytes ``` PrimeQ@#&&PrimeOmega[#+2]<3& ``` [Answer] # JavaScript (ES6), ~~63~~ 61 bytes ``` g=(e,i=e)=>i--<3?1:e%i?g(e,i):g(i)+1 f=e=>e>1&g(e)<2&g(e+2)<3 ``` ``` Test cases:<br><textarea id=i rows=6 oninput="go()">101&#10;223&#10;233&#10;1</textarea><br><pre id=q></pre><script>window.onload=function go(){document.getElementById('q').innerHTML=document.getElementById('i').value.split('\n').map(e=>e+' -> '+f(+e)).join('\n')}</script> ``` Defines a function `f` that takes `n` as argument and returns the result. Im very happy with how `g` turned out; it counts the number of prime factors in a number. *2 bytes saves thanks to Kevin Cruijssen's `&` trick.* ### Ungolfed ``` Ω = (n, // Ω(n) = number of n's prime factors, n > 1. i = n) => // Start iterating from i = n - 1. Since we'll immediately // decrement i, n is used here. --i // Immediately decrement i. < 2 // If i = 0 or i = 1, n is a prime at this point. ? 1 : // Therefore Ω(n) = 1. n % i != 0 ? // If n is not divisible by i, Ω(n, i) // try again with i := i - 1 (immediately decremented, so use i). : Ω(i) + 1 // n is divisible by i. Since we're counting down from n - 1 // and i is the first such number, i is n's largest non-trivial // divisor, and thus n/i is a prime. // Therefore Ω(n) = Ω(i) + Ω(n/i) = Ω(i) + 1. is_chen = n => // An integer n ≥ 1 is a Chen prime if and only if: n > 1 // n > 1, & Ω(n) < 2 // Ω(n) = 1 < 2, i.e. n is a prime, and & Ω(n + 2) < 3 // Ω(n + 2) < 3, i.e. n + 2 is a prime or a semiprime. ``` [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~22~~ ~~20~~ ~~19~~ ~~13~~ 12 bytes ``` U°j ©2¨°Uk l ``` * 6 bytes saved thanks to obarakon's suggestion of a different method. [Test it](http://ethproductions.github.io/japt/?v=1.4.5&code=VbBqIKkyqLBVayBs&input=MTAx) [Answer] # PHP, 64 bytes ``` for($i=$n=$argn+2;--$i;$argn%$i?:$q++)$n%$i?:++$p;echo$p<4^--$q; ``` prints `0` for truthy, other integers for falsy. Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/2b6da5ac5d3bb48251ac49b3fd5f59764af0237d). **breakdown** ``` for($i=$n=$argn+2;--$i; # loop $i from N+1 to 1 $argn%$i?:$q++) # if $i divides N, increment $q $n%$i?:++$p; # if $i divides N+2, increment $p echo$p<4 # $p is 1 for a prime, 3 for a semiprime ^--$q; # $q is 2 for prime; so this is 1^1 (==0) for a Chen Prime ``` **consistent falsy value, 65 bytes:** ``` for($i=$n=2+$k=$argn;--$i;$k%$i?:$q++)$n%$i?:++$p;echo$p<4&$q==2; ``` prints `1` for truthy and `0` for falsy. [Answer] # Regex (ECMAScript), 31 bytes ``` ^(?!((xx+)(\2(xx))*)(\1\4)+$)xx ``` [Try it online!](https://tio.run/##Tc0xT8MwEAXgv9JGSL1riJtUFUOD04mhSwcYKUhWenUOXDuyTRNK@e0hDEhM7@l9w3tTZxVqz23MQssH8idn3@lz8NJSN3kk/dC3ABdZLebDK2ymAH2fIuyXYyLOx1bsV5jeYN8P88UFRXRP0bPVgCIYrgnubrMVYtk1bAjASE/qYNgSIE6l/TAGv7Q0IrSGI8yyGZZ8BLBSC0NWxwar5fXKYad2wLJVPtDWRtDP@QviH9B/sFWxKda/jLHxrku29qwMHyZeWU3rSZKa8ug8lHwvqeQ0xfEw6RPhqSUVgVGcVKwb8Ii1s8EZEsbpcS@/hyIr8jz/AQ) (showing all Chen primes ≤ 1000) Given a string of **n** `x`s this regex will match if and only if **n** is a Chen prime. It asserts that **n** is greater than 2 and that the string is not of the form `((xx+)(\2(xx))*)(\1\4)+` This regex has two meanings, depending on how many times `(\2(xx))` is repeated. When it is repeated 0 times, the regex can be simplified to `(xx+)\1+`, which matches composite numbers. When it is repeated a positive number of times, the regex is equivalent to `((xx+)(\2xx)+)(\1xx)+` That regex requires some explanation, however, I will provide little insight. If you go through the algebra you find that `((xx+)(\2xx)+)(\1xx)+` matches numbers of the form `a*b*c-2` where `a≥4,b≥2,c≥2`. So it will match (almost) whenever **n**+2 has more than 2 prime factors. (i.e neither prime nor semi-prime) Note that it doesn't match 6, 10, 16 or 25, but that this doesn't matter, because they are all composite. So `(?!((xx+)(\2(xx))*)(\1\4)+$)` will match as long as **n** is not composite, and **n**+2 is either prime or semi-prime. Unfortunately this includes 1 (and 0), so we then check that **n** is at least 2 with `xx` A couple of different "31-byters" are: ``` ^xx(?!((x*)(\2xx)+)\1?(\1xx)*$) ^(?!(xx((x*)(\3xx)+))\2?\1*$)xx ``` [Answer] # [Python 3](https://docs.python.org/3/) with SymPy, ~~73~~ 71 bytes ``` lambda n:(sum(factorint(n+2).values())<3)&isprime(n) from sympy import* ``` [Try it online!](https://tio.run/##RctBCsIwEIXhfU@RlcyoSJvZid7ETdQGA53JkKRCTh@rFbp6/B88reUVhZq/3trk@P50Rs6QZwbvHiWmIAXkYPH0dtM8ZkC8EO5C1hR4BMHOp8gmV9ZqAmtMZd/09xqOxsOA2P2zX6HfyFr60jIb0Uq0UPsA "Python 3 – Try It Online") --- This is a more-golfed version of an answer posted here earlier, but it seems to have been deleted. --- Thanks to @JonathanAllan for saving 2 bytes! [Answer] # [PHP](https://php.net/), 87 bytes ``` for($b=($a=$argn)+$i=2;2<$a+$b;)$a%$i?$b%$i?$i++:++$d*$b/=$i:++$c*$a/=$i;echo$c<2&$d<3; ``` [Try it online!](https://tio.run/##Hcg7DoAgEEXR3mWQp1GnMGDnMHEtA36gUeL@E4w2Nye3pFL9WlJpoM95ibHWcD3up0eQHir/HghZHDsPJQQeoC3yivA3Ey1E2EaESZA/xxH6mfeYbkTvOmx@5lpf "PHP – Try It Online") # [PHP](https://php.net/), 87 bytes ``` for(;$n<2;)for($a=$argn+$n++*$i=2;1<$a;)$a%$i?$i++:++$r[$n]*$a/=$i;echo$r[1]<2&$r[2]<3; ``` [Try it online!](https://tio.run/##HYk9CoUwEAZ7jyGf8nQLSV7nbvAgkmIRNWliyP0h/lQzzOSQqyw55AZazuRaY1qux1V@jCSWh1eh7ruERDQiOstGoDxAO8QFkWgmQlmR/AidHCLvW7ieYrzY/qH18udabw "PHP – Try It Online") [Answer] # APL NARS, 23 chars ``` {1≥⍵:0⋄(1=⍴π⍵)∧3>⍴π⍵+2} ``` Here π⍵ return the array of factors of ⍵ different from 1; some test: ``` f←{1≥⍵:0⋄(1=⍴π⍵)∧3>⍴π⍵+2} f 101 1 f 223 0 f 233 1 f 1 0 f ¯10 0 ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~49~~ 41 bytes ``` ->n{/^(.?|((..+)\3+))(\2+|..)$/!~?l*n+=2} ``` [Try it online!](https://tio.run/##BcHRCkAwFADQX7GS7rV2d/E8PsSmePCEllKT8evXOee13LI6Mf3x2AloyABEGn2nEcG3OhNhadU3bPWhXftKLICJGmZG2uf45JTXMYWqSq8ZlYpBfg "Ruby – Try It Online") Thanks H.PWiz for -8 bytes ### How? First thing, get a string of `'l'` repeated n+2 times. Then apply a regex to check if: * Length is 2 or 3 `(.?)(..)` * Length is a composite number plus 2 `((..+)\1)(..)` * Length is a product of at least 3 numbers `((..+)\2)\1+` The 2 regex parts generate a fourth case which doesn't make sense and is safe to ignore: `(.?)\2+`, that resolves to empty string or a single character because `\2` is empty. [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` &<3Lp+2¹ṗ ``` [Try it online!](https://tio.run/##yygtzv7/X83G2KdA2@jQzoc7p////98QAA "Husk – Try It Online") ## Explanation ``` &<3Lp+2¹ṗ ṗ input is prime? & and L Length of p prime factorization of +2¹ input + 2 <3 less than 3? ``` [Answer] # Julia, 59 bytes ``` x->((0∉x%(2:x-1))&(length(find(x->x==0,(x+2)%(2:x)))<=2)) ``` [Answer] # [Pyt](https://github.com/mudkip201/pyt), 11 bytes 3\*isprime(x) stolen from [Jonathan Allan's answer](https://codegolf.stackexchange.com/a/131738/9288) ``` ←Đṗ3*⇹2+ḋŁ> ``` [Answer] # [Haskell](https://www.haskell.org/), 163 bytes ``` p k=last$(not$elem 0(map(mod k)[2..k-1])):[1>2|k<=1] r=round s n=p(r n)||any(\(a,b)->p(r a)&&p(r b))[(n/x,x)|x<-[2..n],n/x==(fromIntegral.r)n/x] c n=p(r n)&&s(n+2) ``` [Try it online!](https://tio.run/##Pcy9DoIwFEDhnae4AyH3RkDBzVB2nwEZyo9K2l6aUhNMePcKi9NJvuG85aJGrUOwoISWi4@RZx@PejRwQSMtmnkARU2Z5yorWqJbU9TlpipRtJETbv7wEC3AwqIDpm2T/MUHyrSjrD5MUpIc7Yga5POarrStVXYMuU13EAKfbjZ39uPLSZ072rGN@v8zSRbkU0nByIlBgHUTe4ihh/J6DT8 "Haskell – Try It Online") ]
[Question] [ In this challenge, given a list of ghosts from Pac-Man, you must output which ghosts are missing. You must do it in as few bytes as you can ## Input Input will consist of a string or list, which will include a number ghosts, which could include: * Blinky * Inky * Pinky * Clyde However, input may also include Pac-Man (with that punctuation). So, the maximum amount of items in a list will be five, in any order. It can be assumed that no invalid items will be in the list ## Output Output will consist of a string, or list. This will include of all the ghosts that are not in the input, in any order. However, if Pac-Man is in the input, all ghosts will be considered missing (because he eats them). ## Test cases ``` input: Clyde output: Blinky, Inky, Pinky alternate output: Inky, Pinky, Blinky or one of the other 4 permutations input: Clyde, Blinky # or however you delimit it output: Inky, Pinky alt: Pinky, Inky input: Pac-Man, Clyde Output: Blinky, Inky, Pinky, Clyde or you could output one of the other 23 permutations input:[null] Output: Blinky, Inky, Pinky, Clyde or you could output one of the other 23 permutations ``` This is codegolf, so the lower the bytecount, the better. [Answer] ## [Retina](https://github.com/m-ender/retina), 45 bytes ``` A`- $ ,;BliNClyde,INPiN N nky, D`\w+, .*;|,$ ``` The trailing linefeed is significant. Input and output are comma separated. [Try it online!](http://retina.tryitonline.net/#code=JShHYApBYC0KJAosO0JsaU5DbHlkZSxJTlBpTgpOCm5reSwKRGBcdyssCi4qO3wsJAo&input=Q2x5ZGUKQ2x5ZGUsQmxpbmt5ClBhYy1NYW4sQ2x5ZGUK) (The first line enables a linefeed-separated test suite.) ### Explanation I did not expect to be able to show off Retina's latest addition (deduplication stages) so soon, but it's really helpful for this challenge. :) **Stage 1: Anti-Grep** ``` A`- ``` Anti-grep stages discard all lines that match the given regex. The regex is just `-` and the input is always a single line, so this discards all ghosts if the input contains `Pac-Man`. **Stage 2: Substitution** ``` $ ,;BliNClyde,INPiN ``` This simply appends the fixed string `,;BliNClyde,INPiN`. This will be the list of ghosts in the output after some clean-up. **Stage 3: Substitution** ``` N nky, ``` Note that we've written the three `*nky` ghosts with an `N` in the previous stage (and omitted the comma after them), and we now expand this shorthand, which saves a couple of bytes. There is now a comma after every single ghost, and we've got the input ghosts and list of all ghosts separated by a semicolon. **Stage 3: Deduplication** ``` D`\w+, ``` This is the new part. Deduplication stages find all instances of the given regex and discard all matched substrings which are equal to an earlier matched substring. The regex simply matches all the ghosts, both in the input and in the list of potential outputs. If the input contains a ghost, then the same ghost will be matched again in the second list and is discarded. Otherwise, the ghost is matched for the first time in the second list and kept. So after this, the list after the semicolon is our desired output. All that's left is a bit of clean-up: **Stage 5: Substitution** ``` .*;|,$ ``` We simply match everything up to the semicolon as well as the comma at the end of the string and remove them. [Answer] ## Python 3, 75 bytes ``` lambda s:[x for x in['Blinky','Inky','Pinky','Clyde']if(x in s)<1or'-'in s] ``` Input is a comma-separated string, and the output will be a list. [Answer] # JavaScript ES6, ~~85~~ 78 bytes As an anonymous function ``` a=>["Blinky","Inky","Pinky","Clyde"].filter(c=>!a.includes(c)|a.some(v=>v[6])) ``` Today I learned about this `filter` function. Fun! 15 bytes saved thanks to Neil. Usage: ``` (a=>["Blinky","Inky","Pinky","Clyde"].filter(c=>!a.includes(c)||a.includes("Pac-Man")))(["Pac-Man"]) > ["Blinky","Inky","Pinky","Clyde"] (a=>["Blinky","Inky","Pinky","Clyde"].filter(c=>!a.includes(c)||a.includes("Pac-Man")))(["Pinky"]) > ["Blinky","Inky","Clyde"] (a=>["Blinky","Inky","Pinky","Clyde"].filter(c=>!a.includes(c)||a.includes("Pac-Man")))([]) > ["Blinky","Inky","Pinky","Clyde"] ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~25~~ 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ff”-ȯ⁸“JLKqḤṢ&F⁻ı»ṣ⁶¤ḟ ``` This is a monadic function. I/O is in form of lists. [Try it online!](http://jelly.tryitonline.net/#code=RmbigJ0tyK_igbjigJxKTEtx4bik4bmiJkbigbvEscK74bmj4oG2wqThuJ8Kw4figqxH&input=&args=WydDbHlkZSddLCBbJ0NseWRlJywgJ0JsaW5reSddLCBbJ1BhYy1NYW4nLCAnQ2x5ZGUnXSwgW10) ### How it works ``` Ff”-ȯ⁸“JLKqḤṢ&F⁻ı»ṣ⁶¤ḟ Monadic link. Argument: A (list of strings) F Flatten A. f”- Filter it with the string "-" to detect "Pac-Man". ȯ⁸ Flat logical OR with A. This yields A if there is no '-' in the input, the string "-" otherwise. ¤ Combine the three links to the left into a niladic chain. “JLKqḤṢ&F⁻ı» Yield "Blinky Inky Pinky Clyde", using Jelly's built-in English dictionary. ṣ⁶ Split at spaces to yield ["Blinky", "Inky", "Pinky", "Clyde"]. ḟ Filter-false; removing all elements from that list that appear in A or "-". This is a noop if A contains "Pac-Man". ``` [Answer] # Ruby, ~~55~~ 49 bytes [Try it online!](https://repl.it/Cd2b/1) *-6 bytes from @MartinEnder* ``` ->a{%w"Blinky Inky Pinky Clyde"-(a*''=~/-/?[]:a)} ``` Ruby arrays can undergo set subtraction, making it very easy to remove the appropriate ghosts. [Answer] ## Perl, 51 bytes **50 bytes code + 1 for `-n`** ``` for$@(Blinky,Inky,Pinky,Clyde){print$@if/-/|!/$@/}g} ``` ### Usage ``` perl -ne 'for$@(Blinky,Inky,Pinky,Clyde){print$@if/-/|!/$@/}' <<< 'Pac-Man, Clyde' BlinkyInkyPinkyClyde ``` I can amend the output if necessary, adding a space after each ghost, for + 3 bytes replacing `print$@` with `print"$@ "`. -6 bytes thanks to [@MartinEnder](https://codegolf.stackexchange.com/users/8478/martin-ender)! --- ## Perl, 53 bytes **51 bytes code + 2 for `-na`** An alternative solution, using the smartmatch operator: ``` print grep/-/~~@F|!($_~~@F),Blinky,Inky,Pinky,Clyde ``` ### Usage Requires a space separated list of input: ``` perl -nae 'print grep/-/~~@F|!($_~~@F),Blinky,Inky,Pinky,Clyde' <<< 'Clyde Pinky Inky' Blinky perl -nae 'print grep/-/~~@F|!($_~~@F),Blinky,Inky,Pinky,Clyde' <<< 'Clyde Pinky Inky Pac-Man' BlinkyInkyPinkyClyde' ``` [Answer] # [Pyth](http://pyth.herokuapp.com/?code=j-c%3A%22+p+bl+clyde%22d%22inky+%22d%3F%3Az%5CaZYcz&input=pac-man&test_suite=1&test_suite_input=clyde%0Ablinky+pinky%0Ainky+clyde%0Apac-man&debug=0) - 45 38 35 Bytes ``` =GwI!:G"a")j-["inky""pinky""blinky""clyde")cG ``` ``` I!:=Gw"a")j-c:" p bl clyde"d"inky "dcG ``` ``` j-c:" p bl clyde"d"inky "d?:z\aZYcz ``` *-1 more byte thanks to Leaky Nun!* Input must be space delimited, all lowercase; outputs missing ghosts on separate lines unless pac-man is in the input. [Answer] # C, 171 bytes Pass a NULL-terminated array of strings to `f()`, and it will print out the missing names. ``` *a[]={"Blinky","Inky","Pinky","Clyde",0},**s,**r,n;f(int**p){for(r=p;*p;)r=strcmp(*p++,"Pac-Man")?r:a+4;for(s=a;*s;++s){for(p=r,n=1;n&&*p;)n=strcmp(*s,*p++);n&&puts(*s);}} ``` [Try it on ideone.](http://ideone.com/F3SYw7) [Answer] ## PowerShell v4+, 107 bytes ``` param($n)((($n+($x='Pinky','Inky','Blinky','Clyde')|group|?{$_.count-eq1}).Name),$x)['-'-in[char[]]-join$n] ``` A little clunky compared to others, as PowerShell lacks a ternary operator or any sort of `map`-style operator. As a result, we build our own. Takes input `$n` as an explicit array of strings (e.g., `.\which-ghosts-are-missing.ps1 @('Clyde','Blinky')`. The rest of the program is one pseudo-ternary that's composed of an array that we index into via some logic `[...]`. The logic is simply whether the `-` character is anywhere in the input array `-join`ed together into a single string and then re-cast as a `char` array, in order to use the `-in` operator. Thus, if `Pac-Man` is in the input array, this will be `$TRUE` and the second element of the pseudo-ternary array will be chosen, else the first will be chosen. If it's the case that `Pac-Man` is not in the array, the first portion of the pseudo-ternary array is output. That is a combination of the input array `$n` concatenated with an array of all the ghosts (saved into `$x`). We pipe that new array into `Group-Object` which will group like items together, then select using `Where-Object` (aliased via `|?{...}` only the items where their `.count` is `-eq`ual to `1`. That's all encapsulated in a parens, and we select the `.Name` property. This is where the v4 requirement comes in, as under v4 you can reference a hashtable label like this rather than using something like `|Select Name`, which saves several bytes. Otherwise, since `Pac-Man` is in the input array, we need to output all the ghosts. Thankfully we already saved those into `$x`, so that's the choice in this case. Either way, the pipeline now contains a string array of ghosts, and output is implicit. ### Examples ``` PS C:\Tools\Scripts\golfing> .\which-ghosts-are-missing.ps1 @('Clyde') Pinky Inky Blinky PS C:\Tools\Scripts\golfing> .\which-ghosts-are-missing.ps1 @('Pac-Man','Clyde') Pinky Inky Blinky Clyde PS C:\Tools\Scripts\golfing> .\which-ghosts-are-missing.ps1 @() Pinky Inky Blinky Clyde PS C:\Tools\Scripts\golfing> .\which-ghosts-are-missing.ps1 @('Clyde','Blinky') Pinky Inky ``` [Answer] # Python 2, ~~66~~ ~~61~~ 96 bytes ``` g={"Blinky","Inky","Pinky","Clyde"};i=set(input());print",".join(g-i if not"Pac-Man"in i else g) ``` Input must be a list, output will be a string of names separated by a `,`. 61 bytes version that doesn't handle Pac-Man: ``` print",".join({"Blinky","Inky","Pinky","Clyde"}-set(input())) ``` [Answer] # Haskell, 91 bytes ``` import Data.List p l=(if elem"Pac-Man"l then id else(\\l))["Blinky","Inky","Pinky","Clyde"] ``` Input is a list of strings. It decides whether to use the list as-is or do a list-difference based on the presence of "Pac-Man". For extra fun, here is no Pac-Man: ``` import Data.List (["Blinky","Inky","Pinky","Clyde"]\\) ``` Will be improving this answer soon, did it super late at night. [Answer] ## Python 3, 77 bytes ``` lambda i:[g for g in"Blinky Inky Pinky Clyde".split()if g not in i or"-"in i] ``` Here is another answer at 89 bytes that I was playing with but didn't work out :( ``` lambda i:[g for g in[s+"nky"for s in"Bli I Pi".split()]+["Clyde"]if g not in i or"-"in i] ``` And here's the original at 85 bytes: ``` lambda i,n="Blinky Inky Pinky Clyde":([g for g in n.split()if g not in i],n)["-"in i] ``` These all take a single string of the names separated by spaces/commas. [Answer] ## 05AB1E, ~~47~~ 44 bytes ``` •1g!Z~÷kÅ]°%Ï0›K/•35B0¡™svy'-åi,q}}v¹ykÌiy)˜ ``` **Explaination** ``` •1g!Z~÷kÅ]°%Ï0›K/•35B0¡™ # push list of the 4 ghosts svy'-åi,q}} # if Pac-Man is in input, quit and output list of all 4 ghosts v¹ykÌiy)˜ # otherwise, generate the list of ghosts missing from input ``` [Try it online](http://05ab1e.tryitonline.net/#code=4oCiMWchWn7Dt2vDhV3CsCXDjzDigLpLL-KAojM1QjDCoeKEonN2eSctw6VpLHF9fXbCuXlrw4xpeSnLnA&input=WydDbHlkZScsICdCbGlua3knLCdQYWMtTWFuJ10) [Answer] # Python 2, 151 bytes As there are already Python answers using sets and strings I decided to restrict myself to work with lists, which turned out to be pretty long and uncompetitive. However, as the approach taken is different as the common one used, here it is: ``` o=['Blinky','Clyde','Inky','Pinky'] p=lambda x:[l for l in reduce(lambda z,x:z+[y+[x]for y in z],o,[[]])if sorted(l+x)==o][0]if'Pac-Man'not in x else o ``` where the expected input is a list of strings. The approach is to bruteforce all possible combinations (without taking order into account) of 0,1,2,3 and 4 elements. This is done by ``` reduce(lambda z,x:z+[y+[x]for y in z],o,[[]]) ``` which returns ``` [[], ['Clyde'], ['Pinky'], ['Clyde', 'Pinky'], ['Inky'], ['Clyde', 'Inky'], ['Pinky', 'Inky'], ['Clyde', 'Pinky', 'Inky'], ['Blinky'], ['Clyde', 'Blinky'], ['Pinky', 'Blinky'], ['Clyde', 'Pinky', 'Blinky'], ['Inky', 'Blinky'], ['Clyde', 'Inky', 'Blinky'], ['Pinky', 'Inky', 'Blinky'], ['Clyde', 'Pinky', 'Inky', 'Blinky']] ``` and find the one which, in addition to the input list results in the complete list of ghosts. Then it is checked if the string `'Pac-Man'` is part of the input and, in case it is, the whole list of ghosts is returned. If not, only the ones which are not part of the input are returned. Notice that the list containing all ghost names (`o`) is sorted alphabetically and the same goes for the list built as (`sorted(l+x)`). This is due to the fact that in Python, `['a','b']==['b','a']` is evaluated as `False` whereas `['a','b']==['a','b']` is evaluated as `True`. 3 bytes can be saved if it is permitted to return the answer as a list of lists ( by removing the `[0]` at the end of the first list comprehension). But as I'm not sure it is a valid output I am counting them. [Answer] # [Pascal (FPC)](https://www.freepascal.org/), ~~204~~ 200 bytes Two loops, using a binary to find which ghosts+pacman are present. Takes the arguments from the commandline. Thanks to @manatwork for saving some more bytes! ``` var a:array[1..4]of string=('Blinky','Inky','Pinky','Clyde');i,s:Byte;begin for i:=1to ParamCount do s:=1<<Pos(ParamStr(i)[4],'nykd-')or s;for i:=1to 4do if(1<<i and s=0)or(s>31)then WriteLn(a[i])end. ``` [Try it online!](https://tio.run/##TY4xq8IwFIX/yt2SQC0WO7X2DToJDgUHh9LhalLfxXojSRTy62NQB6fD@TgfnDv6M86L6X5O6YkOsEHnMA5VWdajncAHR3zppNjMxNcoCrH7RP@t2zlqI1RLhW82MZj2ZC7EMFkH1HRVsNCjw9vWPjiAtuAzXK976@WbH4KTpIZ6LATHq14IlUXf/uh1lmiSWSJA1uC7Zd5I/7eqVPg3DEdHwexZ4kCjMqzLlNL73Qs "Pascal (FPC) – Try It Online") Ungolfed: ``` var a: array[1..4] of string = ('Blinky', 'Inky', 'Pinky', 'Clyde'); i, s: byte; begin for i:=1 to ParamCount do s := 1 << pos(ParamStr(i)[4], 'nykd-') or s; // fill bits by shifting, check for unique 4th char of names, '-' in 'pac-man', could also use the 3rd char for i:=1 to 4 do if (1 << i and s=0) or (s>31) then // check if bits are on writeln(a[i]); end. ``` # Old version using a set, ~~227~~ 209 bytes Two loops, using a set to find which ghosts+pacman are present. Takes the arguments from the commandline. ``` var a:array[1..4]of string=('Blinky','Inky','Pinky','Clyde');i:byte;s:set of 1..5;begin for i:=1to ParamCount do s:=s+[pos(ParamStr(i)[4],'nykd-')];for i:=1to 4do if not(i in s)or(5in s)then writeln(a[i]);end. ``` Ungolfed: ``` var a: array[1..4] of string = ('Blinky', 'Inky', 'Pinky', 'Clyde'); i: byte; s: set of 1..5; begin for i:=1 to ParamCount do s := s + [pos(ParamStr(i)[4], 'nykd-')]; // fill set with indxs for i:=1 to 4 do if not(i in s) or (5 in s) then // check indx not in set or pac-man is writeln(a[i]); end. ``` [Answer] # PHP program, 84 bytes ``` <?print_r(array_diff([Blinky,Inky,Pinky,Clyde],in_array('Pac-Man',$argv)?[]:$argv)); ``` * takes arguments from command line, prints result as an array. * filename must not be any of the ghosts or 'Pac-Man'! * short breakdown: remove (if 'Pac-Man' is in arguments: nothing, else all arguments) from all ghosts; print result recursively examples: ``` >php -d error_reporting=0 ghosts.php Clyde Array ( [0] => Blinky [1] => Inky [2] => Pinky ) >php -d error_reporting=0 ghosts.php Clyde Blinky Array ( [0] => Inky [1] => Pinky ) >php -d error_reporting=0 ghosts.php Pac-Man Clyde Array ( [0] => Blinky [1] => Inky [2] => Pinky [3] => Clyde ) ``` **PHP function, 90 bytes** ``` function p($a){return array_diff([Blinky,Inky,Pinky,Clyde],in_array('Pac-Man',$a)?[]:$a);} ``` takes and returns an array, use empty array for empty input, no other falsy value! **further thoughts** * replace `in_array(...)` with `strstr(join($argv),'-')` to detect `-` instead of `Pac-Man` (-2) * use `ereg('-',join($argv))` instead (another -2) * program could lose another 6 bytes in PHP<5.4 with `register_globals` on * to make the program print a comma-separated list: replace `<?print_r(` with `<?=join(',',` (+2). You may want to add `;echo""` to the call for a line break [Answer] # jq, 69 characters ``` ("Blinky Inky Pinky Clyde"/" ")as $a|if inside($a)then$a-. else$a end ``` Input is JSON, output is JSON, conditional syntax is pain. Sample run: ``` bash-4.3$ jq '("Blinky Inky Pinky Clyde"/" ")as $a|if inside($a)then$a-. else$a end' <<< '["Clyde"]' [ "Blinky", "Inky", "Pinky" ] bash-4.3$ jq '("Blinky Inky Pinky Clyde"/" ")as $a|if inside($a)then$a-. else$a end' <<< '["Pac-Man","Clyde"]' [ "Blinky", "Inky", "Pinky", "Clyde" ] ``` On-line test: * [["Clyde"]](https://jqplay.org/jq?q=%28"Blinky%20Inky%20Pinky%20Clyde"/"%20"%29as%20$a|if%20inside%28$a%29then$a-.%20else$a%20end&j=["Clyde"]) * [["Pac-Man","Clyde"]](https://jqplay.org/jq?q=%28"Blinky%20Inky%20Pinky%20Clyde"/"%20"%29as%20$a|if%20inside%28$a%29then$a-.%20else$a%20end&j=["Pac-Man","Clyde"]) [Answer] # TSQL(sqlserver 2016), 114 bytes **Golfed:** ``` DECLARE @ VARCHAR(99) = 'Blinky,Inky,Pinky,Clyde' SELECT*FROM STRING_SPLIT('Blinky,Inky,Pinky,Clyde',',')EXCEPT SELECT*FROM STRING_SPLIT(@,','WHERE @ NOT LIKE'%-%' ``` **Ungolfed:** ``` DECLARE @ VARCHAR(99) = 'Blinky,Inky,Pinky,Clyde' SELECT * FROM STRING_SPLIT('Blinky,Inky,Pinky,Clyde',',') EXCEPT SELECT * FROM STRING_SPLIT(@,',') WHERE @ NOT LIKE'%-%' ``` **[Fiddle](https://data.stackexchange.com/stackoverflow/query/515126/which-ghosts-are-missing)** [Answer] ## Lotus Notes @Formula language, ~~85~~ ~~84~~ ~~75~~ 74 characters *-1 character by reversing the @If assignment* *-9 Changed @Contains(i;"-") to @Like(i;"%-%") and removed @Trim (not needed if displayed using space as seperator)* *-1 by removing the newline* Create a form with two fields: i (Text,Editable,Multi-value) and o (Text,Computed,Multi-value). Enter the following formula in o: ``` l:="Inky":"Pinky":"Blinky":"Clyde";@If(@Like(i;"%-%");l;@Replace(l;i;"")) ``` From Notes client, create a new document using the form, enter the name(s) in the i field and press F9 to refresh the document. Answer displayed in field o. This takes advantage of the fact that @Like and @Replace can can both be used either on a string or on a list of strings. [Answer] **C# ~~135 bytes~~126 bytes** ``` string[] g{"Blinky","Inky","Pinky","Clyde"};Console.WriteLine(String.Join(",",i.Contains("Pac-Man")?g:g.Except(i).ToArray())); ``` (where i is a string array containing the input) After looking at the other examples, I see that C# is rather a verbose language :) [Answer] ## Pyke, ~~45~~ ~~39~~ ~~38~~ ~~37~~ 32 bytes ``` .d𖭺𐎪膎㧫l4dc].^D`\-R{!* ``` [Try it here!](http://pyke.catbus.co.uk/?code=.d%04%F0%96%AD%BA%F0%90%8E%AA%E8%86%8E%E3%A7%ABl4dc%5D.%5ED%60%5C-R%7B%21%2a&input=%5B%22Blinky%22%2C+%22Pinky%22%5D) ``` .d𖭺𐎪膎㧫l4dc - dictionary_lookup('blinky inky pinky clyde').title().split() ].^ - xor(^, input) D`\-R{!* - ^*("-" not in input) ``` [Answer] ## Batch, 141 bytes ``` @set g= Blinky Inky Pinky Clyde @for %%a in (%*)do @if %%a==Pac-Man goto l @for %%a in (%*)do call set g=%%g: %%a=%% @l @echo(%g:~1,-1% ``` (Subtract 6 bytes for `:~1,-1` if leading and trailing whitespace is acceptable.) Requires Pac-Man in title case but the ghosts are case insensitive. [Answer] # [Japt](https://github.com/ETHproductions/japt), 38 bytes (Non-competing) Takes input as an array of strings, outputs an array of strings ``` `B¦nky Inky Pky CÒè`¸kUø`Pac-M` ?N:U ``` [Try it online](http://ethproductions.github.io/japt/?v=1.4.5&code=YEKmbmt5IElua3kgUIhreSBD0uhguGtV+GBQYWMtTYRgID9OOlU=&input=WyJJbmt5Il0=) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 27 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` …ꥦ¨™Å#'y«.•S:-•ª™IDJ{нaиK ``` [Try it online](https://tio.run/##yy9OTMpM/f//UcOyw6sOLT207NCKRy2LDrcqq1ceWq33qGFRsJUukDy0Cijq6eJVfWFv4oUd3v//RysFJCbr@ibmKekoOedUpqQqxQIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKS/X@9Rw2LjA9vOLTi8Pxzkw8viSs73HVu4@F9So8aJj9q2AWUVH7UsqjSxav6wt7ECzu8/@v8j45Wcs6pTElVitWBsXSUnHIy87IrwUIBicm6vol5QEG4MpCwJ0gerlAHrjMAojEWAA). **Explanation:** ``` …ꥦ¨™Å # Push dictionary string "blink ink pink" # STACK: "blink ink pink" # # Split it on spaces # STACK: ["blink","ink","pink"] 'y '# Push "y" # STACK: ["blink","ink","pink"],"y" « # Append it to each string in the list # STACK: ["blinky","inky","pinky"] .•S:-• # Push compressed string "clyde" # STACK: ["blinky","inky","pinky"],"clyde" ª # Append it to the list # STACK: ["blinky","inky","pinky","clyde"] ™ # Titlecase each string # STACK: ["Blinky","Inky","Pinky","Clyde"] I # Push the input-list # STACK1: ["Blinky","Inky","Pinky","Clyde"],["Pac-Man"] # STACK2: ["Blinky","Inky","Pinky","Clyde"],["Pinky"] # STACK3: ["Blinky","Inky","Pinky","Clyde"],[] D # Duplicate it # STACK1: ["Blinky","Inky","Pinky","Clyde"],["Pac-Man"],["Pac-Man"] # STACK2: ["Blinky","Inky","Pinky","Clyde"],["Pinky"],["Pinky"] # STACK3: ["Blinky","Inky","Pinky","Clyde"],[],[] J # Join the copy to a single string # STACK1: ["Blinky","Inky","Pinky","Clyde"],["Pac-Man"],"Pac-Man" # STACK2: ["Blinky","Inky","Pinky","Clyde"],["Pinky"],"Pinky" # STACK3: ["Blinky","Inky","Pinky","Clyde"],[],"" { # Sort its characters # STACK1: ["Blinky","Inky","Pinky","Clyde"],["Pac-Man"],"-MPaacn" # STACK2: ["Blinky","Inky","Pinky","Clyde"],["Pinky"],"Pikny" # STACK3: ["Blinky","Inky","Pinky","Clyde"],[],"" н # Pop and leave just its first character # STACK1: ["Blinky","Inky","Pinky","Clyde"],["Pac-Man"],"-" # STACK2: ["Blinky","Inky","Pinky","Clyde"],["Pinky"],"P" # STACK3: ["Blinky","Inky","Pinky","Clyde"],[],"" a # Check if this is a letter # STACK1: ["Blinky","Inky","Pinky","Clyde"],["Pac-Man"],0 # STACK2: ["Blinky","Inky","Pinky","Clyde"],["Pinky"],1 # STACK3: ["Blinky","Inky","Pinky","Clyde"],[],0 и # Repeat the input-list that many times # STACK1: ["Blinky","Inky","Pinky","Clyde"],[] # STACK2: ["Blinky","Inky","Pinky","Clyde"],["Pinky"] # STACK3: ["Blinky","Inky","Pinky","Clyde"],[] K # Remove those strings from the earlier quartet-list # STACK1: ["Blinky","Inky","Pinky","Clyde"] # STACK2: ["Blinky","Inky","Clyde"] # STACK3: ["Blinky","Inky","Pinky","Clyde"] # (after which the resulting list is output implicitly) ``` [See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `…ꥦ¨™Å` is `"blink ink pink"` and `.•S:-•` is `"clyde"`. ]
[Question] [ Here's a simple one to stretch your compression muscles. Your code (a complete program) must output the spelled-out English representation of all the cardinal numbers from 1 to 100, and then all the ordinal numbers from 1 to 100. The numerals in each list should be delimited by commas and spaces and properly hyphenated. Each list should begin with a single capital letter and conclude with a period. The two lists should be separated by a newline. For clarity's sake, you must produce this exact byte stream: ``` One, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty, twenty-one, twenty-two, twenty-three, twenty-four, twenty-five, twenty-six, twenty-seven, twenty-eight, twenty-nine, thirty, thirty-one, thirty-two, thirty-three, thirty-four, thirty-five, thirty-six, thirty-seven, thirty-eight, thirty-nine, forty, forty-one, forty-two, forty-three, forty-four, forty-five, forty-six, forty-seven, forty-eight, forty-nine, fifty, fifty-one, fifty-two, fifty-three, fifty-four, fifty-five, fifty-six, fifty-seven, fifty-eight, fifty-nine, sixty, sixty-one, sixty-two, sixty-three, sixty-four, sixty-five, sixty-six, sixty-seven, sixty-eight, sixty-nine, seventy, seventy-one, seventy-two, seventy-three, seventy-four, seventy-five, seventy-six, seventy-seven, seventy-eight, seventy-nine, eighty, eighty-one, eighty-two, eighty-three, eighty-four, eighty-five, eighty-six, eighty-seven, eighty-eight, eighty-nine, ninety, ninety-one, ninety-two, ninety-three, ninety-four, ninety-five, ninety-six, ninety-seven, ninety-eight, ninety-nine, one hundred. First, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth, thirteenth, fourteenth, fifteenth, sixteenth, seventeenth, eighteenth, nineteenth, twentieth, twenty-first, twenty-second, twenty-third, twenty-fourth, twenty-fifth, twenty-sixth, twenty-seventh, twenty-eighth, twenty-ninth, thirtieth, thirty-first, thirty-second, thirty-third, thirty-fourth, thirty-fifth, thirty-sixth, thirty-seventh, thirty-eighth, thirty-ninth, fortieth, forty-first, forty-second, forty-third, forty-fourth, forty-fifth, forty-sixth, forty-seventh, forty-eighth, forty-ninth, fiftieth, fifty-first, fifty-second, fifty-third, fifty-fourth, fifty-fifth, fifty-sixth, fifty-seventh, fifty-eighth, fifty-ninth, sixtieth, sixty-first, sixty-second, sixty-third, sixty-fourth, sixty-fifth, sixty-sixth, sixty-seventh, sixty-eighth, sixty-ninth, seventieth, seventy-first, seventy-second, seventy-third, seventy-fourth, seventy-fifth, seventy-sixth, seventy-seventh, seventy-eighth, seventy-ninth, eightieth, eighty-first, eighty-second, eighty-third, eighty-fourth, eighty-fifth, eighty-sixth, eighty-seventh, eighty-eighth, eighty-ninth, ninetieth, ninety-first, ninety-second, ninety-third, ninety-fourth, ninety-fifth, ninety-sixth, ninety-seventh, ninety-eighth, ninety-ninth, one hundredth. ``` This is code golf, shortest answer in bytes wins. [Answer] # Common Lisp, ~~88~~ ~~82~~ 80 bytes ``` (format t"~@(~{~R~^, ~}~). ~:*~@(~{~:R~^, ~}~)."(loop as i to 99 collect(1+ i))) ``` (It is part of the language, I hope you don't mind) ### Output ``` One, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty, twenty-one, twenty-two, twenty-three, twenty-four, twenty-five, twenty-six, twenty-seven, twenty-eight, twenty-nine, thirty, thirty-one, thirty-two, thirty-three, thirty-four, thirty-five, thirty-six, thirty-seven, thirty-eight, thirty-nine, forty, forty-one, forty-two, forty-three, forty-four, forty-five, forty-six, forty-seven, forty-eight, forty-nine, fifty, fifty-one, fifty-two, fifty-three, fifty-four, fifty-five, fifty-six, fifty-seven, fifty-eight, fifty-nine, sixty, sixty-one, sixty-two, sixty-three, sixty-four, sixty-five, sixty-six, sixty-seven, sixty-eight, sixty-nine, seventy, seventy-one, seventy-two, seventy-three, seventy-four, seventy-five, seventy-six, seventy-seven, seventy-eight, seventy-nine, eighty, eighty-one, eighty-two, eighty-three, eighty-four, eighty-five, eighty-six, eighty-seven, eighty-eight, eighty-nine, ninety, ninety-one, ninety-two, ninety-three, ninety-four, ninety-five, ninety-six, ninety-seven, ninety-eight, ninety-nine, one hundred. First, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth, thirteenth, fourteenth, fifteenth, sixteenth, seventeenth, eighteenth, nineteenth, twentieth, twenty-first, twenty-second, twenty-third, twenty-fourth, twenty-fifth, twenty-sixth, twenty-seventh, twenty-eighth, twenty-ninth, thirtieth, thirty-first, thirty-second, thirty-third, thirty-fourth, thirty-fifth, thirty-sixth, thirty-seventh, thirty-eighth, thirty-ninth, fortieth, forty-first, forty-second, forty-third, forty-fourth, forty-fifth, forty-sixth, forty-seventh, forty-eighth, forty-ninth, fiftieth, fifty-first, fifty-second, fifty-third, fifty-fourth, fifty-fifth, fifty-sixth, fifty-seventh, fifty-eighth, fifty-ninth, sixtieth, sixty-first, sixty-second, sixty-third, sixty-fourth, sixty-fifth, sixty-sixth, sixty-seventh, sixty-eighth, sixty-ninth, seventieth, seventy-first, seventy-second, seventy-third, seventy-fourth, seventy-fifth, seventy-sixth, seventy-seventh, seventy-eighth, seventy-ninth, eightieth, eighty-first, eighty-second, eighty-third, eighty-fourth, eighty-fifth, eighty-sixth, eighty-seventh, eighty-eighth, eighty-ninth, ninetieth, ninety-first, ninety-second, ninety-third, ninety-fourth, ninety-fifth, ninety-sixth, ninety-seventh, ninety-eighth, ninety-ninth, one hundredth. ``` ### Explanations See [Formatted Output to Character Streams](https://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node200.html). * `(format t "<control string>" <arguments>)` formats the control string according to the (variadic) arguments and prints to standard output (because `t`) * `(loop ...)` builds the list of integers from 1 to 100 * `~@( ... ~)` capitalizes the string returned by the inner control string * `~{ ... ~}` iterates over the current argument and applies the inner formatting to each element * Inside the iteration, everything that follows `~^` is *not* printed on the last iteration: this is used to add the comma-space separator *between* elements. * `~R` outputs current argument as a cardinal * `~:R` outputs current argument as an ordinal * `~%` outputs a new line * `~:*` reset the *current* argument to be processed as the previous one, which is used here to reuse the list of integers a second time. Saved 2 bytes thanks to PrzemysławP. [Answer] # Pyth, ~~366~~ ~~342~~ 340 bytes ``` Lcbdj=Y", "++rhJy"one two three four five six seven eight nine"3+tJ+y"ten eleven twelve"+=Nm+d"teen"=by"thir four fif six seven eigh nine"sm+dm++d\-kJKy"twenty thirty forty fifty sixty seventy eighty ninety"+=H"one hundred"\.jY+rh=J++y"first second third"m+d=T"th"tPby"ninth"3+++tJy"tenth eleventh twelfth"+m+dTNsm++Pd"ieth"m++d\-kJK+H"th." ``` [Live demo.](https://pyth.herokuapp.com/?code=Lcbdj%3DY"%2C+"%2B%2BrhJy"one+two+three+four+five+six+seven+eight+nine"3%2BtJ%2By"ten+eleven+twelve"%2B%3DNm%2Bd"teen"%3Dby"thir+four+fif+six+seven+eigh+nine"sm%2Bdm%2B%2Bd%5C-kJKy"twenty+thirty+forty+fifty+sixty+seventy+eighty+ninety"%2B%3DH"one+hundred"%5C.jY%2Brh%3DJ%2B%2By"first+second+third"m%2Bd%3DT"th"tPby"ninth"3%2B%2B%2BtJy"tenth+eleventh+twelfth"%2Bm%2BdTNsm%2B%2BPd"ieth"m%2B%2Bd%5C-kJK%2BH"th."&debug=1) ## 342-byte version: ``` Lcbdj", "++rhJy"one two three four five six seven eight nine"3+tJ+y"ten eleven twelve"+=Nm+d"teen"=by"thir four fif six seven eigh nine"sm+dm++d\-kJKy"twenty thirty forty fifty sixty seventy eighty ninety"+=H"one hundred"\.j", "+rh=J++y"first second third"m+d"th"tPby"ninth"3+++tJy"tenth eleventh twelfth"+m+d"th"Nsm++Pd"ieth"m++d\-kJK+H"th." ``` ## 366-byte version: ``` Lcbd j", "++"One"+tJy"one two three four five six seven eight nine"+y"ten eleven twelve"+=Nm+d"teen"y"thir four fif six seven eigh nine"sm+dm++d\-kJKy"twenty thirty forty fifty sixty seventy eighty ninety"+=H"one hundred"\. j", "+"First"+++t=Jy"first second third fourth fifth sixth seventh eighth ninth"y"tenth eleventh twelfth"+m+d"th"Nsm++Pd"ieth"m++d\-kJK+H"th." ``` [Answer] # PHP - 491 bytes Small cheat here for the cardinals (I'm using the NumberFormatter class that comes default with PHP): ``` echo'One, ';$x=new NumberFormatter(0,5);for($i=1;$i++<100;)echo$x->format($i).($i>99? '.':', ');echo" ";$y=[First,second,third,fourth,fifth,sixth,seventh,eighth,ninth,tenth, eleventh,twelfth,thirteenth,fourteenth,fifteenth,sixteenth,seventeenth,eighteenth,nineteenth, twentieth];for($z=[thirtieth,fortieth,fiftieth,sixtieth,seventieth,eightieth,ninetieth]; $j++<99;$q=floor($j/10),$w=$z[$q-2])echo$j<21?$y[$j-1]:($j%10?$x->format($q*10).'-'. strtolower($y[$j%10-1]):$w),', ';echo'one hundredth.'; ``` (added a few new lines for readability) [Answer] ## PHP 5.3+, 195 bytes That includes the newline character. It's part of the [`NumberFormatter`](https://php.net/manual/en/class.numberformatter.php) class, just like [razvan's answer](https://codegolf.stackexchange.com/a/57058/22867). Except I spell out both the cardinals and ordinals according to the ICU. ``` $f=numfmt_create(en,5);$g=clone$f;$g->setTextAttribute(6,'%spellout-ordinal');for($x=$y='',$i=1;$i++<100;){$x.=$f->format($i).($z=$i<=99?', ':'');$y.=$g->format($i).$z;}echo"One, $x. First, $y."; ``` Related: <https://stackoverflow.com/a/19411974/404623> [Answer] # Oracle SQL 231 bytes **[SqlFiddleLiveDemo](http://sqlfiddle.com/#!4/9eecb7d/5737/0)** ``` SELECT 'O'||SUBSTR(LISTAGG(TO_CHAR(TO_DATE(level,'j'),'jsp'),', ')WITHIN GROUP(ORDER BY level),2)||'.','F'||SUBSTR(LISTAGG(TO_CHAR(TO_DATE(level,'j'),'jTHSP'),', ')WITHIN GROUP(ORDER BY level),2)||'.' FROM DUAL CONNECT BY level<101 ``` [Answer] # JavaScript ES6, ~~562~~ 464 bytes Not even done golfing yet! ``` n=>(f=(a,b)=>Array(89).fill(a=btoa(a+`·§·,í*íË7躻rÍø·,ìrÎǯz{rÍè Ü³)Þ·,ó`).split`z`).map((l,i)=>i<1?b:i<20?a[i]:a[18+(i-i%10)/10]+'-'+a[i%10]).join`, `+', one hundred')(`¢w³· 3¶Þ{7躼ß÷³²,s±ëÞ7¢s)ÞÎ×§Íé^½éó·¥½ìí*íyéó~«µç§Íøµç§Îȱµç§Îǯz{^z|Þmyéó)Þµç§ÎÜܳ¶«·,ߢêíË7â~ܳ²,mË;½éíË7¢rÎx§µì³`,'One')+` `+f(`~*ì·;rÝÎØb­Üߢêí7â~Øs²,m;½éí7¢Øs)Þ¶íz{aÍé^½éí;pz[Þ¶í*íyéí7躻^z{aÍøµç§¶ì^z{aÎǯz{^z{aÍè ×Øs)޵秶ó`,'First')+'th' ``` **If this doesn't work I might need to add a hexdump because of all the special characters** Please let me know if this is the case and I'll get to you by tomorrow. If they are any typos also let me know. [Code in pastebin (Tested on Safari Nightly)](http://pastebin.com/aFpaszEz) # Explanation This may look like a bunch of garbled characters but it's actually pretty simple. We start by generating the cardinals. This array is compressed using the `btoa` function. ``` ['one', ..., 'eighteen', 'nineteen', 'twenty', 'thirty', ...,'ninety'] ``` To loop through a "range" we use the following: Now we generate an Array of length 89 using. The `...` is what uncompresses the array ``` Array(89).fill(...) ``` Then map through it, i is the index: ``` .map((l,i)=> ``` Now for the condition, `i < 1` or if it is the first item, we will use a capitalized version of one / first ``` i<1?b ``` Otherwise... if it is less than 20, we output eleven...nineteen ``` i<20?a[i]: ``` Otherwise... using `(i-i%10)/10` we get the last digit of the number. We add 18 to it to compensate for 1..19. We add a `-` and then add the last digit, or i%10 Finally, we add 'one hundred' to the very end because we don't. We repeat this for both types of numbers and separate with a newline [Answer] # C++ ~~704~~ ~~642~~ ~~620~~ 602 No library usage other than `ostream` `operator<<()` for `char*`s. ``` #include<iostream> char*q,a[]="|one|two|three|four|five|six|seven|eight|ni&u$Il%*twel&bthirte$Q(P#tif#j)/#k'L#|)y#r*4#s'9rst&>cond*5d)zh)gh)U#V)Ch)2h(}#V09$m0M$I0]'g0k)B0|*I#}1A+4$01f+y1u$$|+/nty+(y*`#X*3y)p#V)Ly))y(dyC5~hundred)Oie1o#|1c#}*E#s*a#t*}$&+9#|+T#|+uth",b[448],*s=a,*t=b;int i,j,k;auto p(int k){for(s=b;k--;)while(*s++);return s;}int main(){for(;k=*s++;)if(k>98)*t++=k<'|'?k:" "[k<'~'];else for(i=(k-35)*95+*s++-32,q=t-i/9,k=3+i%9;k--;)*t++=*q++;for(j=0;j<2;++j)for(i=1;b[1+126*j]^=32*(i<3),k=i<20?i:i%10,i<101;++i)std::cout<<p(40+!k*j*11+i/10)<<"-"[!k|i<20]<<p(j*20+k)<<", \0.\n"+i/100*3;} ``` [Live version](http://ideone.com/64xnDc). With some whitespace and some comments: ``` #include <iostream> // Encoded as literal characters or offset/length pairs for previous runs of characters, LZ like char *q, a[] = "|one|two|three|four|five|six|seven|eight|ni&u$Il%*twel&bthirte$Q(P#tif#j)/" "#k'L#|)y#r*4#s'9rst&>cond*5d)zh)gh)U#V)Ch)2h(}#V09$m0M$I0]'g0k)B0|*I#}1A+4$01f+y1u$$|" "+/nty+(y*`#X*3y)p#V)Ly))y(dyC5~hundred)Oie1o#|1c#}*E#s*a#t*}$&+9#|+T#|+uth", b[448], *s = a, *t = b; int i, j, k; // Find the kth null separated string in array b auto p(int k) { for (s = b; k--;) while (*s++) ; return s; } int main() { // Decode the compressed 'primitives' we use to build up the output. for (; k = *s++;) if (k > 98) *t++ = k < '|' ? k : " "[k < '~']; else for (i = (k - 35) * 95 + *s++ - 32, q = t - i / 9, k = 3 + i % 9; k--;) *t++ = *q++; // Loop twice over numbers 1-100, building up output from the 'primitives' in our array for (j = 0; j < 2; ++j) for (i = 1; b[1 + 126 * j] ^= 32 * (i < 3), k = i < 20 ? i : i % 10, i < 101; ++i) std::cout << p(40 + !k * j * 11 + i / 10) << "-"[!k | i < 20] << p(j * 20 + k) << ", \0.\n" + i / 100 * 3; } ``` The compressed string is decoded from `a` into `b`: ``` |one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen| sixteen|seventeen|eighteen|nineteen||first|second|third|fourth|fifth|sixth|seventh|eighth| ninth|tenth|eleventh|twelfth|thirteenth|fourteenth|fifteenth|sixteenth|seventeenth| eighteenth|nineteenth|||twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|one~ hundred|||twentieth|thirtieth|fourtieth|fiftieth|sixtieth|seventieth|eightieth| ninetieth|one~hundredth; ``` Without the newlines. During decompression the `|`s are replaced with `'\0'` and the `~`s are replaced with `' '` (quirk of the way the characters are encoded into printable ASCII). These 'primitive' strings are then looked up by index in the `b` array using the `p` function and used to assemble the output. Compression is a simple LZ like scheme where characters are either encoded as literals or as a negative offset into the buffer and a run length (encoded into two characters) if a match of length >=3 is found. The string could be compressed further using non-printable characters but I like my code to be copy and paste safe :) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `Hoj`, 98 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 12.25 bytes ``` ɾ₍∆ċ∆oƛ‛, j¡\.+ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJIb2o9IiwiIiwiyb7igo3iiIbEi+KIhm/Gm+KAmywgasKhXFwuKyIsIiIsIiJd) ``` ɾ₍∆ċ∆oƛ‛, j¡\.+­⁡​‎‎⁡⁠⁡‏⁠‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏‏​⁡⁠⁡‌⁢⁣​‎‏​⁢⁠⁡‌­ ɾ # ‎⁡H flag sets the stack to 100, so this makes a range [1,100] ₍ # ‎⁢Parallel apply the next two elements in a list ∆ċ∆o # ‎⁣Nth Cardinal and Nth Ordinal (gotta love builtins) ƛ # ‎⁤Map over the list of all cardinals and ordinals ‛, j # ‎⁢⁡Join by the two character string ", " where the second character is a space ¡\.+ # ‎⁢⁢Convert to sentence case and add a period. # ‎⁢⁣Implicit output, the j flag prints the top of the stack joined by newlines, which formats the list of two strings into the desired output. 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). Obviously non-competing. [Answer] # Javascript (ES6), 713 Similar to my [second PHP submission on this question](https://codegolf.stackexchange.com/a/55936/20666). (2444 - 713) / 2444 = 70.8% compression. ``` a=`Onez]cu^dP~Ntenz\`zHlvezmwgwjwkw{wqwpwHnQxZx]xcxux^xdxPx~xNmQXZX]XcXuX^XdXPX~XNforQbZb]bcbub^bdbPb~bNjQWZW]WcWuW^WdWPW~WNkQVZV]VcVuV^VdVPV~VN{QUZU]UcUuU^UdUPU~UNqQTZT]TcTuT^TdTPT~TNpQSZS]ScSuS^SdSPS~SNy. FirstzaRMLKJI[ten}\`}Hlf}mGgGjGkG{GqGpGHnYx_xaxRxMxLxKxJxIx[mYX_XaXRXMXLXKXJXIX[forYb_babRbMbLbKbJbIb[jYW_WaWRWMWLWKWJWIW[kYV_VaVRVMVLVKVJVIV[{YU_UaURUMULUKUJUIU[qYT_TaTRTMTLTKTJTIT[pYS_SaSRSMSLSKSJSIS[yth.`,'eleven|`}|`z|twe|q}|{}|k}|j}|g}|pz|{z|kz|gz|one hundred|tyz|mdz|qtz|p~|q~|{~|k~|j~|m~|tie}|onez|nin}|twoz|fivez|firstz|teen|threez|secondz|for~|four|fif|twen~|six|thir|nine|eigh|, |seven|th, |ty-'.split('|').map((e,i)=>a=a.split('`GwHIJKLMNPduyQR~STUVWXYZ[]^_`cabgjxkmpqz{}~'[i]).join(e)),alert(a) ``` [Fiddle](http://jsfiddle.net/45buvakf/) [Answer] # Mathematica ~~415 391~~ 407 The cardinals are given by `IntegerName[n]`. The ordinals are derived from the cardinals. ``` s = StringRiffle; y = IntegerName; t = StringReplace; k@n_ := If[(z = (TextWords["first second third a fifth a a a ninth,a, a twelfth a a a a a eighteenth a, twentieth"])[[n]]) == "a", y@n <> "th", z] g@n_ := Module[{i = IntegerDigits[n], z}, z := y[Quotient[n, 10]*10];Which[n == 100, "one hundredth", n < 20, k[n], i[[-1]] == 0, t[z, "y" -> "ieth"], 3 > 2, z <> "-" <> k[i[[-1]]]]] t[(s[y@Range@100 /. "one" -> "One", ", "] <> ".") <> s[g /@ Range@100 /. "first" -> "\nFirst", ", "] <> ".", "tt" -> "t"] ``` Output: ``` One, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty, twenty-one, twenty-two, twenty-three, twenty-four, twenty-five, twenty-six, twenty-seven, twenty-eight, twenty-nine, thirty, thirty-one, thirty-two, thirty-three, thirty-four, thirty-five, thirty-six, thirty-seven, thirty-eight, thirty-nine, forty, forty-one, forty-two, forty-three, forty-four, forty-five, forty-six, forty-seven, forty-eight, forty-nine, fifty, fifty-one, fifty-two, fifty-three, fifty-four, fifty-five, fifty-six, fifty-seven, fifty-eight, fifty-nine, sixty, sixty-one, sixty-two, sixty-three, sixty-four, sixty-five, sixty-six, sixty-seven, sixty-eight, sixty-nine, seventy, seventy-one, seventy-two, seventy-three, seventy-four, seventy-five, seventy-six, seventy-seven, seventy-eight, seventy-nine, eighty, eighty-one, eighty-two, eighty-three, eighty-four, eighty-five, eighty-six, eighty-seven, eighty-eight, eighty-nine, ninety, ninety-one, ninety-two, ninety-three, ninety-four, ninety-five, ninety-six, ninety-seven, ninety-eight, ninety-nine, one hundred. First, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth, thirteenth, fourteenth, fifteenth, sixteenth, seventeenth, eighteenth, nineteenth, twentieth, twenty-first, twenty-second, twenty-third, twenty-fourth, twenty-fifth, twenty-sixth, twenty-seventh, twenty-eighth, twenty-ninth, thirtieth, thirty-first, thirty-second, thirty-third, thirty-fourth, thirty-fifth, thirty-sixth, thirty-seventh, thirty-eighth, thirty-ninth, fortieth, forty-first, forty-second, forty-third, forty-fourth, forty-fifth, forty-sixth, forty-seventh, forty-eighth, forty-ninth, fiftieth, fifty-first, fifty-second, fifty-third, fifty-fourth, fifty-fifth, fifty-sixth, fifty-seventh, fifty-eighth, fifty-ninth, sixtieth, sixty-first, sixty-second, sixty-third, sixty-fourth, sixty-fifth, sixty-sixth, sixty-seventh, sixty-eighth, sixty-ninth, seventieth, seventy-first, seventy-second, seventy-third, seventy-fourth, seventy-fifth, seventy-sixth, seventy-seventh, seventy-eighth, seventy-ninth, eightieth, eighty-first, eighty-second, eighty-third, eighty-fourth, eighty-fifth, eighty-sixth, eighty-seventh, eighty-eighth, eighty-ninth, ninetieth, ninety-first, ninety-second, ninety-third, ninety-fourth, ninety-fifth, ninety-sixth, ninety-seventh, ninety-eighth, ninety-ninth, one hundredth. ``` [Answer] # JavaScript (ES6), 480 ``` /*TEST: redirect console output to snippet body */ console.log=x=>O.innerHTML=x // Not a function, as a complete program is requested b=x=>btoa(x).split`/`; Z=i=>z[i]||z[i-8]||z[i-18]; y=b("ýø«²ßìyÊ'wûa·ýøÿÿÞ)ÿÿûpzWÿÿÿÿÿÿÿ"); z=b("þÞþÜ(þØkyïߢêÿ~+ÞþȱþǯzÞmþx§{û^÷¥z÷§þÜ÷¿¶«ÿ÷âÿÿz(!ÿûpzÿ~ÿÿÿÿ"); o=(z.map((v,i)=>i<20?i<13?v:(v||z[i-10])+'teen':z[S='slice'](0,10).map(d=>Z(i)+(d?'ty-'+d:'ty')))+`,${h='one hundred'}.\nF`).split`,`; q=y.map((v,i)=>i<4?v:`${v||o[i]}th`); q=z.map((v,i)=>i<20?' '+q[i]:q[S](0,10).map(d=>' '+Z(i)+(d?'ty-'+d:'tieth'))); console.log('O'+o.join`, `[S](3)+`${q}, ${h}th.`[S](4)) // INFO: z uncompressed is [,one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,,fif,,,eigh,,twen,,for,,,,,] // INCO: y uncompressed is [,first,second,third,,fif,,,eigh,nin,,,twelf,,,,,,,,,] ``` ``` #O { white-space: pre-wrap } ``` ``` <pre id=O></pre> ``` [Answer] # PHP - 842 bytes Omitting regular PHP starting and ending tags, compression is 1 - 842/2445 = 65.6% Basically getting the output of `base64_encode(gzdeflate($input, 9));` and reversing the operations. Obviously, if I chose to output in pure 8-bit vs. base-64, it would be 25% smaller, but at the risk of running into escape or non-printable characters. ``` echo gzinflate(base64_decode('VZRdcuIwEITfcwoOQHKMfd1DBGnlKspUEYfEt1+rf2bGL6gbkLplS9/ftV0v28/j+BjPduj++H4en8vr0F/L7/HRXm29Xtryb2zXy7pgAr6585ftp93nv7exPLc2v5lrSC2d4lhKYk6ixJJQc1WqY7F12z2+P1gPmi2lWVaOnW1QXQY7sI6602k/ctrW3MHuUeHUekTUCqdTuMzyyl8YLq1wOofTMbw/kI2B0ZRIlvQrylxpxFIjVZKhNMqkUeTxdnYNioRkJKUiYXw2ekZCM5JSkTCOhGHkPAe7BkZSIlKSkTSMlPahdKQkI2kUSaNInLg9hGJlGGyjaFmF2zFeLu9GqSDrErKsgS93jywhjQ7WrCDHBjYoIIN863JFI12O4bhgu0eGSyPcmuFyDLdBuAzCrRkuVzAR4UfaZXyvt2e7fbz9WZ5feDafj/XGK3ATMQaPyuDrG36AQ3sZWHYOm769+/eJIEw0g7CWKOR1JUWiXL+VDGnzSGuv29JCzkeBLQRWtBOTCRsqZDrN7MVplxVPxXvPSajYoNoYOWxjzuRzLW0SVaeZvTi3KbwqPtoEsviIXcYcQhfTh1XMLr3oWsSzehrVKABL6xLBML9adRCY2EE4UgfBjB0CZnVWT+MOSbS00cFQ85liB5OKh1x8YgfTDR2SbnVWT+MrkIhL6w5BuTzMahHI0mV7nY5q4o5dCu7Os3u1p0tZO1XqjRP24l6xVnAMrQJeLBX8Q6fCv9PMXpwKVQgW7zrJwbjZbBNgQ5ugGdsEENGmAPE0sxenNpWKxReCtWxTyLiNj7f/')); ``` ]
[Question] [ > > For nandgame fans: Please try out [DPD to decimal in logic gates](https://codegolf.stackexchange.com/q/176557/78410) too! > > > ## Background [Densely packed decimal (DPD)](https://en.wikipedia.org/wiki/Densely_packed_decimal) is a way to efficiently store decimal digits in binary. It stores three decimal digits (000 to 999) in 10 bits, which is much more efficient than naive BCD (which stores one digit in 4 bits). ### Notations * The lowercase letters `a` to `i` are the bits that are copied to the decimal representation. * `0` and `1` are the exact bits in the input or output bit patterns. * `x` bits are ignored in the conversion. ### Conversion table The following is the conversion table from 10 bits of DPD to three decimal digits. Each decimal digit is represented as 4-bit binary (BCD). Both sides are written left to right from the most significant digit to the least. ``` Bits => Decimal (Digit range) a b c d e f 0 g h i => 0abc 0def 0ghi (0-7) (0-7) (0-7) a b c d e f 1 0 0 i => 0abc 0def 100i (0–7) (0–7) (8–9) a b c g h f 1 0 1 i => 0abc 100f 0ghi (0–7) (8–9) (0–7) g h c d e f 1 1 0 i => 100c 0def 0ghi (8–9) (0–7) (0–7) g h c 0 0 f 1 1 1 i => 100c 100f 0ghi (8–9) (8–9) (0–7) d e c 0 1 f 1 1 1 i => 100c 0def 100i (8–9) (0–7) (8–9) a b c 1 0 f 1 1 1 i => 0abc 100f 100i (0–7) (8–9) (8–9) x x c 1 1 f 1 1 1 i => 100c 100f 100i (8–9) (8–9) (8–9) ``` ## Task Convert 10 bits of DPD to 3 digits of decimal. ## Test cases ``` DPD Decimal 0000000101 005 0001100011 063 0001111001 079 0000011010 090 0001011110 098 1010111010 592 0011001101 941 1100111111 879 1110001110 986 0011111111 999 1111111111 999 * Output is same regardless of the `x` bits ``` ## Input The default input format is a list of 10 bits. The bits should follow the exact order above, or the reverse of it. You may choose to use an equivalent string or integer representation instead. Unlike my other challenges, **reordering or using nested structures is not allowed**. For the input `[1, 1, 0, 0, 0, 1, 0, 1, 0, 0]`, the following formats are allowed: * List of bits: `[1, 1, 0, 0, 0, 1, 0, 1, 0, 0]` * String: `"1100010100"` * Binary integer: `788` or `0b1100010100` * Decimal integer: `1100010100` * Reversed: `[0, 0, 1, 0, 1, 0, 0, 0, 1, 1]` and reversed in any other formats above The following formats are NOT allowed: * Arbitrary reordering of bits: `[0, 0, 0, 0, 0, 1, 1, 1, 0, 1]` * Nested structures: `[[1, 1, 0], [0, 0, 1], [0, 1, 0, 0]]` or `[0b110, 0b001, 0b0100]` ## Output The default output format is a list of 3 decimal digits. Each digit should be represented as 0 to 9, either an integer or a character. As in input, you can choose string or integer representation. If you choose integer representation, leading zeroes can be omitted. ## Scoring & winning criterion Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest program or function in bytes for each language wins. [Answer] # JavaScript (ES6), 112 bytes *All credit for this shorter version goes to @nwellnhof.* Takes input as an integer. Returns an array of three decimal digits. ``` n=>[(x=n>>4,y=x>>3,q=n/2&55,p=q%8)>5&&q-39?8|y&1:y,(p&5^5?x&6:q-23?8:y&6)|x&1,(p<5?p*2:p<6?x&6:p%q<7?y&6:8)|n&1] ``` [Try it online!](https://tio.run/##XY3RboMgFIbvfQpuSmEBJzqccwJXe4JeNl3CbO26NIDWLJr47s7Kupr9FyQf33/O@dLf@lI2J9dSY/eHsRKjEXKLOmGkfCK96KRMSC3MYww5J07UqwxLDmFNkxeVDT1keU@Qg/ydqw6meU3jRGV5D1M8dJBNquDKPcS5K9K54FZ18awmn2d4MJDtxtdtAED0EfmwiJEbMzY/C77@3HlusOjufcMz87jw8/Dffk/X3NhfW/b/@d8EuzCobPOmy09kgJCgtOZiz4fwbI/IhK3dtM3JHFGMQ6f3m1Y3LZq2gggTsKZUrgmokMEYjz8 "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), ~~118~~ 117 bytes Takes input as an integer. Returns an array of three decimal digits. ``` n=>[(x=n>>4&7,y=n>>7,p=n/2&7)>5&&p<7|x/2^2?8|y&1:y,(p<7?p-5?x:8:x/2^1?8:y&6)|x&1,(p<5?p*2:p<6?x&6:p<7|x<2?y&6:8)|n&1] ``` [Try it online!](https://tio.run/##XY3NbsMgEITvfgpOBCrsGFT/iBo49QlyjFKJOHGaKgLkoMqW/O6ubZrG6hxW@@0Mw5f@1ve6vTofG3s6j40YjZB71Akj5SssSD8vBXHCbBkssMwgdFUxdFv2wVQ59JDynqDppFycqY6XfLaoKnkPczx0kM5uptwL467KVQdzvhRUTE0JXuLBQHoY3/YRAOkxDaIpJQ@mdBkrni9PXhI0ffohEZgGXPnL47/@QLMeHH5b5//5v4oOSdTY9l3Xn8gAIUFtzd3ezsnNXpBJvN359mouiOHE6dPO69ajqRWkmIBNHMsNAQ0yGOPxBw "JavaScript (Node.js) – Try It Online") ## How? Instead of trying to apply the 'official' algorithm, this code is based on some kind of reverse-engineering of the patterns that can be found in the expected results. Given the input integer \$n\$, we compute: $$\begin{align}&x=\left\lfloor\frac{n}{16}\right\rfloor \bmod 8\\ &y=\left\lfloor\frac{n}{128}\right\rfloor\\ &p=\left\lfloor\frac{n}{2}\right\rfloor \bmod 8\end{align} $$ ### Example: first digit (hundreds) ``` x | 0 | 1 | 2 | 3 n & 1 | 0101010101010101 | 0101010101010101 | 0101010101010101 | 0101010101010101 p | 0011223344556677 | 0011223344556677 | 0011223344556677 | 0011223344556677 ------+------------------+------------------+------------------+----------------- y = 0 | 0000000000008888 | 0000000000008888 | 0000000000008888 | 0000000000008888 y = 1 | 1111111111119999 | 1111111111119999 | 1111111111119999 | 1111111111119999 y = 2 | 2222222222228888 | 2222222222228888 | 2222222222228888 | 2222222222228888 y = 3 | 3333333333339999 | 3333333333339999 | 3333333333339999 | 3333333333339999 y = 4 | 4444444444448888 | 4444444444448888 | 4444444444448888 | 4444444444448888 y = 5 | 5555555555559999 | 5555555555559999 | 5555555555559999 | 5555555555559999 y = 6 | 6666666666668888 | 6666666666668888 | 6666666666668888 | 6666666666668888 y = 7 | 7777777777779999 | 7777777777779999 | 7777777777779999 | 7777777777779999 x | 4 | 5 | 6 | 7 n & 1 | 0101010101010101 | 0101010101010101 | 0101010101010101 | 0101010101010101 p | 0011223344556677 | 0011223344556677 | 0011223344556677 | 0011223344556677 ------+------------------+------------------+------------------+----------------- y = 0 | 0000000000008800 | 0000000000008800 | 0000000000008888 | 0000000000008888 y = 1 | 1111111111119911 | 1111111111119911 | 1111111111119999 | 1111111111119999 y = 2 | 2222222222228822 | 2222222222228822 | 2222222222228888 | 2222222222228888 y = 3 | 3333333333339933 | 3333333333339933 | 3333333333339999 | 3333333333339999 y = 4 | 4444444444448844 | 4444444444448844 | 4444444444448888 | 4444444444448888 y = 5 | 5555555555559955 | 5555555555559955 | 5555555555559999 | 5555555555559999 y = 6 | 6666666666668866 | 6666666666668866 | 6666666666668888 | 6666666666668888 y = 7 | 7777777777779977 | 7777777777779977 | 7777777777779999 | 7777777777779999 ``` Algorithm: * If \$p<6\$, we have \$d=y\$ * If \$p=6\$, we have \$d=8+(y\bmod2)\$ * If \$p=7\text{ AND }(x<4\text{ OR }x>5)\$, we have \$d=8+(y\bmod2)\$ * If \$p=7\text{ AND }(x=4\text{ OR }x=5)\$, we have \$d=y\$ As JS code: ``` p > 5 && p < 7 | x / 2 ^ 2 ? 8 | y & 1 : y ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~126~~ ~~119~~ ~~117~~ ~~112~~ 111 bytes ``` (a,b,c,d,e,f,g,h,i,j)=>[(g&h&i+(b+=a*4+b,e+=d*4+e)!=5?8:b)+c,(g&i?h+e-3?8:b:e)+f,(g?h<i?e:h>i*e?b:8:h*4+i*2)+j] ``` [Try it online!](https://tio.run/##fZJRb5swEMff@RTGD8jOuQ5NMwlBHZQ@pJq0h2p5rKbVgAFHDBC4VaQqnz01bJnGSvtyOp3vd//72z7IF9mnnW7NVd1k6rwTZyJZwlKWMcVyVrCSaXagYvNICq/0NJAEhFysIWEKRGYTRV3xJQ7ChELKbJOOS1BXN0MlVBRyW4vLWx2rsNzohYqTMAhLy@nFisLhxzl/rlOjmxrdzyqjVwfpHBG3oKhT5rmr0eOov1hZvXEBm@Xsz0g7MXKQqno1UoXnlp6rP0eDOWiWCWz3hfufmeoEE4XLhCnjZp6rvPFap2DwGTJLXLrfm5nTmBp6T3y41O/Wk@O0su@RQH7k5E1HXmSHtPAjfXvtr9aRBhifbSgfbZfmptmbTtcFWVHeymxvZGfItc98aoXTpu6bSvGqKciRd6qtZKrIkvDXmxP9G9cnumTkJxv/iP2PEjDCkIwxpWwrdoRzfuR9W2nz9MR/yZYYsQFDKbsT9x8fYgxbIWy8i8lgC4Dhh@1@j2mId9uv3zC1hv/dET8M5r9LoxBGgMarAJsu0eAe0@j8Bg "JavaScript (Node.js) – Try It Online") **-5 bytes thanks @tsh** (and 2 by myself) So `l` can make more effort than I expected. **-2 more bytes using @tsh's technique!** **-5 bytes thanks @Arnauld** **-1 byte thanks @Neil** Input as a list of 10 bits (as 10 arguments), output as a list of 3 digits. [Answer] # [Python 3](https://docs.python.org/3/), ~~229 ... 97~~ 96 bytes ``` lambda a:[[a&6,a>>4&6,a>>7&6,8][b" eW7B]Oys"[~a&8or~a&6or~6|a>>4]%x&3]|a>>x%9&1for x in[7,4,9]] ``` [Try it online!](https://tio.run/##VY9NboMwEIX3PoUbKRhLVoTzAzgSWfQCXXTRBfHCSYlKRQBhIyVS1atTj4dU7SzGfh9vnpn@7j66djNdiuPUmOvp3VCzL0sTpcIcDls8Mn/kujwtKK3esmf9creL8ttEeTf4nvqefoFbL2/RRsP1tlSRvHQDvdG6LTOxFUrrydKCMsYSLJlI6itJdgSUDC2QdIMEGJJMEZzxQ0kgKiGYAS4kOZEIZs9OrQkGy/kttZUENRSQ3CfL@W2cUnlKHg70KBU8/4nfgxBYqGzqtlrZvqldzCnsDMCvTe1M2bFlXBPiKuvOxlZhKq5bF4MSay4oiG50/eg4ZoQvSEKUHwdsBD2B/o3aE/iffoAAw/@Ii5fejMhYWw0uPMnY6rOr2/hq@ti6QYDPFy2KhxnnOcGTvY7nc2XtE@PTDw "Python 3 – Try It Online") *-4 bytes by @xnor* *-6 bytes by @nwellnhof* Formatted: ``` h = lambda a:[ [a&6, a>>4&6, a>>7&6, 8][ List to take high bits from b" eW7B]Oys"[ 10 char string; where to get high bits for indicator values 1-8. 0th,1st chars not used. ~a&8 or ~a&6 or ~6|a>>4] Compute indicator (by @nwellnhof) %x&3] High bits of each digit | a >> x%9 & 1 bitwise OR with low bit of each digit for x in [7,4,9]] ``` ### Explanation Because I originally wanted to implement this in Jelly, I take a different approach from most answers here, which is simple and perhaps suited to a golfing language. Though the golfed function takes an integer, let the input as a bit list be `[a0,a1,...,a9]`. Then we can derive three values from the input * The low bits `[a2,a5,a9]`: These will always be the low bits of `[d0,d1,d2]` respectively. * The high bits `[2*a0a1,2*a3a4,2*a7a8,8]`: The high bits of each digit will be one of these. * The indicator bits, `[a3,a4,a5,a7,a8]`, determining how to get the high bits of each digit. We compute the indicator (between 1 and 8) as follows: + If a5 == 0, the indicator is 8 (originally 0, but using 8 instead saves a byte) + If a3 nand a4, the indicator is 6 - 2\*a3a4 + Otherwise the indicator is 2\*a7a8 + 1 (actually calculated as a negative number). Then the nth digit can be elegantly computed as `high_bits[arr[indicator][n]] | low_bits[n]` by the table below, which is compressed into a string. ``` arr = [ [0,1,2], [3,1,2], [1,3,2], [2,1,3], [2,3,3], [3,2,3], [3,3,2], [3,3,3] ] ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~138~~ 129 bytes ``` f(w){int t=w/2&55,s=t%8,v=w/16,u=v/8;w=((s<6|t==39?u:8|u%2)*10+v%2+(s&5^5?v&6:t-23?8:u&6))*10+w%2+(s<5?s*2:s<6?v&6:s%t<7?u&6:8);} ``` [Try it online!](https://tio.run/##TZDRboMgFIav9SlIEw2ojYDDgkp8kK5NNjcXL2aXipqs9dkdAibjgsDHd84PNMevplnXFs7o0fUKKDmnNGQsGaQKeDLpLcmTUU4pL2cJ4VDlTyVlJuqx4M8xoCgiOJ4CGsMhZFdWT2FeqCPNal6MYY7M8WyOK1YPES10ByMNgapOtXYKjspl3cK/37oeIvDwPXOV8wVIvcHv2A6CSQLSFGDMLCTETBbm2Q437OBJ7OUaEmyhwM60roNcQ2LZbjJBjWka7unihWwmsUkunZsg4i7kygXPXfk/UwhnugF26C2l77W3O4Db4zuJS9BVQ/f7eWuhQqlbRQppHsfml7yfu3ZbeAhw9vHaHxKg1XN3QUi3Wvxl/QM "C (gcc) – Try It Online") First extracts some bits into variables `s` and `t`, so that the eight rows of the conversion table can be identified by: ``` 1. s < 4 u v w¹ 2. s = 4 u v 8¹ 3. s = 5 u 8 v 4. s = 6 8 v u 5. s = 7, t = 7 8 8 u 6. s = 7, t = 23 8 u 8 7. s = 7, t = 39 u 8 8 8. s = 7, t = 55 8 8 8 ¹ Can be computed with s*2 ``` Then sets up `u` and `v` with divisions (right shifts), so that `u`, `v` and the input `w` contain the lower three BCD bits in positions 0-2. The rest is bit shuffling depending on `s` and `t`. Two notable tricks are: ``` s&5^5 // Rows 1, 2 and 4. s%t<7 // Rows 1-5. ``` A port of [Shieru Asakoto's Javascript solution](https://codegolf.stackexchange.com/a/176375/9296) is only **124 bytes**: ``` f(a,b,c,d,e,f,g,h,i,j){a=(((g&h&i+(b+=a*4+b,e+=d*4+e)!=5?8:b)+c)*10+(g&i?h+e-3?8:b:e)+f)*10+(g?h-i|h&!e?h?b:e:8:h*4+i*2)+j;} ``` [Try it online!](https://tio.run/##TZDRbsIgFIav61OgyRooGMFaLXW1D@K8aCsIJtPFNV7M9dk7CqfJuOCHj//ww2mXl7YdBo1r1rCWnZliml2YYZZdyasuMcaX2MSW4oaWdbKhDVO0PLuFIvMyq/KiIbQlieDUGW1lqFqmIy0UoRp4ZZb218RzVZnKHRR5YdwFNlkTet33g7116LO2N0zQaxaNu@54QqXb8IaHIbhgaLVCnGcBCuGnALfpBEcMcCencgcFD1BycAYvwNxBEdjkzOTaO/2FU7rciNEpQhKk5z5IwIOgXOZbKP/nlBKcMNAEo34/i/T9gfD4eVvyPbLv3/ZH3TXuyApWSUccp9R3ybfp6ZrUHe3JVUdfD0c0Xrzx9PxxWzCk8fNwkLGLdpqD7kC3oBnoBjQFXYMKr7EgxGX0s374Aw "C (gcc) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~153 ... 119~~ 117 bytes ``` ->n{n+=n&896;a,b,c=n&1536,n&96,n&14;"%x"%n+=c<9?0:2036+[b/16-b-1918,r=a>>8,[r+126,a/16-26,a-1978,38][b/32]-a][c/2-5]} ``` [Try it online!](https://tio.run/##TZBBDsIgEEX3nqIxsZsOlgGLjLX1IIQFNHFnY5qYaNSzVyjVymIgj8d8YLj5x3huRtb2z75o@lyTqh146MIaK6mgzykW3NXrzX29CVJ3pBM/CC5VYXyJinmGhBqGxrWtBjMUKBS4uBPnsLnXILUNshSWOWu6UrDKvkdjuOdpIEeoLKwSQZwKKPmHIkTY0w9NHnIgvljJA9IJYSLRqkh8talTTKQdzh6mhJCpvwk432Jqp5azs0e0eP/Mbi/u@nyFT3xl18w4OBtnwYfnfgA "Ruby – Try It Online") ### How it works: ``` ->n{n+=n&896; ``` This is the starting point: convert to BCD by shifting 3 bits to the left, which works for most of the patterns. ``` a,b,c=n&1536,n&96,n&14; ``` Get the middle bits of each nibble (and one extra bit of the third nibble, but mask the least significant bit). ``` "%x"%n+=c<9?0 ``` If the third digit is less than 10 (less than 9 because we never cared for the LSB anyway), we're set: this is plain BCD, we can output the hex without changing anything ``` :2036+[b/16-b-1918,r=a>>8,[r+126,a/16-26,a-1978,38][b/32]-a][c/2-5]} ``` Otherwise do some black magic by shifting bits around and adding magic numbers until we get the result we want. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~51~~ ~~48~~ ~~40~~ 39 bytes ``` &\‘f4;s3ɓạ4ḅ-œ?µ/Ḥ “MY-€-Y¤©¡‘Dịs3Ḅç+ƭ/ ``` [Try it online!](https://tio.run/##y0rNyan8/18t5lHDjDQT62Ljk5Mf7lpo8nBHq@7RyfaHtuo/3LGE61HDHN9I3UdNa3QjDy05tPLQQqBil4e7u4uNH@5oObxc@9ha/f8Pd29R8Fd4uKNJ4dBWhaN7FA63A9UreIOIyP//DSDA0MCQC0QZggkIE8QBM8HihgZcEHUgcS5DCAsiClYIMgHCAAEuQ6hRUAUIUSgAAA "Jelly – Try It Online") ### Algorithm With the exception of list indices, all integers in this section are written in binary. Given input \$\alpha\beta\gamma\delta\varepsilon\zeta\eta\theta\iota\kappa\$, we first construct the arrays \$[\eta\eta, \theta\iota, \delta\varepsilon]\$, \$[\alpha\beta, \delta\varepsilon, \theta\iota]\$, and \$[\gamma, \zeta, \kappa]\$. 1. If \$\eta\eta = 00\$, all three output digits are low (\$0000\$ to \$0111\$). 2. If \$\eta\eta = 11\$ but \$\theta\iota < 11\$, exactly one output digit is high (\$1000\$ or \$1001\$). 3. If \$\eta\eta = \theta\iota = 11\$ but \$\delta\varepsilon < 11\$, exactly two output digits are high. 4. If \$\eta\eta = \theta\iota = \delta\varepsilon = 11\$, all three output digits are high. If we count the number of leading \$11\$'s \$[\eta\eta, \theta\iota, \delta\varepsilon]\$, create an array of a matching number of \$100\$'s, concatenate it with \$[\alpha\beta, \delta\varepsilon, \theta\iota]\$, and split the result into subarrays of length three, we get the following results in each case. 1. \$[[\alpha\beta, \delta\varepsilon, \theta\iota]]\$ 2. \$[[100, \alpha\beta, \delta\varepsilon], [\theta\iota]]\$ 3. \$[[100, 100, \alpha\beta], [\delta\varepsilon, \theta\iota]] = [[100, 100, \alpha\beta], [\delta\varepsilon, 11]]\$ 4. \$[[100, 100, 100], [\alpha\beta, \delta\varepsilon, \theta\iota]] = [[100, 100, 100], [\alpha\beta, 11, 11]]\$ In the first and last case, we just have to zip the first array with \$[\gamma, \zeta, \kappa]\$, yielding \$[\alpha\beta\gamma, \delta\varepsilon\zeta, \theta\iota\kappa]\$ in the first case and \$[100\gamma, 100\zeta, 100\kappa]\$ in the last. The remaining two cases are similar, but the arrays \$[100, \alpha\beta, \delta\varepsilon]\$ and \$[100, 100, \alpha\beta]\$ have to be reordered, according on the values of \$[\theta\iota]\$ and possibly \$\delta\varepsilon\$. In the second case, the six permutations of \$[100, \alpha\beta, \delta\varepsilon]\$ are \$[100, \alpha\beta, \delta\varepsilon]\$, \$[100, \delta\varepsilon, \alpha\beta]\$, \$[\alpha\beta, 100, \delta\varepsilon]\$, \$[\alpha\beta, \delta\varepsilon, 100]\$, \$[\delta\varepsilon, 100, \alpha\beta]\$, and \$[\delta\varepsilon, \alpha\beta, 100]\$. By computing \$100-\theta\iota\$, we map \$00\$, \$01\$, and \$10\$ to four, three and two, selecting the permutations \$[\alpha\beta, \delta\varepsilon, 100]\$, \$[\alpha\beta, 100, \delta\varepsilon]\$, and \$[100, \delta\varepsilon, \alpha\beta]\$. After zipping the result with \$[\gamma, \zeta, \kappa]\$, we get \$[\alpha\beta\gamma, \delta\varepsilon\zeta, 100\kappa]\$, \$[\alpha\beta\gamma, 100\zeta, \delta\varepsilon\kappa]\$, or \$[100\gamma, \delta\varepsilon\zeta, \alpha\beta\kappa]\$. In the third case, the permutations (with duplicates) of \$[100, 100, \alpha\beta]\$ are \$[100, 100, \alpha\beta]\$, \$[100, \alpha\beta, 100 ]\$, \$[100, 100, \alpha\beta]\$, \$[100, \alpha\beta, 100 ]\$, \$[\alpha\beta, 100, 100]\$ and \$[\alpha\beta, 100, 100]\$. By computing \$(100 - \theta\iota) - (100 - \delta\varepsilon) = \delta\varepsilon - \theta\iota = \delta\varepsilon - 11\$, we map \$00\$, \$01\$, and \$10\$ to three, four, and five modulo six, selecting the permutations \$[100, 100, \alpha\beta]\$, \$[100, \alpha\beta, 100 ]\$, and \$[\alpha\beta, 100, 100]\$. After zipping the result with \$[\gamma, \zeta, \kappa]\$, we get \$[100\gamma, 100\zeta, \alpha\beta\kappa]\$, \$[100\gamma, \alpha\beta\zeta, 100\kappa]\$, or \$[\alpha\beta\gamma, 100\zeta, 100\kappa]\$. ### Code ``` “MY-€-Y¤©¡‘Dịs3Ḅç+ƭ/ Main link. Argument: A (array of 10 bits) “MY-€-Y¤©¡‘ Array literal; yield [77, 89, 45, 12, 45, 89, 3, 6, 0]. D Decimal; yield [[7,7], [8,9], [4,5], [1,2], [4,5], [8,9], [3], [6], [0]]. ị Retrieve the elements of A at those indices. Indexing is 1-based and modular, so 1 is the first index, while 0 is the last. s3 Split the results 2D array of bits into chunks of length 3. Ḅ Convert the 9 arrays of bits from binary to integer. ç+ƭ/ Reduce the resulting array (length 3) once by the helper link, then by addition. &\‘f4;s3ɓạ4ḅ-œ?µ/Ḥ Helper link. Arguments: B, C (arrays of three integers each) &\ Cumulatively reduce B by bitwise AND. ‘ Increment the results by 1. f4 Filter; keep only integers equal to 4. ; Concatenate the result with C. s3 Split the result into (one or two) chunks of length 3. ɓ µ/ Reduce the array of chunks by the following chain. ạ4 Take the absolute difference of the integers in the right chunk and the integer 4. ḅ- Convert the resulting array from base -1 to integer, i.e., map [x] to n = x and [x, y] to n = y - x. œ? Take the n-th permutation of the left chunk. Ḥ Unhalve; multiply the resulting integers by 2. ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~191~~ 181 bytes ``` (...)(...) :$1,$2; ..(.),11(.);111 100$1,100$2;100 (10|(..)(.,)01)(.);111 100$3$2$4;100 (..)(.),(00.);111 100$2,1$3;0$1 (..)((.{5});110|(.);101) 100$3$4;$1 1 01 +`10 011 .0+(1*) $.1 ``` [Try it online!](https://tio.run/##TU67DgIxDNvzHR1arori3rHQn4GBgYUBsQHfXvKodJfBcW3H6uv@fjxvY2RmLg50SaipdWLOXCqg2AEQRNQxbF2RMuSb/aoWQTnG1tTSFiEPlJpFDn6rSGvXuvAzf84/c61Qt7bNmq1rBiSg5QrRDWJZMk6FEmMMidELsgWHoPZw6rode850QrBQPWgNQeCfnFUzsKtz/g "Retina 0.8.2 – Try It Online") Link includes test cases. Edit: Saved 10 byte by not padding digits to 4 bits except where necessary. Explanation: ``` (...)(...) :$1,$2; ``` Insert separators so that each digit can be converted to decimal separately. This effectively handles the first two cases in the conversion table. ``` ..(.),11(.);111 100$1,100$2;100 ``` Handle the last (eighth) case in the conversion table. ``` (10|(..)(.,)01)(.);111 100$3$2$4;100 ``` Handle the sixth and seventh cases in the conversion table. ``` (..)(.),(00.);111 100$2,1$3;0$1 ``` Handle the fifth case in the conversion table. ``` (..)((.{5});110|(.);101) 100$3$4;$1 ``` Handle the third and fourth cases in the conversion table. ``` 1 01 +`10 011 .0+(1*) $.1 ``` Perform binary to decimal conversion. [Answer] # [Python 2](https://docs.python.org/2/), 157 bytes ``` lambda a,b,c,d,e,f,g,h,i,j:[c+[a*4+b*2,8][g*h*~(d*~e*i)],f+[d*4+e*2,8,a*4+b*2][g*i+(d<e)*g*i*h],j+[h*4+i*2,[8,[a*4+b*2,d*4+e*2][h<i]][h^i or(h&i-(d|e))]][g]] ``` [Try it online!](https://tio.run/##bY59a4MwEIf/91McDGYSb2BcX7S0nyTLwDbRpLRWimMMRr@6O43oBstBCM89@d21X527NVlfHd76S3k9mhJKPOIJDVqssEaHHs87dUpUKVbJUWSYa1ULJx7MiIcVnmusEmWoaYcmTtog@YSZveWCXsJpPCfKUdOTpnKc86avWrm913S/e7jdmXv2L8x8W86J1Vr3n85fLMhdBP7gm/ajYzyC9u6bDiomrmXL6Ime8z5Ow5GpjOEJ6KRU62jgUo7XzDfwOvGhs/AtFFHIIS7TmReQBj/8@MXzKJYBL/6aeDb4Y/iyTwErkOTLMHjeJw9z5bTlnEPpsAk5f/xiqNH/h/8A "Python 2 – Try It Online") [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~238~~ ... 189 bytes *-2 bytes thanks to Neil* ``` import StdEnv $a b c d e f g h i j=100*(c+2*b+4*a)+10*(f+2*e+4*d)+j+2*i+4*h-2*(h*(99*b+198*a-394)+i*(9*e+18*d+h*(e+2*d-4+(b+2*a-4)*(1-10*e-100*d+110*e*d))-35)-4)*g+0^(e+d)*(2*b+4*a-8*i*h*g) ``` [Try it online!](https://tio.run/##bZBNT@MwEIbP7a@YAxL@GAs7TSGR4MYekPbG3kpWcmM3cdWmEXUX8ec3O6mzQCV8sGb8zDvzjuudt92wP7jTzsPehm4I@/7wGuE5uh/dn/mVhTXU4MDDBhpoIcD2wWgtWC0zsZa5sFwaSjeUekodl1sKA4WtygRrBStLKjRlIaxalDmXgZ6o1hTCScKeyp3KJVtTYFXOBTOKWno1znHSjDH15Wqx5CNupP5NKkeFkwVViCBa0fDhOVoy/wArdjjF/hQB4Qq@2YEDvLwAW1lcY40OPW6wwRYDbiuEpOVwr@hPemC27zNgY@hCE@Kvw1MXEQJ5guiP8VjN31r/6uHmBjKTz2fnx9HFfDZjq2udjtHmusKVRo3LiuMHowXHK7FbXFyykU7sDsuv7Kw0OrES9YUuKf@z4oOZhCbdklj2RXceNvksMUfzqTPJTPJZXHgx0wapJ03D24uen7qS5pGOUDX8rTc72xwH9fRzeHzv7D7Ux38 "Clean – Try It Online") Takes a 'list' of 10 bits in the form of 10 arguments, using a direct formula to compute the result. [Answer] # Perl 5, 195 bytes ``` sub f{$n=shift;@p=((map{($n>>$_&3)*2}(8,5,1)),8);for(16390,28935,29005,227791,29108,225788,226803,228863){return 2*$n&256|$n&17|$p[$_>>4&3]<<8|$p[$_/4&3]<<4|$p[$_&3]if($_>>12&$n/2)==($_>>6&63);}} ``` [Try it online](https://tio.run/##ZZDRasIwFIbvfYrgYkkkzHMS26bUlr3DbgbbEMWWCRpDVRjUPnuXNGNY91@ck//jPychtmoOcd@fr1tSt9QU5699fclfbMHYcWNbRk1Z0nWk@Fx2TItYIOdC87w@NQwTlYGQOlOxkBmAqzJNM3QGQTsTp9q3RINyTetE8bapLtfGEDmnJpJxcnMN0xu173RdlstIfa5WOthFcMvg3HlfMx9CGVGzkLwoBptEbm3edf0TeT0dK1J9b472UJ0n7omEwRYAEV0BFBPi5dGgB@RTrozRMDoedAhhlAq5P4SBjFPDovsbA/C6Q@EJD4P/U7/ipHXQNntzqdl0Z3dsBs8IW17MQL19mKmga@E/jfN80vU/) I know 195 bytes is far too much for this contest, but I had no idea how to further compress the Perl code. Suggestions? ## Explanation of the code In a more readable version, the code intention should become apparent: ``` sub dpd { my $n = shift; my $v=2*($n&128)|$n&17; my @p=((map{($n>>$_&3)*2}(8,5,1)),8); for (16390,28935,29005,227791,29108,225788,226803,228863) { return $v |$p[$_>>4&3]<<8|$p[$_>>2&3]<<4|$p[$_&3] if(($_>>12&$n/2)==($_>>6&63)); } } ``` In the rules for DPD encoding, each line is encoded into a 18 bit value, segmentation into (6,6,(2,2,2)) bits. * The first 6 bits are an appropriate bit mask for the bits 1 (=h) to 6 (=d) of the input (bit 4 = f is redundant, but it simplifies the evaluation code to have it included). * The next 6 bits are the value bits for this bit mask. The values are checked on all places where the bit mask has a 1 value. * The following 3\*2 bits contain the indices for the array `@p` for the 3-bit sequences which are to spliced into bits 11-9, 7-5 and 3-1 of the result. * The array `@p` is constructed from bits 9-8, 6-5, 3-2 of the input, and the number `8` as fourth member * The bits at position 7,4 and 0 of the input are transferred directly into bits 8,4 and 0 of the result. For example, the first number in the list, `16390`, which is `100000000000110` as a bit field, carries the following information: ``` 000100 : bit mask says: only consider bit 3 of the input 000000 : bit values say: bit 3 should be 0 00 : use '0ab' as higher bits of first digit 01 : use '0de' as higher bits of second digit 10 : use '0gh' as higher bits of third digit ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 84 bytes Port of [KimOyhus' answer](https://codegolf.stackexchange.com/a/178360/6484) to 05AB1E. ``` •4’7þ2Ô€iΘEuĆΣk4Ѐ:ΘΛs‡CaΔʒì₁3¶rdiMß¡þи иø-˜)Â∍DY—WûQ@—Mā}Γ¤ÒÙ]p•44в2ôvÐyèP≠«}4ôC3.£ ``` [Try it online!](https://tio.run/##AZ8AYP9vc2FiaWX//@KAojTigJk3w74yw5TigqxpzphFdcSGzqNrNMOQ4oKsOs6Yzptz4oChQ2HOlMqSw6zigoEzwrZyZGlNw5/CocO@0Lgg0LjDuC3LnCnDguKIjURZ4oCUV8O7UUDigJRNxIF9zpPCpMOSw5ldcOKAojQ00LIyw7R2w5B5w6hQ4omgwqt9NMO0QzMuwqP//zAwMDExMTEwMDE "05AB1E – Try It Online") Rough explanation: ``` •yadayada•44в2ô # encoded list of nand gates v # for each gate ÐyèP≠ # compute the output of the gate « # append it to the input } # end of the loop 4ô # split the list of bits in groups of 4 C # convert each from binary to decimal 3.£ # keep the last 3 numbers # implicit output ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~104~~ ~~103~~ 101 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` •3γã•S£©4èUXтÌ‹XSPVY®2èDˆTQ*~i0®нëт}®1èY¯`*i0®нëY_Xт>Ê*i0¯`ëт]®3èY¯`_*X110Q~i0®нëXт›iYiтë0¯`ëX]®θJ4ôC ``` Definitely not the right language for this kind of challenge, but ah well.. Input as string, output as list of three digits. [Try it online](https://tio.run/##yy9OTMpM/f//UcMi43ObDy8G0sGHFh9aaXJ4RWjExabDPY8adkYEB4RFHlpndHiFy@m2kECtukyDQ@su7D28@mJT7aF1hodXRB5an6AFE4yMB@qzO9wFElifAFIUe2idMURRvFaEoaFBINwAoMpHDbsyIzOBNq2GKI8Aqj63w8vk8Bbn//8NDIDKQdgQAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/0cNi4zPbT68GEgHH1p8aKXJ4RWhERebDvc8atgZERwQFnlondHhFS6n20ICteoyDQ6tu7D38OqLTbWH1hkeXhF5aH2CFkwwMh6oz@5wF0hgfQJYEVCVMURVvFaEoaFBINwEoNJHDbsyIzOBVq2GqI8AKT@3w8vk8Bbn/zqHtvw3gABDA0MuEGUIJiBMEAfMBIsbGnBB1IHEuQwhLIgoWCHIBAgDBLgMoUZBFSBEoQAA). **Explanation:** We have the following eight scenarios to consider: ``` 1st 2nd 3rd 4th 5th 6th 1st digit 2nd digit 3rd digit 1. ab c de f 0gh i → 0abc 0def 0ghi → '0'+1st 2nd '0'+3rd 4th 5th 6th 2. ab c de f 100 i → 0abc 0def 100i → '0'+1st 2nd '0'+3rd 4th 5th 6th 3. ab c gh f 101 i → 0abc 100f 0ghi → '0'+1st 2nd '100' 4th '0'+3rd 6th 4. gh c de f 110 i → 100c 0def 0ghi → '100' 2nd '0'+3rd 4th '0'+1st 6th 5. gh c 00 f 111 i → 100c 100f 0ghi → '100' 2nd '100' 4th '0'+1st 6th 6. de c 01 f 111 i → 100c 0def 100i → '100' 2nd '0'+1st 4th '100' 6th 7. ab c 10 f 111 i → 0abc 100f 100i → '0'+1st 2nd '100' 4th '100' 6th 8. xx c 11 f 111 i → 100c 100f 100i → '100' 2nd '100' 4th '100' 6th ``` I first split the (implicit) input into chunks of size `[2,1,2,1,3,1]` and store that list in the register: ``` •3γã• # Push compressed integer 212131 S # Convert it to a list of digits £ # Split the (implicit) input in chunks of that size © # Store it in the register (without popping) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•3γã•` is `212131` Now we're first going to built the 0s and 1s for the first digit of the output. Scenarios 1,2,3,7 use `'0'+1st+2nd`; and scenarios 4,5,6,8 use `'100'+2nd`: ``` 4è # Take the 5th item of the list U # Pop and store it in variable `X` XтÌ‹ # Check if `X` is below 102 ~ # OR XSP # `X` is equal to 111 VY # And store that result in variable `Y` * # and ®2è # Get the 3rd item from the list of the register Dˆ # Push it to the global array TQ # And check if it's equal to 10 i # If the combined check above is truthy (exactly 1): 0 # Push 0 to the stack ®н # Push the 1st item of the list to the stack ë # Else: т # Push 100 to the stack } # Close the if-else ®1è # And push the 2nd item of the list to the stack ``` Then we're going to built the 0s and 1s for the second digit of the output. Scenarios 1,2,4 use `'0'+3rd+4th`; scenarios 3,5,7,8 use `'100'+4th`; and scenario 6 uses `'0'+1st+4th`: ``` Y # Push `Y` (check if `X` equals 111) * # and ¯` # Push the item from the global array (3rd item of the list) i # If both checks above are truthy (exactly 1): 0 # Push 0 to the stack ®н # Push the 1st item of the list to the stack ë # Else: Y_ # Push inverted `Y` (check if `X` does NOT equal 111) * # and Xт>Ê # Check if `X` (5th item of the list) does NOT equal 101 i # If both checks above are truthy (exactly 1): 0 # Push 0 to the stack ¯` # Push the item from the global array (3rd item of the list) ë # Else: т # Push 100 to the stack ] # Close both if-else cases ®3è # And push the 4th item of the list to the stack ``` Then we're going to built the 0s and 1s for the third digit of the output. Scenarios 1,2 use `5th+6th`; scenario 3 uses `'0'+3rd+6th`; scenarios 4,5 use `'0'+1st+6th`; and scenarios 6,7,8 use `'100'+6th`: ``` Y # Push `Y` (check if `X` equals 111) * # and ¯`_ # Check if the item from the global array (3rd item of the list) is exactly 0 ~ # OR X110Q # Check if `X` (5th item of the list) equals 110 i # If the combined check above is truthy (exactly 1): 0 # Push 0 to the stack ®н # Push the 1st item of the list to the stack ë # Else: Xт›i # If `X` (5th item of the list) is larger than 100 (so 101/110/111): Yi # If `Y` (if `X` equals 111): т # Push 100 to the stack ë # Else: 0 # Push 0 to the stack ¯` # Push the item from the global array (3rd item of the list) ë # Else: X # Push `X` (5th item of the list) to the stack ] # Close all if-else cases ®θ # And push the last (6th) item of the list to the stack ``` Now we have all 0s and 1s on the stack, so we can convert it to the three output digits: ``` J # Join the entire stack together 4ô # Split it into parts of size 4 C # Convert each part from binary to an integer (and output implicitly) ``` ]
[Question] [ People on this site really love to embellish their post titles... ``` Stewie's sequence: + * - / + * - / ``` However, when this title needs to be included in the page URL, it is simplified: ``` stewies-sequence ``` --- # The Challenge Your task is to create a program or function which, given a string representing a post title, outputs/returns its "URL-Friendly" conversion. **The algorithm is:** * Convert to lowercase (where applicable) * Replace every space (), period (`.`), comma(`,`) or slash (`/`) with a dash (`-`) * Remove any non-alphanumeric characters, except dashes. * Minify groups of adjacent dashes (`a---b -> a-b`), remove any that are leading/trailing. Please note that this algorithm is a simplification, and may not always produce the same results as the site's real method. --- # Rules * You can assume that input: + Will not be empty. + Will contain at least one alphanumeric character. + Will only contain characters in the ASCII range 32-126 (printable) * Full programs or functions are permitted. * A builtin which does the exact task specification is *not* permitted. * **This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution (in bytes) wins!** --- # Test Cases Most posts on this site will serve as tests, but here's a handy list: ``` Loading... Forever -> loading-forever N(e(s(t))) a string -> nest-a-string "Hello, World!" -> hello-world URL-Friendly titles -> url-friendly-titles C.U.S.R.S -> c-u-s-r-s 1+2+3+4+...+n = -1/12? -> 1234-n-1-12 How can I use cmp(a,b) -> how-can-i-use-cmpa-b ``` Some longer ones... ``` Export The $PATH Variable, Line-By-Line -> export-the-path-variable-line-by-line Do n and n^3 have the same set of digits? -> do-n-and-n3-have-the-same-set-of-digits Quine Anagrams! (Cops' Thread) -> quine-anagrams-cops-thread The Golfer Adventure - Chapter 1 -> the-golfer-adventure-chapter-1 Bootloader golf: Brainf*** -> bootloader-golf-brainf ``` And some edge-case checking samples (feel free to suggest more): ``` 0123 -> 0123 a a1 -> a-a1 2-1=1 -> 2-11 ``` [Answer] ## JavaScript (ES6), ~~90~~ ~~82~~ ~~79~~ 75 bytes This is an attempt to do the job with a single `replace()`. This code extracts only the characters that we're interested in and ignores everything else. There's some additional logic to process the hyphens. ``` s=>(s.toLowerCase().replace(/[ a-z,-9]/g,c=>S=c<'0'?s+'-':s=s?S+c:c,s=0),s) ``` ### Test cases ``` let f = s=>(s.toLowerCase().replace(/[ a-z,-9]/g,c=>S=c<'0'?s+'-':s=s?S+c:c,s=0),s) console.log(f(`Loading... Forever`)); // -> loading-forever console.log(f(`N(e(s(t))) a string`)); // -> nest-a-string console.log(f(`"Hello, World!"`)); // -> hello-world console.log(f(`URL-Friendly titles`)); // -> url-friendly-titles console.log(f(`C.U.S.R.S`)); // -> c-u-s-r-s console.log(f(`1+2+3+4+...+n = -1/12?`)); // -> 1234-n-1-12 console.log(f(`How can I use cmp(a,b)`)); // -> how-can-i-use-cmpa-b console.log(f(`Export The $PATH Variable, Line-By-Line`)); // -> export-the-path-variable-line-by-line console.log(f(`Do n and n^3 have the same set of digits?`)); // -> do-n-and-n3-have-the-same-set-of-digits console.log(f(`Quine Anagrams! (Cops' Thread)`)); // -> quine-anagrams-cops-thread console.log(f(`The Golfer Adventure - Chapter 1`)); // -> the-golfer-adventure-chapter-1 console.log(f(`Bootloader golf: Brainf***`)); // -> bootloader-golf-brainf console.log(f(`0123`)); // -> 0123 console.log(f(`a a1`)); // -> a-a1 console.log(f(`2-1=1`)); // -> 2-11 console.log(f(',a^a,')); // -> aa ``` [Answer] # [V](http://github.com/DJMcMayhem/V), ~~41, 40, 37~~, 36 bytes ``` VuÍ[ .,\/]/- Í0-9a-z­] Í-«/- Í^-ü-$ ``` [Try it online!](http://v.tryitonline.net/#code=VnXDjVsgLixcL10vLQrDjcKEMC05YS16wq1dCsONLcKrLy0Kw41eLcO8LSQ&input=IkhlbGxvLCBXb3JsZCEi) or [Check all test cases at once!](http://v.tryitonline.net/#code=Vkd1w41bIC4sXC9dLy0Kw43ChDAtOWEtesKtXQrDjS3Cqy8tCsONXi3DvC0k&input=IkhlbGxvLCBXb3JsZCEiCkxvYWRpbmcuLi4gRm9yZXZlcgpOKGUocyh0KSkpIGEgc3RyaW5nCiJIZWxsbywgV29ybGQhIgpVUkwtRnJpZW5kbHkgdGl0bGVzCkMuVS5TLlIuUwoxKzIrMys0Ky4uLituID0gLTEvMTI_CkhvdyBjYW4gSSB1c2UgY21wKGEsYik) As usual, here this contains a bunch of unprintable and non-ASCII characters, so here is a hexdump: ``` 0000000: 5675 cd5b 202e 2c5c 2f5d 2f2d 0acd 8430 Vu.[ .,\/]/-...0 0000010: 2d39 612d 7aad 5d0a cd2d ab2f 2d0a cd5e -9a-z.]..-./-..^ 0000020: 2dfc 2d24 -.-$ ``` It's challenges like these where V's "Compressed regex" system come in handy. # Explanation First things first, we will convert everything to lowercase. Fortunately there is a really convenient way to do this in two bytes. I wrote a tip about that [here](https://codegolf.stackexchange.com/a/90098/31716). So we do ``` V " Visually select this whole line u " Convert this whole line to lowercase ``` After that we do a bunch of compressed substitute commands. A nice overview of how V's compressed regex works can be foud [here](https://github.com/DJMcMayhem/V/wiki/Regexes), but the basic idea is we can set the high-bit to avoid having to escape certain characters. Another convenience is that ranges (like `:%`) and flags (like `/g`) are automagically filled in. But in the end, it all translates to vim substitute commands. In fact, we could even directly translate the rest of the program to vim. That would give us this: ``` :%s/[ .,/]/-/g :%s/[^0-9a-z\-]//g :%s/-\+/- :%s/^-\|-$//g ``` If you speak vim-regex, it should be more clear what the rest of the program does now. So here is the rest of the program: ``` Í " Substitute: [ .,\/] " a space, period, comma or forward slash. (Due to a strange bug, this needs to be escaped) /- " with a dash Í " Remove: [^0-9a-z­] " Any character that is not a dash or alpha-numeric Í " Substitute: -« " One or more dashes /- " with one dash Í " Remove: ^- " A dash at the beginning of a line ü " OR -$ " a dash at the end of a line ``` [Answer] # JavaScript (ES6) 91 ~~96~~ *1 bytes saved* thx @ETHproductions ``` s=>s.toLowerCase().replace(/([ .,/-])|\W|_/g,(c,d)=>d?'-':'').replace(/^-*|-*$|-(?=-)/g,'') ``` **Test** ``` F= s=>s.toLowerCase().replace(/([ .,/-])|\W|_/g,(c,d)=>d?'-':'').replace(/^-*|-*$|-(?=-)/g,'') ;[['Loading... Forever.....', 'loading-forever'], ['N(e(s(t))) a string', 'nest-a-string'], ['"Hello, World!"', 'hello-world'], ['URL-Friendly titles', 'url-friendly-titles'], ['C.U.S.R.S','c-u-s-r-s'], ['1+2+3+4+...+n = -1/12?', '1234-n-1-12'], ['How can I use cmp(a,b)', 'how-can-i-use-cmpa-b'], ['Export The $PATH Variable, Line-By-Line', 'export-the-path-variable-line-by-line'], ['Do n and n^3 have the same set of digits?', 'do-n-and-n3-have-the-same-set-of-digits'], ['Quine Anagrams! (Cops\' Thread)', 'quine-anagrams-cops-thread'], ['The Golfer Adventure - Chapter 1', 'the-golfer-adventure-chapter-1'], ['Bootloader golf: Brainf***', 'bootloader-golf-brainf'], ['0123', '0123'], ['a a1', 'a-a1'], ['2-1=1', '2-11']] .forEach(t=>{ var i=t[0],k=t[1],r=F(i) console.log(r==k?'OK':'KO',i+' -> '+r,r==k?'':k) }) ``` [Answer] # Retina, ~~33~~ 31 bytes ``` T`L`l [^a-z ,-9]+ \W+ - ^-|-$ ``` (The program has a trailing newline) I'm not sure I can squeeze more out of this. This should cover everything. Came similar to Mama Fun Roll's. [Another 33 bytes version using recursive regexes](http://vihan.org/p/tio/?l=retina&p=C0nwScjhitbR1Y/V5tLl0k6I063RVamJjkvUrYpJ0Y3l@m@obaRtrG2iraenp52nYKuga6hvaGSvkAhkVinYAgA) [Try it online!](http://vihan.org/p/tio/?l=retina&p=C0nwScjhio5L1K1S0NG1jNXm4ooJ1@bS5YrTrdFV4fpvqG2kbaxtoq2np6edp2CroGuob2hkr5AIZFYp2AIA) ## Explanation ``` T`L`l ``` This line is simple, it converts to lowercase by **T**ransliterating `A-Z` (`L`) to `a-z` (`l`, lowercase). --- This stage is simple, it essentially gets rid of all unneeded characters to save ourselves a lot of trouble later on ``` [^a-z ,-9]+ ``` `[^a-z ,-9]` Matches any character that is NOT: * `a-z`: lowercase alphabet (remember entire string is lowercase because of previous item) * : space chacacter * `,-9` this is char code range of `,` to `9` which happens to be `,-./0123456789`, exactly the characters we need --- Next we convert all non alphanumeric chars to dashes (which is now just and `,./-`. ``` \W+ - ``` This won't (not) match `_` which is included in `\w` (negation of `\W`) because it was removed in the previous stage [Answer] # Python 3, ~~103~~ ~~100~~ ~~96~~ 95 bytes *5 bytes saved thanks to Flp.Tkc* ``` import re lambda s,y=re.sub,d='-':y('-+',d,y('[^0-9a-z-]','',y('[ .,/]',d,s.lower()))).strip(d) ``` [Answer] # Retina, 34 bytes ``` T`L`l [^a-z\d .,/-]+ \W+ - ^-|-$ ``` [Try it online!](http://retina.tryitonline.net/#code=VGBMYGwKW15hLXpcZCAuLC8tXSsKClxXKwotCl4tfC0kCg&input=MSsyKzMrNCsuLi4rbiA9IC0xLzEyPw) Note the trailing newline. Essentially the OP's implementation. [Answer] # [MATL](https://github.com/lmendo/MATL), 38 bytes ``` '-'jyvk45y' .,/'m(t8Y245hm)'-*'45YX6L) ``` [Try it online!](https://tio.run/nexus/matl#@6@uq55VWZZtYlqprqCno6@eq1FiEWlkYpqRq6muq6VuYhoZYeaj@f9/cElqeWaqerFCcWphaWpecqqVgraCloKugj6MBgA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#FVDJTsMwEL37K6YVUrbaxWmKEFJVdaH0ECHoAvSCMMo0MTh25bgR@friXmb0tnnSfF0CGvx07W827gJgg2FQh@7@kGbjqo4CGgfZ@PBxl0eX5e6SG1FIXTLGYGUstmjJc4hhE7ooikBA46yXSX@NSpkBvBuril6f7Dc5XVmJulAdOOkUNmTB9mzLNmxLeJImoyRL/NVEwwQoH/J0Sh7/TsY62FUINy@z3RrehJXiW@EAcqmRzjt63WRpQIPQBejPEVSiRXA@0ojaD3RgjlDIUrpmSl7P3g8zLUor6qYH4cKcmsA3WBRFRK5NT0Yd0cKsaFG7s0WgsKjEyXmOk7kxTvkPeFB63wPMrZD6GMcxueXpiAgQnKSUT/g/). ### Explanation ``` '-'jyv % Take input line. Append and prepend a dash. Gives a char column vector k % Convert to lowercase 45y' .,/'m( % Replace any of ' .,/' by a dash, using assignment indexing t8Y245hm) % Keep only alphanumeric chars or dashes, using reference indexing '-*'45YX % Replace each run of dashes by a single dash, using a regular expression 6L) % Remove first and last chars, which are always dashes. Implicitly display ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~61~~ ~~60~~ ~~61~~ ~~64~~ 53 bytes (52 bytes of code plus one byte for the `-p`) ``` $_=$_.tr("A-Z ,-/","a-z ").gsub(/[^\w ]/){}.split*?- ``` [Try it online!](https://tio.run/nexus/ruby#U1bULy0u0k/KzNNPzStTKCpNqlTQLfivEm@rEq9XUqSh5KgbpaCjq6@ko5SoW6WgpKmXXlyapKEfHRdTrhCrr1ldq1dckJNZomWv@/8/AA "Ruby – TIO Nexus") > > **`tr(`**…**`)`** – convert upper case characters, space, comma, period, and slash. Temporarily substitute the `-` with whitespace so I can use `strip` later on. > > Note the `-` character in the `"A-Z ,-/"` expression is actually a range operator, which also makes the `.` character subject to transformation. This maneuver won’t actually shave off bytes but it’s fancy so it gets to stay. > > > **`gsub(/[^\w ]/){}`** – remove all characters not in the allowed set. > > > **`split`** – technically, we don’t exactly need that array but `split` eliminates leading and trailing whitespace (which is actually `-` characters in disguise). As a bonus, this squeezes together runs of multiple spaces. > > > **`*?-`** – Shorthand for `.join("-")`; this reverses both the preceding `split` operation *and* the whitespace transformation at the same time. One more byte is saved by using the [abbreviated notation for character literals](https://ruby-doc.org/core-2.3.0/doc/syntax/literals_rdoc.html), which makes the program require Ruby 1.9 or newer. > > > **Update 1:** ~~Using `gets` instead of Ruby’s stream editing mode saves one byte.~~ Reverted as per [ValueInk’s suggestion](https://codegolf.stackexchange.com/questions/102812/url-friendly-titles#comment250085_102888). **Update 2:** **(+3 bytes overall)** * Fixed edge case `..--hi, $/` (→ `hi`) **(+10 bytes)** – once again courtesy of user ValueInk * Took malus for `-p` **(+1 byte)** * Got rid of `squeeze` and used `gsub` instead **(+2 bytes)**, which allowed me to: * Use `strip` to handle the leading and trailing dashes **(-10 bytes)**. **Update 3:** Hattrick by ValueInk. We save 11 bytes by leveraging `String#split`’s habit of auto-squeezing runs of the same separator, which enables us to ditch the whole final `strip`/`gsub` chain and replace it by a `split`/`join` combo. **(-11 bytes)** [Answer] ## JavaScript (ES6), ~~74~~ 69 bytes ``` f= s=>s.toLowerCase().replace(/[^-/,. a-z\d]/g,``).match(/\w+/g).join`-` ``` ``` <input oninput=o.textContent=/[a-z\d]/i.test(this.value)?f(this.value):``><pre id=o> ``` Edit: Saved 5 bytes by realising that I had already deleted all characters except `-/,. 0-9a-z` so I can use `\w` to match the remaining words. [Answer] # PHP, 87 bytes The idea of the regular expressions come from existing answers. ``` <?=trim(preg_replace(['@[^ a-z,-9]@','@[ ,-/]+@'],['','-'],strtolower($_GET[T])),'-'); ``` It requires you to have a server running PHP, and access over HTTP. The title must be on the key `T`, and the result will be printed on the screen. Example: `http://localhost/title.php?T=<my shiny title>` [Answer] # bash/Unix tools, 56 bytes ``` tr A-Z\ .,/ a-z-|tr -cds a-z0-9- -|sed s/^-//|sed s/-$// ``` Replace upper-case with lower-case letters, and the required special characters with dashes. Delete (-d option to tr) characters other than letters, digits, and dashes, and then squeeze (-s option to tr) multiple dashes in a row into a single dash. Delete dashes at the beginning, and then at the end. [Answer] ## Powershell, 85 Bytes ``` ($args[0].ToLower()-replace'[ .,/]','-'-replace'[^a-z,-9]'-replace'-+','-').Trim('-') ``` make it lowercase, then 3 regex replaces in a row, and trim any trailing `-`'s [Answer] # JavaScript, ~~90~~ ~~98~~ ~~94~~ ~~93~~ ~~91~~ ~~90~~ 91 bytes *1 byte saved thanks to @edc65!* *1 byte saved thanks to @IsmaelMiguel for spotting a leading semi-colon!* *1 byte gained after failing for* `,a-^-a,` ``` f=s=>s.toLowerCase().replace(/[^ a-z,-9]/g,"").replace(/[ ,-/]+/g,"-").replace(/^-|-$/g,"") ``` The thing I like most about this particular submission are the ranges. In the first `replace`, we remove anything that is not alphanumeric and not a `,`,`-`,`.`,`/` and not a space. We use `a-z` for detecting the letters, and we use `,-9` to detect those special characters *and* numbers since the character codes of these ASCII literals all line up! ``` , = 44 - = 45 . = 46 / = 47 0 = 48 ... 9 = 57 ``` ``` f=s=>s.toLowerCase().replace(/[^ a-z,-9]/g,"").replace(/[ ,-/]+/g,"-").replace(/^-|-$/g,"") console.log(f("---"));//TEST console.log(f("!@#$%ˆ&*()_+"));//TEST console.log(f("Stewie's sequence: + * - / + * - /-")); console.log(f("Loading... Forever")); console.log(f("N(e(s(t))) a string")); console.log(f("\"Hello, World!\"")); console.log(f("URL-Friendly titles")); console.log(f("C.U.S.R.S")); console.log(f("1+2+3+4+...+n = -1/12?")); console.log(f("How can I use cmp(a,b)")); console.log(f("Export The $PATH Variable, Line-By-Line")); console.log(f("Do n and n^3 have the same set of digits?")); console.log(f("Quine Anagrams! (Cops' Thread)")); console.log(f("The Golfer Adventure - Chapter 1")); console.log(f("Bootloader golf: Brainf***--")); console.log(f("0123")); console.log(f("a a1")); console.log(f("2-1=1")); ``` ``` <input oninput=a.textContent=f(this.value)><pre id=a> ``` [Answer] # Lua, 91 bytes ``` a=a:lower():gsub( '[ .,/]', '-' ):gsub( '[^%w-]', '' ):gsub( '%-+', '-' ):match'%-?(.*)%-?' ``` Where `a` is the URL string. Explanation: * Most of it's pretty straight forward. `a:lower()` returns the lower-case function * `:gsub` finds the match of the pattern and replaces it with the string. * `'[ .,/]'`: Brackets mean "or", so this matches space, period, comma, and slash. No need to be greedy because `:gsub` does all occurrences. * `'[^%w-]'`: `^` means "not" when inside brackets, `%w` means anything alphanumeric. So `'[^%w-]` matches anything that's *not* alphanumeric or a dash. * `'%-+'`: Match as many dashes as you can and replace them with just one dash. * `match'%-?(.*)%-?'`: In Lua, if a string is the function's only argument, no parenthesis are needed. Only needs to check for one dash at the start and end because dashes have been minimized already. No need for anchor characters because `.*` is match everything, greedy. [Answer] # C, 194 bytes ``` i,j;f(char*s,char*d){if(*s>47&*s<58|*s>96&*s<123)d[i++]=*s;if(*s>64&*s<91)d[i++]=*s+32;if(i-j&&*s>43&*s<48|*s==32&&*(s+1)&&*(s+1)>47|(*(s+1)<44&&*(s+1)^32)){d[i++]=45;j=i;}*++s?f(s,d):(d[i]=0);} ``` Call with: ``` int main() { char *in="Loading... Forever"; char out[128]; f(in,out); puts(out); } ``` [Answer] ## SAS, 108 One of the less competitive answers here due to the verbose syntax of SAS - the 9 character penalty per regex really hurts - but it was a good regex learning exercise: ``` t=prxchange('s/^-|-$//',-1,prxchange('s/-+/-/',-1,compress(translate(lowcase(t),'----',' .,/'),'-','adk'))); ``` [Answer] ## Pyth, 35 bytes ``` :r::rQ0"[-.,/]"d"[^\w ]"k6"[ -]+"\- ``` ### Explanation ``` rQ0 Convert letters to lower case : "[-.,/]"d Replace all -.,/ with spaces : "[^\w ]"k Remove all remaining symbols r 6 Remove leading and trailing spaces : "[ -]+"\- Turn runs of spaces and dashes to one dash ``` [Answer] ## Perl 6, 75 ``` {lc .subst(/<[\ .,/]>/,"-"):g.subst(/<[\W]-[\-]>/,""):g.subst(/\-+/,"-"):g} ``` [Answer] ## GNU Sed, 65 bytes ``` s/.*/\L\0/ s@[ .,/]@-@g s/[^-a-z0-9]//g s/-\+/-/g s/^-\|-$//g ``` A series of regex substitutions. Uses non-portable `\L` from GNU sed to lowercase the input. Run from a file using `sed -f`. ]
[Question] [ A sequel to [this question](https://codegolf.stackexchange.com/questions/94028/find-the-largest-number-thats-beside-a-zero). # Task Given an array of positive integers, find the **largest element k** for which: > > There exists *some* positive integer distance **n**, so that the element in the array located **n** places to the left *or* right from **k** equals **n**. > > > The array is guaranteed to contain at least one element satisfying this condition. The shortest code (in bytes) wins. You may choose whichever I/O format you like. # Example Given the input ``` [4, 6, 7, 9, 3, 6, 5, 7, 2] ``` The eligible values are: * The `4`, as there is a `7` located 7 positions to its right * The first `6`, as there is a `3` located 3 positions to its right * The `3`, as there is a `4` located 4 positions to its left * The `5`, as there is a `2` located 2 positions to its right * The second `7`, as there is a `3` located 3 positions to its left. Of these values, the largest is `7`. # Test cases ``` [1, 13] → 13 [2, 9, 8, 3, 72, 2] → 8 [5, 28, 14, 5, 6, 3, 4, 7] → 14 [1, 3, 5, 15, 4, 1, 2, 6, 7, 7] → 7 [5, 1, 3, 5, 2, 5, 5, 8, 5, 1, 5, 1, 2, 3] → 5 [5, 12, 2, 5, 4, 7, 3, 3, 6, 2, 10, 5, 5, 5, 4, 1, 8, 5] → 10 ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 21 bytes ``` vyN+Ny-})¹gL<Ãv¹yè})Z ``` **Explanation** ``` v } # for each num in input yN+ # push index + num Ny- # push index - num ) # wrap stack in a list ¹gL<à # remove indices outside the range of input v¹yè}) # get list of elements in input at the remaining indices Z # get max ``` [Try it online!](http://05ab1e.tryitonline.net/#code=dnlOK055LX0pwrlnTDzDg3bCuXnDqH0pWg&input=WzUsIDEyLCAyLCA1LCA0LCA3LCAzLCAzLCA2LCAyLCAxMCwgNSwgNSwgNSwgNCwgMSwgOCwgNV0) [Answer] ## Haskell, ~~61~~ ~~57~~ 55 bytes ``` f x=maximum[a|(n,a)<-x,(i,b)<-x,b==abs(n-i)] f.zip[0..] ``` Usage example: `(f.zip[0..]) [5,28,14,5,6,3,4,7]` -> `14`. (More or less) a direct implementation of the definition: for each index `n` of the input list `x` keep `a := x!!n` if there's an index `i` where `b := x!!i` equals `abs(n-i)`. Find the maximum. Edit: @xnor saved two bytes. Thanks! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ,N+JFfJị¹Ṁ ``` [Try it online!](http://jelly.tryitonline.net/#code=LE4rSkZmSuG7i8K54bmA&input=&args=WzQsIDYsIDcsIDksIDMsIDYsIDUsIDcsIDJd) or [verify all test cases](http://jelly.tryitonline.net/#code=LE4rSkZmSuG7i8K54bmACsOH4oKs&input=&args=WzEsIDEzXSwgWzIsIDksIDgsIDMsIDcyLCAyXSwgWzUsIDI4LCAxNCwgNSwgNiwgMywgNCwgN10sIFsxLCAzLCA1LCAxNSwgNCwgMSwgMiwgNiwgNywgN10sIFs1LCAxLCAzLCA1LCAyLCA1LCA1LCA4LCA1LCAxLCA1LCAxLCAyLCAzXSwgWzUsIDEyLCAyLCA1LCA0LCA3LCAzLCAzLCA2LCAyLCAxMCwgNSwgNSwgNSwgNCwgMSwgOCwgNV0). ### How it works ``` ,N+JFfJị¹Ṁ Main link. Argument: A (array) ,N Pair A with -A (element-wise negative). J Yield the indices of A [1, ..., len(A)]. + Add the elements of A (and their negatives) with the corr. indices. F Flatten the resulting 2D array. fJ Filter indices; remove invalid indices (not in [1, ..., len(A)]) from the generated array. The result is the list of all indices of eligible elements of A. ị¹ Retrieve the corresponding elements of A. Ṁ Take the maximum. ``` [Answer] # Python 3, ~~85~~ ~~80~~ 72 Bytes ``` lambda l,e=enumerate:max(i for p,i in e(l)for s,j in e(l)if j==abs(s-p)) ``` Edit: -8 Bytes thanks to @Dennis [Answer] # EXCEL: ~~32~~ 30 bytes `=MAX(IF(A:A-ROW(A:A)<0,A:A,0))` I still cannot believe I got it to be this short... **How to use:** paste this into ANY cell EXCEPT the cells of column A. After pasting, while still editing, press `control`+`shift`+`enter` to correctly enter it. put your values into column A, 1 value per cell (as per CSV entry). If you want to find out how this works, I've posted an additional tip in my [Tips for golfing in Excel](https://codegolf.stackexchange.com/a/94199/56309) question. [Answer] ## JavaScript (ES6), 61 bytes ``` a=>Math.max(...a.filter((_,i)=>a.some((e,j)=>e==i-j|e==j-i))) ``` [Answer] # Perl, 45 bytes Includes +2 for `-ap` Give numbers on a line on STDIN: ``` largest.pl <<< "5 12 2 5 4 7 3 3 6 2 10 5 5 5 4 1 8 5" ``` `largest.pl`: ``` #!/usr/bin/perl -ap ($_)=sort{$b-$a}map@F[$^P=$n-$_,$n+++$_],@F ``` One more byte can be gained by replacing `^P` by the literal control character, but that leads to a warning on STDERR on recent perls. Assumes `largest number + array length < 2^32` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Jạþ`=ḅa¹Ṁ ``` [Try it online!](http://jelly.tryitonline.net/#code=SuG6ocO-YD3huIVhwrnhuYA&input=&args=WzQsIDYsIDcsIDksIDMsIDYsIDUsIDcsIDJd) or [verify all test cases](http://jelly.tryitonline.net/#code=SuG6ocO-YD3huIVhwrnhuYAKw4figqw&input=&args=WzEsIDEzXSwgWzIsIDksIDgsIDMsIDcyLCAyXSwgWzUsIDI4LCAxNCwgNSwgNiwgMywgNCwgN10sIFsxLCAzLCA1LCAxNSwgNCwgMSwgMiwgNiwgNywgN10sIFs1LCAxLCAzLCA1LCAyLCA1LCA1LCA4LCA1LCAxLCA1LCAxLCAyLCAzXSwgWzUsIDEyLCAyLCA1LCA0LCA3LCAzLCAzLCA2LCAyLCAxMCwgNSwgNSwgNSwgNCwgMSwgOCwgNV0). ### How it works ``` Jạþ`=ḅa¹Ṁ Main link. Argument: A (array) J Indices; yield [1, ..., len(A)]. ` Use the previous return value as left and right argument: ạþ Absolute difference table; take the absolute value of the difference of each pair of indices, yielding a 2D array. = Compare each absolute difference with the corresponding item of A. ḅ Base; convert each Boolean list from base i to integer, where i is the corresponding item of A. The value of i is not important; we only care if the list contains a 1, which will result in a non-zero integer. ¹ Identity; yield A. a Logical AND; replace non-zero values with the corresponding items of A. Ṁ Take the maximum. ``` [Answer] # Pyth, ~~19~~ 17 bytes *Thanks to @Pietu1998 for -2 bytes* ``` eS@[[email protected]](/cdn-cgi/l/email-protection),-kb+b ``` A program that takes input of a list on STDIN and prints the result. [Try it online](https://pyth.herokuapp.com/?code=eS%40LQ%40UQs.e%2C-kb%2Bb&test_suite=1&test_suite_input=%5B1%2C+13%5D%0A%5B2%2C+9%2C+8%2C+3%2C+72%2C+2%5D%0A%5B5%2C+28%2C+14%2C+5%2C+6%2C+3%2C+4%2C+7%5D%0A%5B1%2C+3%2C+5%2C+15%2C+4%2C+1%2C+2%2C+6%2C+7%2C+7%5D%0A%5B5%2C+1%2C+3%2C+5%2C+2%2C+5%2C+5%2C+8%2C+5%2C+1%2C+5%2C+1%2C+2%2C+3%5D%0A%5B5%2C+12%2C+2%2C+5%2C+4%2C+7%2C+3%2C+3%2C+6%2C+2%2C+10%2C+5%2C+5%2C+5%2C+4%2C+1%2C+8%2C+5%5D&debug=0) **How it works** ``` eS@[[email protected]](/cdn-cgi/l/email-protection),-kb+b Program. Input: Q .e Map over Q (implicit input fill) with elements as b and indices as k: -kb k-b +b k+b (Implicit fill with k) , 2-element list of those (possible indices) s Flatten that UQ Yield [0, 1, 2, 3..., len(Q)-1] @ Filter the flattened list by presence in the above, removing invalid indices @LQ Index into Q at those indices S Sort that e Yield the last element of that, giving the maximum Implicitly print ``` [Answer] # MATL, 13 Bytes ``` ttn:tYTq=a)X> ``` Input must be a column vector. I.e., input is semicolon-separated like [1;2;3], or comma separated with a transpose tick at the end like [1,2,3]'. [Try it online!](http://matl.tryitonline.net/#code=dHRuOnRZVHE9YSlYPg&input=WzQsIDYsIDcsIDksIDMsIDYsIDUsIDcsIDJdJw) All test cases: [(A)](http://matl.tryitonline.net/#code=dHRuOnRZVHE9YSlYPg&input=WzEsIDEzXSc), [(B)](http://matl.tryitonline.net/#code=dHRuOnRZVHE9YSlYPg&input=WzIsIDksIDgsIDMsIDcyLCAyXSc), [(C)](http://matl.tryitonline.net/#code=dHRuOnRZVHE9YSlYPg&input=WzUsIDI4LCAxNCwgNSwgNiwgMywgNCwgN10n), [(D)](http://matl.tryitonline.net/#code=dHRuOnRZVHE9YSlYPg&input=WzEsIDMsIDUsIDE1LCA0LCAxLCAyLCA2LCA3LCA3XSc), [(E)](http://matl.tryitonline.net/#code=dHRuOnRZVHE9YSlYPg&input=WzUsIDEsIDMsIDUsIDIsIDUsIDUsIDgsIDUsIDEsIDUsIDEsIDIsIDNdJw), [(F)](http://matl.tryitonline.net/#code=dHRuOnRZVHE9YSlYPg&input=WzUsIDEyLCAyLCA1LCA0LCA3LCAzLCAzLCA2LCAyLCAxMCwgNSwgNSwgNSwgNCwgMSwgOCwgNV0n) *Thanks to Suever for suggestions in the [MATL chatroom](http://chat.stackexchange.com/rooms/39466/matl-chatl) to save 2 characters.* **Explanation:** The overall strategy is the same as my Octave/MATLAB answer, where the basic concept is explained: <https://codegolf.stackexchange.com/a/94161/42247> The specific code in this MATL answer is built up as follows: The core of the method is the construction of the Toeplitz matrix whose ij'th entry is abs(i-j). We first construct the Toeplitz matrix with entries abs(i-1)+1 with MATL's toeplitz command YT as follows: ``` n:tYT % Equivalent to @(v)toeplitz(1:length(v)) ``` To see how this works, let us call the input vector to this code snippet 'v'. The 'n' finds the length of v, then ':' constructs the vector 1:length(v). Next the 't' makes another copy of 1:length(v) on the stack; this extra copy is needed due to a well-known bug in the YT function in MATL (the MATL equivalent of toeplitz()), wherein it expects two copies of the input instead of 1. Then YT takes the two copies of this vector 1:length(v) off the stack, and makes the abs(i-j)+1 Toeplitz matrix from them. Now we need to subtract 1 from this matrix to get the Toeplitz matrix with entries abs(i-j), and find the ij locations where this abs(i-j) Toeplitz matrix is equal to the matrix of all column vectors containing column-copies of the input vector v. This is done as follows: ``` t n:tYT q= % t [code] q= is equivalent to @(v) [code](v)-1 == v ``` The first 't' makes an extra copy of the input and stores it on the stack. The 'n:tYT' makes the toeplitz matrix as described earlier and outputs it into the stack. Then 'q' subtracts 1 from the Toeplitz matrix, and '=' does the elementwise equality comparison between the abs(i-j) matrix and the vector whose columns are copies of the input. Note that by comparing a column vector to a matrix, we are implicitly taking advantage of MATLAB/MATL's operator broadcasting rules (the column vector in the comparison gets copied to make a matrix without issuing any commands). Finally, we need to find the row indices i where there is a column j such that the ij'th entry in the matrix difference constructed above equals 1, then get the value of the input vector corresponding to these indices, then take the maximum. This in the following three steps: 1) Find the indices for any row that contains a nonzero: ``` tn:tYTq= a % [code] a is equivalent to @(v) any([code](v)) ``` 2) Extract the elements of the input vector corresponding to those indices: ``` t tn:tYTq= a ) X> % t [code] ) is equivalent to @(v) v([code](v)] ``` 3) Find and return the maximum element: ``` t tn:tYTq= a ) X> % [code] X> is equivalent to @(v) max(v). ``` [Answer] ## Ruby, 66 bytes ``` ->a{i=-1;a.map{|e|i+=1;[a[j=i+e]||0,a[0>(k=i-e)?j:k]||0].max}.max} ``` [Answer] # Octave / MATLAB, 40 Bytes ``` @(v)max(v(any(toeplitz(1:nnz(v))-v==1))) ``` Input must be a column vector. *Thanks to Luis Mendo for suggestions saving 3 bytes (see comment)* *Thanks to Suever for suggestions saving 4 more bytes (replacing ~~(sum()) with any())* **Explanation:** Given an input vector v, this problem is equivalent to finding all solutions i,j of the following discrete equation, ``` abs(i-j) = v(i), i,j both in 1..k, ``` where abs() is the absolute value function. Each v(i) for which this equation is solved is one of the candidate solutions which we can maximize over. As a discrete function of i and j, all possibilities for the left hand side can be arranged in the toeplitz matrix that looks something like this: ``` [0, 1, 2, 3, 4] [1, 0, 1, 2, 3] [2, 1, 0, 1, 2] <--- abs(i-j) [3, 2, 1, 0, 1] [4, 3, 2, 1, 0] ``` And since the right hand side doesn't depend on i, all possibilities for it can be arranged into a matrix where the columns are all copies of the input, ``` [v(1), v(1), v(1), v(1), v(1)] [v(2), v(2), v(2), v(2), v(2)] [v(3), v(3), v(3), v(3), v(3)] <--- v(i) [v(4), v(4), v(4), v(4), v(4)] [v(5), v(5), v(5), v(5), v(5)] ``` To find all solutions to the equation, we subtract these two matrices and find the locations where there is a zero. The rows where there is a zero correspond to the desired indices i's where there is a j such that abs(i-j) = v(i). Other tricks: * It takes less characters to construct the absolute value function plus one, abs(i-j)+1, then check for locations where the difference is 1, rather than construct the true (unshifted) absolute value function. * Uses automatic operator broadcasting to implicitly make column copies of v * Gets the length of the input via nnz() instead of length(), which works since the inputs are said to be positive in the problem statement. [Answer] # Python, 58 bytes Based on [Tony S.'s Ruby answer](https://codegolf.stackexchange.com/a/94356/47581). This answer works in Python 2 and 3. Golfing suggestions welcome. ``` lambda n:max([n[i+v]for i,v in enumerate(n)if i+v<len(n)]) ``` **Ungolfing** ``` def f(array): result = [] for index, value in enumerate(array): if index + value < len(array): result.append(array[index + value]) return max(result) ``` [Answer] # Mathematica, 69 bytes ``` Max@MapIndexed[{If[#2[[1]]>#,a[[#2-#]],{}],a[[#2+#]]~Check~{}}&,a=#]& ``` Anonymous function. Takes a list of integers as input and returns an integer as output. Ignore any messages generated. [Answer] # Scala, 94 bytes ``` a=>a.zipWithIndex.filter(p=>a.zipWithIndex.exists(x=>x._1==Math.abs(p._2-x._2))).unzip._1.max ``` [Answer] # PHP, 128 Bytes ``` <?foreach(($i=$_GET[i])as$k=>$v){$k-$v<0?:!($i[$k-$v]>$m)?:$m=$i[$k-$v];if($k+$v<count($i))if($i[$k+$v]>$m)$m=$i[$k+$v];}echo$m; ``` [Answer] # Java 7, ~~125~~ 123 bytes ``` int c(int[]a){int r=0,i=0,l=a.length,x;for(;i<l;r=l>(x=i+a[i])?a[x]>r?a[x]:r:r,r=(x=i-a[i++])>0?a[x]>r?a[x]:r:r);return r;} ``` 2 bytes saved thanks to *@mrco*. **Ungolfed (sort of) & test code:** [Try it here.](https://ideone.com/lMalsl) ``` class M{ static int c(int[] a){ int r = 0, i = 0, l = a.length, x; for(; i < l; r = l > (x = i + a[i]) ? a[x] > r ? a[x] : r : r, r = (x = i - a[i++]) > 0 ? a[x] > r ? a[x] : r : r); return r; } public static void main(String[] a){ System.out.println(c(new int[]{ 1, 13 })); System.out.println(c(new int[]{ 2, 9, 8, 3, 72, 2 })); System.out.println(c(new int[]{ 5, 28, 14, 5, 6, 3, 4, 7 })); System.out.println(c(new int[]{ 1, 3, 5, 15, 4, 1, 2, 6, 7, 7 })); System.out.println(c(new int[]{ 5, 1, 3, 5, 2, 5, 5, 8, 5, 1, 5, 1, 2, 3 })); System.out.println(c(new int[]{ 5, 12, 2, 5, 4, 7, 3, 3, 6, 2, 10, 5, 5, 5, 4, 1, 8, 5 })); } } ``` **Output:** ``` 13 8 14 7 5 10 ``` [Answer] # Java, 118 bytes ``` int f(int[]a){int t=0,i,j,z=0,l=a.length;while(t<l*l){i=t/l;j=t++%l;z=a[i]>z&&((i<j?j-i:i-j)==a[j])?a[i]:z;}return z;} ``` [Answer] # Ruby 56 bytes My smallest ruby solution. ``` ->n{x=[];i=0;n.map{|v|x<<n[v+i]&&v+i<n.size;i+=1};x.max} ``` Pretty easy to test in rails console ``` a = ->n{x=[];i=0;n.map{|v|x<<n[v+i]&&v+i<n.size;i+=1};x.max} a[[1, 13] => 13 a[[2, 9, 8, 3, 72, 2]] => 8 a[[5, 12, 2, 5, 4, 7, 3, 3, 6, 2, 10, 5, 5, 5, 4, 1, 8, 5]] => 10 ``` This started at 63 bytes, thanks for the suggestions to help trim it down! [Answer] # [Actually](https://github.com/Mego/Seriously), 17 bytes This answer is an Actually port of [my Python answer](https://codegolf.stackexchange.com/a/94397/47581). Golfing suggestions welcome. [Try it online!](https://tio.run/##S0wuKU3Myan8/9/60dTphzc@mtl0bvGjngWPps7JsXvUs/DRtIkQniuQ4@v7/3@0qY6CoZGOAhABWSY6CuY6CsZgZAYWNDQAS5jCpA11FCyA7FgA "Actually – Try It Online") ``` ;╗ñ♂Σ⌠╜l>⌡░⌠╜E⌡MM ``` **Ungolfing** ``` Implicit input L. ;╗ Duplicate L and save a copy of L to register 0. ñ enumerate() the other copy of L. ♂Σ sum() all the pairs of [index, value of n]. Call this list Z. ⌠...⌡░ Push values of Z where the following function returns a truthy value. Variable v_i. ╜ Push L from register 0. l Push len(L). > Check if len(L) > v_i. ⌠...⌡M Map the following function over Z_filtered. Variable i. ╜ Push L from register 0. E Take the ith index of L. M max() the result of the map. Implicit return. ``` [Answer] # JavaScript (ES6), ~~56 54~~ 53 bytes ``` l=>l.map((n,i)=>m=Math.min(m,~l[i+n],~l[i-n]),m=0)|~m ``` [Try it online!](https://tio.run/##bU9LDoIwEN17ii7bOAItFDCm3sATEBYEf5i2EDWujEsP4BG9CNYxEEGTZjpv8j4zh@JSnMpj1Zxntl5v2q1qtVpqzxQNpRYqppZGrYrz3jOVpQZuOqumNsd/ZnMGRgXsejNtWdtTrTeernd0SzMOhIc5Ywvi@@R5fzg0GVEEkDmQFEgIJHFAfNPTMVs6guPyCIhrY1S5PhlkRJPfNUIUcIl0hwWqk5E0@ZPXiwVWict@5rKzGtwo/5mITh9haogvxiEPOuN@u3fC4KSgfQE "JavaScript (Node.js) – Try It Online") [Answer] # T-SQL(sqlserver 2016), 132 bytes **Golfed:** ``` ;WITH C as(SELECT value*1v,row_number()over(order by 1/0)n FROM STRING_SPLIT(@,','))SELECT max(c.v)FROM C,C D WHERE abs(D.n-C.n)=D.v ``` **Ungolfed:** ``` DECLARE @ varchar(max)='2, 9, 8, 3, 72, 2' ;WITH C as ( SELECT value*1v, row_number()over(order by 1/0)n FROM STRING_SPLIT(@,',') ) SELECT max(c.v) FROM C,C D WHERE abs(D.n-C.n)=D.v ``` **[Fiddle](https://data.stackexchange.com/stackoverflow/query/542948/find-the-largest-number--positions-away-from-an-)** [Answer] **Clojure, 68 bytes** ``` #(apply max(map(fn[i](get % i 0))(flatten(map-indexed(juxt - +)%)))) ``` For example `(map-indexed (juxt - +) [3 4 1 2])` is `([-3 3] [-3 5] [1 3] [1 5])` (index `+/-` its value), these are used to look-up values from the original vector (out-of-range defaulting to `0`) and the max value is found. Still feels a bit verbose but at least I got to use `juxt` :) ]
[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/32081/edit). Closed 3 years ago. [Improve this question](/posts/32081/edit) Calculate `n` modulo `12` for an unsigned 32 bit integer. ## The Rules: * Must work for all `n` between 0 and 23. Other numbers optional. * Must only use any of the operators `+-*`, `~&^|` or `<<`, `>>` as commonly defined on 32 bit uints. * May use arbitrary number of constant uints. * May not use any form of pointers, including arrays, or any `if` statements, including things that compile to if statements such as ternary operators or "greater than" operators. ## The scoring: * Operators `+ -` and the bitwise operators `~ & ^ | << >>` (NOT, AND, XOR, OR, bit shifts) give a score of `1`, `*` gives a score of `2`. * Lowest total score wins. [Answer] # 4 (Language is irrelevant) ``` n-((48&(11-n))>>2) ``` Woo! Got to 4. `11-n` will ensure all of the high order bits are set if and only if n>= 12. `48&(11-n)` == if n>11 then 48 else 0 `(48&(11-n))>>2` == if n>11 then 12 else 0 `n-((48&(11-n))>>2)` is the answer [Answer] # 4 A solution with a lookup table (it looks up `i ^ (i % 12)`): ``` i ^ (0x1d4c000 >> (i & 0xfc) & 30) ``` # 4 Here's another solution with 4 operations: ``` i - ((0xffff >> (i - 12)) & 12) ``` It assumes that the count operand of bitshifts is implicitly taken mod 32, i.e. `x >> -1` is the same as `x >> 31`. # 5 Another approach, using a lookup table: ``` i - (16773120 >> i & 1) * 12 ``` [Answer] # bash – 1 ``` echo `seq 0 11` `seq 0 11` | awk '{print $(number+1)}' ``` e.g. ``` $ echo `seq 0 11` `seq 0 11` | awk '{print $(0+1)}' 0 $ echo `seq 0 11` `seq 0 11` | awk '{print $(11+1)}' 11 $ echo `seq 0 11` `seq 0 11` | awk '{print $(12+1)}' 0 $ echo `seq 0 11` `seq 0 11` | awk '{print $(23+1)}' 11 ``` [Answer] ## C, little-endian - 2 This is probably cheating but I think it satisfies the rules... ``` union { int i; struct { int a:4; int b:2; int c:10; } s; struct { int a:2; int b:14; } t; } u; u.i = 11-n; u.s.a = 0; u.s.c = 0; result = n-u.t.b; ``` [Answer] # PHP - score 0 I wonder how is it possible that noone came with this before me!!! ``` $n = 18; $s = str_repeat("a", $n); $s2 = preg_replace('/aaaaaaaaaaaa/', '', $s); echo strlen($s2); ``` [Answer] # C, score 5 Works up to 23, not guaranteed above that. ``` ( ((n+4)>>2)&4 ) + n & 15 ``` `((n+4)>>2)&4` returns 4 for n>=12. Add it to n and you get the right answer in the least significant 4 bits, then truncate the other bits. [Answer] ### whatever language: 5 not going to win, but participating because fun and maybe because it's easier to understand then others: ``` n - ((n+20)>>5)*12 ``` this is equivalent to ``` n - (n>11)*12 ``` this is equivalent because when you add 20 to 12, you get 32, thus the 5th bit becomes 1. This is only when n > 1 as 32 is the smallest number where the 5th bit becomes 1. also note that is easily expandable for a higher range, as you can do ``` n - ((n+20)>>5)*12 - ((n+41)>>5)*12 ``` to reach a range until 35 [Answer] # Python 2.x - 4 ``` j=input();m=lambda a,b:a*b;a=(m(j,357913942)>>32);print j-m(12,a) ``` Is `=` an operator? In that case the score is 6. ``` j-12*(j*357913942>>32) ``` BTW @steveverrill 's solution can be directly used in Python as well. Works for the range 0 .. 23 So whats going on ? Multiply by 357913942 and divide by 2^32 (or right shift 32) [Answer] # C - 6 ``` (n - (((n * 0xAAAB) >> 19)) * 12 ) ``` [Answer] # Cobra - 2 (or 3) ``` def modulo12(n as uint32) as uint32 for i in 11:n to int64:12,n-=12 return n ``` This *might* be bending the rules a bit, but I've asked and was allowed to use this. It also works for any number. [Answer] # [Kona](https://github.com/kevinlawler/kona/) - 5 Might be invalid because I'm not sure if the floor operator is allowed, but I've got two `*` and a minus: ``` mod:{x-(_0.08333*x)*12} ``` Which should work for any integer. ]
[Question] [ [This was fun!](https://codegolf.stackexchange.com/questions/25670/output-pi-without-math) However with only three digits, the fun was over way too soon. This challenge is similar, but we'll keep the fun going. ## The Challenge > > Print as many digits of the [Golden Ratio](https://en.wikipedia.org/wiki/Golden_ratio) φ as possible. The Golden Ratio is defined as the number that satisfies φ = (φ + 1)/φ and the first 100 digits are given by: > > > 1.6180339887498948482045868343656381177203091798057628621354486227052604628189024497072072041893911375... > > > *This challenge is **not** about computing φ!* It's about printing as many digits as possible without using any method for doing that twice. So find as many creative ways to get your digits as you can! > > > ## Restrictions By itself, printing the digits of φ would be a bit too simple, so here are the rules: 1. **You have to construct the number *in order* from left to right**, either by printing it piece by piece or by constructing a string from left to right and printing it at the end - you could even generate an array of digit characters and then join it and print it, as long as you do it in order. In the following rules "print" and "output" may refer to any of those processes (e.g. if you're building a string, and the string contains `1.6` that counts as having `1.6` already printed). 2. For your code **you get a budget of *15 characters per digit***. The period does not count towards that budget, but has to be printed as well. Note that the restriction is only on total code size: you may use more than 15 characters for any digit as long as you don't use more on average. In fact, you may build up a "debt" in characters and "pay it off" later. E.g. to print `1.618` you have **60** characters. 3. **Standard-library includes/imports do not count towards the code size.** But you can't give those includes shorthand aliases for free! 4. **You must not use the digit you are currently generating, nor any you have already printed.** E.g. `1` may appear nowhere in your source code, because it's the very first digit. The code that outputs the `8` in `1.618` may use any or all of the digits `[0234579]`, but none of `[168]`. For this purpose, **all literals that are equivalent to a *single* digit are treated *as that digit***. So if your language can represent `9` as `'\t'` you are not allowed to use that anywhere, where you couldn't use an `9` instead. 5. **You must not produce multiple digits at once.** It should be possible to clearly split your code into chunks that generate one digit a time. 6. **You must not refer to any *built-in* function, mathematical/boolean/bit-wise/string operator, variable or constant which you have used in code that generated an earlier digit.** Exceptions are integer-to-string conversion, string concatenation and printing functions which you might need for every single digits. Note that it doesn't matter by which *name* you refer to any built-in: just because you alias a built-in `PI` to both `p` and `q` doesn't mean you get to use `p` once and `q` once. Likewise, you *are* allowed to use a name twice if it refers to two different built-ins, like string `length` and array `length`. If your programming language doesn't have functions use your best judgement on what the equivalent would be - e.g. for bash scripting, invoking other programs should follow the rules imposed on functions 7. **Your submission must be written in a single language.** So no executing another language's interpreter to get access to that language's built-ins as well. ## Implications The following points are all implied by the above rules, but I add them here to avoid questions that have already come up in the sandbox: * You're not allowed to overwrite parts of your output by printing some backspaces (usually `'\b'`) in between. * Loops which generate/output multiple digits are forbidden. (Loops that compute a single digit are fine, though.) * Using an obfuscated version `(1 + √5)/2` or dividing Fibonacci numbers to obtain more than a single digit is forbidden. * You cannot precalculate the 10 digits and store them in 10 variables and then just refer to those, because those variable references don't *generate* the digit - the code that fills the variable does, so this is a violation of rule 6. * In fact, you can't reuse any previous (or intermediate results), because that would mean two digits would share code for being *generated*. * Otherwise, you can use any means whatsoever (which do not have to purely mathematical) to generate the digits. (And you should!) * In fact there is no need to calculate anything, if you can pull out the correct digits from many different places using your standard library. * You *may* use an operator multiple times while generating a single digit, so `2+2+2` is fair game to generate the first `6` (although it's unlikely the shortest). * You *may* use any literal as often as you want, because they are not built-in constants. So as long as you don't have to print `5`, you can as many `5`s in your code as you want. * You can't hardcode the output, because that would involve using the digits you are outputting. In short: don't use any method of generating digits twice and don't use the digit you are currently outputting or any have already printed. If you do spot a loophole which allows you to get a (quasi-)infinite score, please don't ruin the challenge by exploiting it, but let me know so I can see if the loophole can be fixed without breaking anything. ## Scoring The program that prints the highest number of digits correctly wins. In case of a tie the shorter code breaks the tie. Please add an ungolfed commented version that identifies which part of your code generates which digit. PS: If anyone beats the 100 digits above, [here are some more](http://www.goldennumber.net/phi-million-places/). [Answer] # PHP, 100 digits I'm probably bending the rules a bit here, but PHP has dozens of constants to choose from: ``` <?php echo TRUE . '.' . PM_STR . DNS_A . MSG_EOR . LC_ALL . T_FMT . LOCK_UN . SQL_DATE . E_NOTICE . IMG_WBMP . INI_ALL . E_PARSE . SOCKET_EBADF . LOG_USER . IMAGETYPE_JPC . IMG_PNG . GLOB_MARK . LOCK_NB . LOG_NDELAY . D_FMT . PHP_ZTS . GLOB_ERR . AM_STR . SQL_DOUBLE . SOL_TCP . FILE_APPEND . LOG_ERR . SORT_ASC . SOCK_RAW . LOG_INFO . LC_TIME . SQL_FLOAT . SORT_DESC . INFO_MODULES . E_ERROR . IMG_GIF . SQL_REAL . LOG_DEBUG . DNS_NS . CODESET . CAL_FRENCH . CURLE_OK . LDAP_OPT_RESTART . LOCK_SH . XML_PI_NODE . SQLITE_INTERRUPT . MYSQLI_ASYNC . CURLM_OK . SNMP_NULL . SQLITE_NOMEM . LC_MESSAGES . IMG_JPG . SO_KEEPALIVE . SOCKET_ENXIO . LOCK_EX . D_T_FMT . ENT_QUOTES . LOG_NOTICE . SOCK_RDM . INPUT_ENV . CURLAUTH_NTLM . INPUT_SESSION . AF_INET . IMG_JPEG . SQL_CONCURRENCY . SEEK_SET . SOCKET_EIO . LC_CTYPE . PHP_URL_QUERY . LOG_KERN . INI_SYSTEM . IMAGETYPE_BMP . SEEK_END . JSON_HEX_QUOT . LOG_PID . LIBXML_DTDATTR . XML_DOCUMENT_NODE . PHP_DEBUG . LOG_CRIT . ENT_IGNORE . LC_NUMERIC . DOM_NOT_SUPPORTED_ERR . PHP_URL_FRAGMENT . FILE_TEXT . IMAGETYPE_TIFF_II . LOG_CONS . LOG_EMERG . UPLOAD_ERR_CANT_WRITE . MSG_PEEK . SQLITE_OK . FNM_PERIOD . AF_UNIX . CURLPROTO_FTPS . STREAM_NOTIFY_FAILURE . MYSQL_BOTH . CURLE_FTP_ACCESS_DENIED . MSG_OOB . FTP_TEXT . LC_MONETARY . CURLE_COULDNT_CONNECT . SQLITE_BUSY . "\n"; ``` This probably isn't very portable code, but it works fine on my system. Here's the code that generated it: ``` <?php $phi = "6180339887498948482045868343656381177203091798057628621354486227052604628189024497072072041893911375"; echo "<?php\necho TRUE . '.' . "; $consts = get_defined_constants(); foreach($consts as $k=>$v) if (preg_match('/\d|TRUE|PHP_EOL/',$k)) unset($consts[$k]); for ($p=0;$p<strlen($phi);$p++) { $d = ord($phi[$p]) - 48; $min = 999; foreach($consts as $k=>$v) { if (strlen("$v")==1 && $v==$d && strlen($k)<$min) { $min = strlen($k); $maxk = $k; } } if ($min==999) break; echo "$maxk . "; unset($consts[$maxk]); } echo "\"\\n\";\n"; ``` [Answer] ## Perl - 37 digits ``` use Math::Trig; use POSIX; print !0,'.',chop$=||$=,A==A,2**3,$|,++$^F,75/5/5,pi*pi%\_,4+4,a^Y,w&'?',~"\xcb",$^=~y/_//c, ord"\b",unpack(h,"\t").@{[c,c,c,c]},$#{[b..j]},"$^W"|'$',$^H>>log$^H,cos()- -cos,$[, $-=sqrt%SIG,$%=$],$+[*$=~/($)/],split('',$~).map(glob,"{,,,}{,}"),index(\L,L), exp(exp)<<exp,ceil(sinh acosh$^C).keys{stat$0},rindex(\R,R),($s=ssssss)=~s/s//g, $?=acos(--$z),$^T=pack(u,$^T.$^T.TTTT),B~~B,C<=C,length$^V, ``` 392 bytes currently, (10.6 per digit). Output: ``` 1.618033988749894848204586834365638117 ``` --- **Self-imposed Restrictions** I've added a few additional restrictions to limit the use of language features that would trivialize the problem. For example, array dereference `@{...}` and array final index `$#{...}` are only used once. Each array used is generated in a different manner (compare `[c,c,c,c]`, `[b..j]`, `split('',$~)`, `map(glob,"{,,,}{,}")`). Additionally, no symbol or bareword is used more than once, although this is explicitly allowed in the challenge description. I think it's a good idea for perl (or any language with int-only special variables (are there any others?)), because it limits the number of implicit int conversions. --- **Pieces** ``` !0 # returns 1 '.' chop$=||$= # $= is 60, chop the 0, returns 6 A==A # returns 1 (because 0==0) 2**3 # returns 8 $| # auto flush, returns 0 ++$^F # max system filehandle pre-incremented, returns 3 75/5/5 # returns 3 pi*pi%\_ # pi² mod a large value, returns 9 4+4 # returns 8 a^Y # bitwise 'a' xor 'Y', returns 8 w&'?' # bitwise 'w' and '?', returns 7 ~"\xcb" # bitwise inversion of char 203, returns 4 $^=~y/_//c # count non-underscores in $^, returns 9 ord"\b" # returns 8 unpack(h,"\t") # unpack "\t" as a hex nibble, returns 9 @{[c,c,c,c]} # anonymous array, returns 4 in scalar context $#{[b..j]} # final index of the range b..j, returns 8 "$^W"|'$' # bitwise '0' or '$', returns 4 $^H>>log$^H # $^H is 256, log$^H is ~5, returns 8 cos()- -cos # cos(undef) is 1, subtract -1, returns 2 $[ # array start index, returns 0 $-=sqrt%SIG # set $- to sqrt(23), returns 4 $%=$] # set $% to the version number, returns 5 $+[*$=~/($)/] # match end on *$ (aka *main::$), returns 8 split('',$~) # split "STDOUT" into chars, returns 6 in scalar context map(glob,"{,,,}{,}") # an array of 8 empty strings, returns 8 in scalar context index(\L,L) # finds 'L' in 'SCALAR(...)', returns 3 exp(exp)<<exp # 2.718281828 << 1, returns 4 ceil(sinh acosh$^C) # ceil(2.30129...), returns 3 keys{stat$0} # stat$0 is an array with 13 entries, which has 6 keys when # interpreted as a hash, returns 6 in scalar context rindex(\R,R) # finds 'R' in 'SCALAR(...)' in reverse, returns 5 ($s=ssssss)=~s/s//g # replace the every 's' in 'ssssss' with nothing, returns 6 $?=acos(--$z) # set $? to 3.14159... implicit int conversion, returns 3 $^T=pack(u,$^T.$^T.TTTT) # set $^T to "8,30P,...", returns 8 B~~B # returns 1 (because B represents the same thing as B) C<=C # returns 1 (because 0<=0) length$^V # string length of $^V, returns 7 ``` [Answer] ### Python 2.7, 19 digits, 231 relevant chars ``` from math import ceil, pi, trunc, gamma, sin print ''.join(map(str, [33-32, chr(46), ~-7, 8>>3, trunc(gamma(4.3)), 'x'.find('x'), 22/7, range(4).pop(), len('am I phi?'), 52%44, 2*4, 5|2, ord('/'), '\b', 5+2+2, 2<<2, eval("5+2+2"), ceil(pi), '\b', '\b', str(sin(5))[5], 5&52])) ``` [Answer] # Ruby 2.1 for 54 digits, 808 characters ``` #!ruby -rdate -rdigest -ropenssl -rprime -rset -rsocket print 2/2,?.,9-3,3&5,2*4,2^2,7%4,55>>4,5+4,2<<2,-~7,5|2,2**2,(2r+2+5).to_i,(2.2+5).ceil,(55r/5-2).floor,(2.2*2).to_i,(2r*2*2).ceil,(2.2**2).floor,2.to_bn<<2,__LINE__,$<.to_i,IO::LOCK_NB,Errno::EIO::Errno,File::APPEND,'aaaaaa'.size,?a.encoding.name.sub(/\D+/,''),%w[a a a].size,%w[a b c d].to_set.size,%w[a a a].count,Socket::AF_NS,Date.jd(Date::ITALY).wday,*Digest::MD5.digest(?j).scan(/\d/),Set[?a,?b,?c].count,SignalException.new('FPE').signo,Float::ROUNDS,begin exit false rescue Object $!.status end,Process::RLIMIT_NPROC,:aaaaaaa.size,Prime.first,?/.next,{a:p,b:p,c:p}.size,STDIN.lineno,?a.crypt('at')[/\d/],{a: :a}.find_index([:a,:a]),/b/=~'aaaaaaaaab',[?a,?b].index(?b),:aaaaaaab=~/b/,?\t.ord,'aaaaaaaab'=~/b/,open(?/).pos,'aaaaab'.index(?b),?\a.bytes{|b|break b},'aaaaaaa'.rindex(?a),%w[a a].map.size ``` This program works with `ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-openbsd]`. Systems other than OpenBSD 5.5 might have different values for a few digits. ## Interpretations The restrictions of this challenge, especially restriction 6, are not precise for Ruby. So I add my own interpretations: 1. **The parentheses, dot and double-colon are not operators.** The parentheses just change the order of operations. The dot calls methods, as in `$<.fileno`, and the double colon gets constants, as in `IO::LOCK_NB`. The name of the method or constant is part of the operation. Because `()` `.` `::` are not operators, I do not apply restriction 6 to them. I may reuse them to generate more digits. 2. **A method with a different implementation is a different method.** For example, `Array#count` and `Enumerable#count` are not the same function for restriction 6. Both methods act the same, but `Array#count` overrides `Enumerable#count` with a different implementation. If I use `Array#count` to generate one digit, I may use `Enumerable#count` to generate another digit. 3. **Class#new is one method.** In Ruby, `Mutex.new`, `Random.new`, `Time.new` and so on refer to the same method, `Class#new`. I use `SignalException.new` to generate one digit. Because of restriction 6, I may never again use `Class#new`. 4. **Constants for classes or modules are still constants.** In Ruby, class names like `Float` and `IO` are constants! I use `IO::LOCK_NB` to generate one digit. Because of restriction 6, I may never again use `IO`. This interpretation binds only Ruby, and not other languages where package names are not constants. 5. **Literals are not constants.** Though 2 is a mathematical constant (independent of any variables), it is not a constant in Ruby. I do not apply restriction 6 to literals, and I may reuse the literal 2 for more than one digit. 6. **Literals are not operators.** I do not apply restriction 6 to the brackets or quotes that form literal arrays, hashes, regular expressions, or strings, as in `[]` `{}` `//` `''`. I may always use such literals to generate more digits. 7. **Two constants with the same value are the same constant.** `File::APPEND` and `IPSocket::LOCK_UN` are two names for the same number 8. Restriction 6 says, "it doesn't matter by which *name* you refer to any built-in." Because `File::APPEND` and `IPSocket::LOCK_UN` differ only by name, they must be the same constant, so I may not use them for two digits. 8. **Two digits may not refer to the same global variable.** This closes a loophole. Restriction 6 only applies to functions, operators and constants. Restriction 4 only applies to literals. `$SAFE` is a built-in global variable, not a function, operator, constant, nor literal. `$SAFE` has the value 0. With the loophole, I can reuse `$SAFE` to generate every digit 0 in the program. I close the loophole by interpreting restriction 6 to also restrict global variables. ## Comments The first line is `#!ruby -rdate -rdigest -ropenssl -rprime -rset -rsocket`. Ruby parses this line and loads six parts of its standard library, as if by `require 'date'`, `require 'digest'` and so on. I do not count these 56 characters, because restriction 3 exempts "standard library imports/includes". The rest of the program calls `print` with a long list of arguments, to convert them to strings and print them in order. The arguments are these: 1. `1` from `2/2`: division *Fixnum#/* `.` from `?.`: literal single-character string 2. `6` from `9-3`: subtraction *Fixnum#-* 3. `1` from `3&5`: bitwise and *Fixnum#&* * By interpretation 5, I may use `3` again. 4. `8` from `2*4`: multiplication *Fixnum#\** 5. `0` from `2^2`: bitwise exclusive-or *Fixnum#^* 6. `3` from `7%4`: modulus *Fixnum#%* 7. `3` from `55>>4`: right shift *Fixnum#>>* 8. `9` from `5+4`: addition *Fixnum#+* 9. `8` from `2<<2`: left shift *Fixnum#<<* 10. `8` from `-~7`: negation of complement *Fixnum#-@ Fixnum#~* * Subtraction *Fixnum#-* and negation *Fixnum#-@* are different methods. 11. `7` from `5|2`: bitwise or *Fixnum#|* 12. `4` from `2**2`: exponentiation *Fixnum#\*\** 13. `9` from `(2r+2+5).to_i`: rational addition *Rational#+ Rational#to\_i* * By interpretation 2, *Fixnum#+* and *Rational#+* are different methods. They both add numbers, but they have different implementations, starting from different types for the left number. * Rational literals like `2r` are new in Ruby 2.1. `2r+2` calls *Rational#+* and returns another rational; `2r+2+5` calls *Rational#+* again. * Ruby prints rationals like `2/1` and floats like `2.0`. To fix this, I convert to integer: *to\_i* rounds toward zero, *ceil* rounds up, *floor* rounds down. 14. `8` from `(2.2+5).ceil`: float addition *Float#+ Float#ceil* * By interpretation 1, I may use parentheses `()` and dot `.` again. 15. `9` from `(55r/5-2).floor`: rational division and subtraction *Rational#/ Rational#- Rational#floor* 16. `4` from `(2.2*2).to_i`: float multiplication *Float#\* Float#to\_i* 17. `8` from `(2r*2*2).ceil`: rational multiplication *Rational#\* Rational#ceil* 18. `4` from `(2.2**2).floor`: rational exponentiation *Rational#\*\** 19. `8` from `2.to_bn<<2`: left shift with OpenSSL big number *Fixnum#to\_bn OpenSSL::BN#<<* 20. `2` from `__LINE__`: magic constant for current line number 21. `0` from `$<.to_i`: file descriptor of standard input *IO#to\_i* 22. `4` from `IO::LOCK_NB`: flag for non-blocking file lock * This is the first of many constants to depend on system. OpenBSD has 4. * By interpretation 4, I may no longer use `IO`. By interpretation 7, I may no longer use any constant with the value of 4. 23. `5` from `Errno::EIO::Errno`: number for input/output error 24. `8` from `File::APPEND`: flag to append to a file * This is a loophole around interpretation 4. I may not use `IO`, but `File` inherits constants from `IO`, so `File::APPEND` is a different way to get `IO::APPEND`. 25. `6` from `'aaaaaa'.size`: length of string *String#size* 26. `8` from `?a.encoding.name.sub(/\D+/,'')`: part of name of encoding *String#encoding Encoding#name String#sub* * By interpretation 6, I may use string quotes again. * Since Ruby 2.0, the default encoding is UTF-8. I take the name "UTF-8" and substitute /\D+/ matching "UTF-" with an empty string. This yields "8". 27. `3` from `%w[a a a].size`: length of array *Array#size* 28. `4` from `%w[a b c d].to_set.size`: number of elements in set *Array#to\_set Set#size* 29. `3` from `%w[a a a].count`: count all elements *Array#count* * The difference between *Array#size* and *Array#count* is that the latter takes optional arguments to choose which elements to count. I pass no arguments, so it counts all elements. 30. `6` from `Socket::AF_NS`: number for NS address family 31. `5` from `Date.jd(Date::ITALY).wday`: weekday number for Friday 15 October 1582, when Italy switched to Gregorian calendar *Date::jd Date#wday* 32. `6` from `*Digest::MD5.digest(?j).scan(/\d/)`: first ASCII digit in binary MD5 digest of "j" *Digest::MD5::digest String#scan* * *String#scan* returns an array of all matches. The `*` passes the array elements as arguments to `print`. This array is ["6"]. 33. `3` from `Set[?a,?b,?c].count`: count all elements *Set::[] Enumerable#count* * By interpretation 2, *Array#count* and *Enumerable#count* are different methods. 34. `8` from `SignalException.new('FPE').signo`: number of SIGFPE *Class#new SignalException#signo* 35. `1` from `Float::ROUNDS`: rounding mode, here 1 for round-to-nearest 36. `1` from `begin` (newline) `exit false` (newline) `rescue Object` (newline) `$!.status` (newline) `end`: exit status for failure * This is the same value as `SystemExit.new(false).status`, but by interpretation 3, I may no longer call *Class#new*. Instead I raise and rescue a SystemExit. 37. `7` from `Process::RLIMIT_NPROC`: number for resource limit for number of processes for one user 38. `7` from `:aaaaaaa.size`: length of symbol *Symbol#size* 39. `2` from `Prime.first`: first prime number *Enumerable#first* 40. `0` from `?/.next`: next string after "?" *String#next* 41. `3` from `{a:p,b:p,c:p}.size`: length of hash *Hash#size String#p* 42. `0` from `STDIN.lineno`: current line number for standard input *IO#lineno* * By interpretation 8, I may not reuse `$<`. I use `STDIN`. The difference is that `$<` is a global variable and `STDIN` is a constant. A program may set `$<` to a different input, but `STDIN` is always the original value of `$<`. 43. `3` from `?a.crypt('at')[/\d/]`: first ASCII digit in encrypted password *String#crypt String#[]* * System with different crypt() function will give different result. 44. `0` from `{a: :a}.find_index([:a,:a])`: index of first key :a, value :a in hash *Enumerable#find\_index* * I use a hash, not an array, because *Array#find\_index* is an alias for *Array#index*, which I plan to use soon. 45. `9` from `/b/=~'aaaaaaaaab'`: index where string matches /b/ *Regexp#=~* 46. `1` from `[?a,?b].index(?b)`: index of first "b" in array *Array#index* 47. `7` from `:aaaaaaab=~/b/`: index where symbol matches /b/ *Symbol#=~* 48. `9` from `?\t.ord`: ASCII value of tab "\t" *String#ord* 49. `8` from `'aaaaaaaab'=~/b/`: index where string matches /b/ *String#=~* * By interpretation 2, *Regexp#=~* and *String#=~* are different methods. 50. `0` from `open(?/).pos`: position in file after opening root directory "/" as a file *Kernel#open IO#pos* 51. `5` from `'aaaaab'.index(?b)`: index of first "b" in string *String#index* 52. `7` from `?\a.bytes{|b|break b}`: ASCII value of alert "\a" *String#bytes* * This works by iterating the bytes in "\a", but breaking the loop by returning the first byte. 53. `6` from `'aaaaaaa'.rindex(?a)`: index of last "a" in string *String#rindex* 54. `2` from `%w[a a].map.size`: size of enumerator that maps from array *Array#map Enumerator#size* [Answer] # Java, 21 digits, 276 characters ``` class C{public static void main(String[]a){System.out.print((3&5)+"."+(2|4)+Byte.BYTES+2*4+"".length()+(7-4)+~-4+(7+2)+(2<<2)+(int)Math.sqrt('@')+(2^5)+(int)Math.pow(2,2)+32%23+Byte.SIZE+('$'>>2)+Float.BYTES+Long.BYTES+Integer.BYTES+Double.BYTES+Short.BYTES+Math.round(.2));}} class C { public static void main(String[] a) { System.out.print( (3&5)+ // 1 "."+ // . (2|4)+ // 6 Byte.BYTES+ // 1 2*4+ // 8 "".length()+ // 0 (7-4)+ // 3 ~-4+ // 3 (7+2)+ // 9 (2<<2)+ // 8 (int)Math.sqrt('@')+ // 8 (2^5)+ // 7 (int)Math.pow(2,2)+ // 4 32%32+ // 9 Byte.SIZE // 8 // rest of explanation to come later today ); } } ``` [Answer] # Ruby, 74 chars, 10 digits It's just a start; I have to go so I will improve it later. ``` $><<[3-2,?.,3+3,?..size,2**3,$*.size,24/8,7%4,[*7..77][2],2*4,7.next].join ``` I have 76 characters saved up for later, when it will get more difficult! [Answer] # Ruby, 17 digits, 168 bytes ``` $><<[-~0,'.',9-3,3/3,2**3,$.,25%22,' '=~/$/,2+7,2<<2,"10".oct,2|5,[2,2,2,2].size,[*$....2*5].last,(2^5).succ,'a'.to_i(25).pred,'aaaa'.count('a'),eval(55.chr.next)]*'' ``` Ungolfed: ``` $><<[ -~0, # 1 '.', # . 9-3, # 6 3/3, # 1 2**3, # 8 $., # 0 25%22, # 3 ' '=~/$/, # 3 2+7, # 9 2<<2, # 8 "#{'a'.hex}".oct, # 8 2|5, # 7 [2,2,2,2].size, # 4 [*$....2*5].last, # 9 (2^5).succ, # 8 'a'.to_i(25).pred, # 9 'aaaa'.count('a'), # 4 eval(55.chr.next) # 8 ]*'' ``` Haven't been forced to do anything particularly clever yet, I may come back and add digits. [Answer] # [Golfscript](http://golfscript.apphb.com/?c=ICAgICIuIiwgICAgICAgICAgICAgICAgICAgICAgICAgIyAxOiBzdHJpbmcgbGVuZ3RoIChzZXBhcmF0ZSBmcm9tIGFycmF5IGxlbmd0aCkKICAgICcuJyAgICAKICAgIDMgMysgICAgICAgICAgICAgICAgICAgICAgICAgIyA2OiBhZGRpdGlvbgogICAgJydbNDldKyAgICAgICAgICAgICAgICAgICAgICAjIDE6IHN0cmluZyBjb25jYXRlbmF0aW9uCiAgICAtOX4gICAgICAgICAgICAgICAgICAgICAgICAgICMgODogYml0d2lzZSBub3QKICAgIDIhICAgICAgICAgICAgICAgICAgICAgICAgICAgIyAwOiBib29sZWFuIG5vdAogICAgNyA0JSAgICAgICAgICAgICAgICAgICAgICAgICAjIDM6IG1vZHVsdXMKICAgIDQoICAgICAgICAgICAgICAgICAgICAgICAgICAgIyAzOiBkZWNyZW1lbnQKICAgIDcpKSAgICAgICAgICAgICAgICAgICAgICAgICAgIyA5OiBpbmNyZW1lbnQKICAgIDI1NyAyLzIvMi8yLzIvICAgICAgICAgICAgICAgIyA4OiBkaXZpc2lvbgogICAgNCAyKiAgICAgICAgICAgICAgICAgICAgICAgICAjIDg6IG11bHRpcGxpY2F0aW9uCiAgICAyMiA1LSA1LSA1LSAgICAgICAgICAgICAgICAgICMgNzogc3VidHJhY3Rpb24KICAgIDIgMj8gICAgICAgICAgICAgICAgICAgICAgICAgIyA0OiBwb3dlcgogICAgWzIgNV0gMiBiYXNlICAgICAgICAgICAgICAgICAjIDk6IGJhc2UgY29udmVyc2lvbgogICAgWzIgMiAyIDIgMiAyIDIgMl0sICAgICAgICAgICAjIDg6IGFycmF5IGxlbmd0aCAoc2VwYXJhdGUgZnJvbSBzdHIgbGVuZ3RoKQogICAgWzIgMiAyIDIgMiAyIDIgMiAyIDVdNT8gICAgICAjIDk6IGFycmF5LmZpbmQoKQogICAgMiAyKyAgICAgICAgICAgICAgICAgICAgICAgICAjIDQ6IGFkZGl0aW9uCiAgICAiMiAyKjIqIn4gICAgICAgICAgICAgICAgICAgICMgODogZXZhbA%3D%3D), 17 digits A straightforward attempt. Golfscript may have a lot of non-alphanumeric one-letter built-ins, but it doesn't have many built-ins as a whole! ``` ".", # 1: string length (separate from array length) '.' 3 3+ # 6: addition ''[49]+ # 1: string concatenation -9~ # 8: bitwise not 2! # 0: boolean not 7 4% # 3: modulus 4( # 3: decrement 7)) # 9: increment 257 2/2/2/2/2/ # 8: division 4 2* # 8: multiplication 22 5- 5- 5- # 7: subtraction 2 2? # 4: power [2 5] 2 base # 9: base conversion [2 2 2 2 2 2 2 2], # 8: array length (separate from str length) [2 2 2 2 2 2 2 2 2 5]5? # 9: array.find() 2 2+ # 4: addition "2 2*2*"~ # 8: eval ``` [Answer] # Julia - 23 digits in 345 characters (15 per digit exactly) ``` print(div(2,2),'.','/'+7,length(" "),2^3,size([])[end],isqrt(9),int(cbrt(27)),54-45,'h'$'P',[2:22][7],endof("2222222"),count(isodd,[5,5,5,5]),search("Hello man",'n'),nextpow2(5),rsearch("Love boat",'t'),sizeof('й'),("I"summary(b"H"))[22],iceil(float(pi)),iround(cosh(e)),ifloor(exp(catalan)),cmp(5,5),itrunc(5sin(one(Int))),uint(erfcx(-ones()))) ``` Output: 1.6180339887498948482045 I interpreted characters and strings as usable, so long as I did not re-use a specific character or string (characters in a string could be re-used, as long as the string was not); however, I did not permit myself to use the int value of a character directly. There is one non-ASCII character (й). In a more readable fashion (not actual code): ``` 1> div(2,2) .> '.' 6> '/'+7 1> length(" ") 8> 2^3 0> size([])[end] 3> isqrt(9) 3> int(cbrt(27)) 9> 54-45 8> 'h'$'P' 8> [2:22][7] 7> endof("2222222") 4> count(isodd,[5,5,5,5]) 9> search("Hello man",'n') 8> nextpow2(5) 9> rsearch("Love boat",'t') 4> sizeof('й') 8> ("I"summary(b"H"))[22] 4> iceil(float(pi)) 8> iround(cosh(e)) 2> ifloor(exp(catalan)) 0> cmp(5,5) 4> itrunc(5sin(one(Int))) 5> uint(erfcx(-ones())) ``` [Answer] # Bash, 5 digits in 65 chars I will update this soon! For now, it just prints `1.6180`, and does not contain any digits. ``` false tr -d ' '<<<$?.`wc -c<<<abcde``nl<<<' '``kill -l FPE`$(()) ``` ## Explanation The following methods are used to generate the digits: 1: exit status of `false` 6: string length 1: `nl` abuse 8: `kill` signal numbers 0: numeric value of an empty expression [Answer] # Mathematica 9 8 digits, in 86 83 78 characters. ``` 10`8FromDigits@#/10^Length@#&@{a/a,3!,-I I,2π/(45°),#&''[],Prime@2,Sqrt@9,4+5} ``` Output: ``` 1.6180339 ``` [Answer] ## C++ 12.4 chars per line, was 14 chars per line for each digit Fixed my mistake of reusing operators. ``` #include <iostream> #include <math.h> #define S std::string #define C(x) std::cout<<x int main() { C(cos(0)); C(char(46)); C('j'%'d'); C('\0'+3-2); C(sqrt('@')); C(log(1)); C('c'/'!'); S s("xyz"); C(s.size()); return 0; } ``` Not sure if using chars like this counts as char literals or not? If this code is acceptable it can be continued forever and char debt will be paid back. ``` #include <iostream> #define C(x) std::cout<<x int main() { C('b'-'a');//1 C(char(46));//. C('g'-'a');//6 C('b'-'a');//1 C('i'-'a');//8 C('a'-'a');//0 C('d'-'a');//3 C('d'-'a');//3 C('j'-'a');//9 //etc return 0; } ``` ]
[Question] [ The challenge is simple, find the matching parentheses for every one of the parentheses in a given string input E.g. ``` ()()() -> [1, 0, 3, 2, 5, 4] ``` Always start with the ending parentheses index before the starting parentheses, which is why `()` becomes `[1,0]`, not `[0,1]`, unless the parentheses is stacked e.g. `(())`, where the position of the parentheses must match the index so `(())` is `[3, 2, 1, 0]` ## Test Cases: ``` () -> [1, 0] ()(()) -> [1, 0, 5, 4, 3, 2] ()()() -> [1, 0, 3, 2, 5, 4] ((())) -> [5, 4, 3, 2, 1, 0] (()(())) -> [7, 2, 1, 6, 5, 4, 3, 0] ``` You may output the indexes in the form of a list, or in the form of a string representation if so, but the output indexes must be distinguishable from each other e.g. `1 0` You are allowed to use 0-index or 1-indexed lists/arrays. **This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest bytes wins!** [Answer] # x86-64 machine code, 21 bytes ``` 5A 58 89 0A 8D 51 57 AB FF C1 45 31 C9 AC 84 C0 7B EE 75 F1 C3 ``` [Try it online!](https://tio.run/##XVLPb9sgFD6bv@KNqSokTpR03TTFyy7ddZedJrk@OIBjJgIW4M5Z5H993qNJ27UHw3sf7/sBsui6xV6IaarDARj8oIws98btagMN8d0m61wHXg7kXNRYHNwDlAhVOSiB/XJ3jApWw@dvxCRCH1rw6eBcSU2yEF2QJNNWvKbcfiTNJhucT/BFzjgZdiSLKkSoTY4fyX51DnyHu/0DBnevIuEUeEHUEJW3QO8onB6cltAwbSPMvAq9iTkIZ1FHtLWHWeDFSMh7TGF6qeBLiFK7ZfuVkP@nkrGogwplBVs4UcZpjgtj/FLwM5IATseCJL9DrS3j5ESyBi/DXunBBp41OclwJkuUc8JyvaoKRBr2lDjy1HceZxpGrwJ9gh6VE1NjrlUBsdRVAXo@R9EXAlxpZFzEdXUW62PKwq7v7XUCRvI8fm@/16LVVuFLSbWh6Th5DMkjhyO20sHpRX118xP1j1vGehv03ir5eM8ZbxbrNS@H@Rw9R/jdaqOAHeEd6gx3H5LumxjjNP0Vjan3YVocPt3igv/gFn2U@Qc "C++ (gcc) – Try It Online") Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as an array of 32-bit integers; and the address of the input, as a null-terminated byte string, in RSI. In assembly: ``` .global f rp: pop rdx # (Right parenthesis) Pop the matching left parenthesis's # corresponding output address into RDX. pop rax # Pop its index into RAX. mov [rdx], ecx # Put the current index at the popped address. .byte 0x8D # Subsumes the next two instructions into 'lea edx, [rcx+0x57]'. lp: push rcx # (Left parenthesis) Push the index onto the stack. push rdi # Push the corresponding output address onto the stack. stosd # Store EAX at [RDI] and advance the pointer. inc ecx # Increment the index. .byte 0x45 # REX.RB prefix byte; changes the next instruction to 'xor r9, r9'. f: xor ecx, ecx # (Start here.) Set ECX to 0 (index in string). lodsb # Load a character of the string into AL, advancing the pointer. test al, al # Set the flags based on that character. jpo rp # Jump if it has an odd number if 1 bits (for a right parenthesis). jnz lp # Jump if it is nonzero (for a left parenthesis). ret # Return (for the null terminator). ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 37 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` {⌽˘⌾(∘‿2⊸⥊)¨⌾(((1⊸≠++`)¯1⋆𝕩-@)⊸⊔)⊒˜𝕩} ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpB74oy9y5jijL4o4oiY4oC/MuKKuOKliinCqOKMvigoKDHiirjiiaArK2Apwq8x4ouG8J2VqS1AKeKKuOKKlCniipLLnPCdlal9CgpGICIoKSgoKSki) `(1⊸≠++`)¯1⋆𝕩-@` generates a depth map for the brackets. Coupled with Under, we can group the indices by depths, and reverse the grouping to get back the original array shape. `⌽˘⌾(∘‿2⊸⥊)¨` reverses each pair of bracket indices, putting them in the correct place. -1 and -4 with ovs' help. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 51 bytes ``` a=>a.map((c,i)=>a[a[i]=a.lastIndexOf(c>'('&&-1)]=i) ``` [Try it online!](https://tio.run/##JYyxDoIwFEV3vqITfS@Bl7iZkLIx6CCDI2F4KRRrsCW0MRrjtyPIcu49d7h3fnLQs51i7nzXL0YtrEqmB08AOrO4SsONbRXTyCGeXNe/agO6lCDTND9gqywuErAA3AC4t3342yZbrERJYRptBFlIJOPnivUNolCl@CRCaO@CH3sa/QCRJu4q18ERMwEGWCjREFFsVz9f6wuFOFs3WPMGXp@L5IvF8gM "JavaScript (Node.js) – Try It Online") Input an array of characters. Output by modify the array in-place. [Answer] # [Haskell](https://www.haskell.org/), 112 bytes ``` g(a:x)|a>'('=1|w<-g x=1+w+g(drop w x) a#b=succ<$>a!map(-1+)b ('(':x)!s=g x:x#(0:s) (_:x)!(a:s)=a:x#s _!w=w (![]) ``` [Try it online!](https://tio.run/##FczLCoMwEIXhfZ5iYgRnEKFuxfFFSpHRlij1hmlJFr57msJZHfj@Sdz7tSwxWpQm0CVdgQXXl28rC4Hr0pcWn@d@gIdASszA7juObd6JXuXAqi5pUJhQ0tpxQk0weGscKez/X@o64hQ3TvXas1cTo74/KK4yb8BwnPP2gRwmyBAJKS2LPw "Haskell – Try It Online") With some comments: ``` -- Get the 1-based index of the first unmatched ')' g :: [Char] -> Int g(a:x)|a>'('=1|w<-g x=1+w+g(drop w x) -- Common part of the two cases in (!); updates the indices (#) :: [Char] -> [Int] -> [Int] a#b=succ<$>a!map(-1+)b -- Main function, iterates through the string (!) :: [Char] -> [Int] -> [Int] -- '(' are replaced by the result of g on the remaining string ('(':x)!s=g x:x#(0:s) -- ')' are replaced by the index of the matching '(' (stored in the right argument) (_:x)!(a:s)=a:x#s _!w=w h :: [Char] -> [Int] h=(![]) ``` [Answer] # [Haskell](https://www.haskell.org/), 94 bytes ``` snd.([]%).zip[0..] z%((i,c):x)|c<')',(j:k,a)<-(i:z)%x=(k,j:a)|v:w<-z=([i],[v])<>w%x z%e=mempty ``` [Try it online!](https://tio.run/##bc2xboMwFIXhnae4ioJyr2RbnS07SyulS6XulMECUxzAWOAGivLsdenadv3065zWzJ3t@@SGME4Rnkw04mX0o6sBUZ2JgHPwdoHL8yO0ZobYuhmch9fJ9h@1FVmj39Lsa4FFmZPYXCgehCizLUd0rCK50r1SJzoxvMqOGVIcndwoXzV27CoN3W9yUXzTWLiSFbeS1HnJ133A6sEOIX6mweyHGuoxAwiT8xGO0MAB6fAbEOkfpL/lT7hj@qqa3rzPiVchfAM "Haskell – Try It Online") [Answer] # Python3, 75 bytes ``` def f(a,*s,i=-1): for c in a: i+=1;s+=i, if"("<c:*s,a[i],_=s;a[a[i]]=i ``` [Try it online!](https://tio.run/##NY4xDoMwDEX3nsLKZJcwoG5QnwShKqJEtVQFRLJw@tQWdLHf//K3vR3ls6ZHre8lQsTg79kLtx31N4jrDjNIgqACpOFuyA2LNxEduufc63QYZfIvzkMYDSeWasGy5GJZh@S8VUT6E12eWRfRyXYoAMNXckFbQWroW9a2XVJRrD8) -2 thx to @KevinCruijessen -6 thx to @ovs -10 thx to @loopywalt -6 thx to @ovs -4 thx to @loopywalt ## Other solutions: ## Python3, 76 bytes ``` def f(a,s=[]): for*s[:0],c in enumerate(a): if"("<c:i,v,*_=a[v],a[i],*s=s ``` [Try it online!](https://tio.run/##NY5BCgMhDEX3PUVwFSWLQjdF6klEikyVCq0zGGegp7cG2k3yeeGFv336c62X69bGeKQMGSOx80HbE@S1Gfb2HGiBUiHV/Z1a7AmjXKFkheq22EIHmbuL/ggUfQlk2PGYMvTEXUyFWpFMRP1P@scEaSX/Ijh4Fe4omp5gdpG1tVL7jOML) [Answer] # [Python](https://www.python.org), 93 bytes ``` def f(x): d=c=0 for y in x:c-=y<')';x[d]=c;x[k:=x.index(c)]=d;x[d]=[c,k][k<d];c+=y>'(';d+=1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY5BbsMgEEX3PsXsGBpsJW0jVXbIRSwWERgVGWPL0Mo-SzfetHfKbQqmUsoGzX_z_5-vn2kN76Pbtu-PoMu3u1CdBo0LrQtQXPJjAXqcYQXjYKllydcLoaRZWiW4jF9f86UyTnULSiq4yqSVrBdtf1GikQe-XgmSRh346a9kNsM0zgH86ouUblN6HCoflHHV3N2UNa7zmK6Iz7ARONjKT9YEJFBegdCdJL37vFkc8zzNxgWM-0zjUPP2yQgaCwaam7e7RJrs7YnBURRIEelDYHBm8MrghcHzDin-h0nOKxEmY4YPD4M9Nnf9Ag) Takes a list of characters and modifies it in-place. #### How? Simply walks the list from left to right. Tracks the bracketing depth (uses negative numbers, so we can unambiguously overwrite them with indices later). Whenever we encounter a level for the second time swap indices with first occurrence. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~19~~ 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` '(QvyiNëN‚ˆ]¯vyÂǝ ``` Input as a list of characters. [Try it online](https://tio.run/##yy9OTMpM/f@/rFJdIzDT7/Bqv0cNs063xR5aX1Z5uOn43P//o5U0lHTAWBNKw9gQHAsA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaWLEpCrrhGY6Xd4td@jhlmn22IPrS@rPNx0fO5/Jb0wnUNb/kdHK2ko6ShpKsXqKMCYOmAaxsYihaDhUqg6MKQ0sSuJBQA). **Explanation:** ``` v # Loop over the characters `y` of the (implicit) input-list: y'(Qi '# If the current character is a ")": N # Push the current loop-index ë # Else: N‚ # Pair the top value on the stack with the current loop-index ˆ # Pop and add this index-pair to the global array ] # Close both the if-statement and loop ¯ # Push the global array of index-pairs v # Loop over each pair of indices: y # Bifurcate the current pair; short for Duplicate & Reverse copy ǝ # Insert the values at the indices in the list # (which will use the implicit input-list the first iteration, # and modifies it further every iteration) # (after which the list is output implicitly as result) ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 61 bytes -1 byte thanks to [@DialFrost](https://codegolf.stackexchange.com/users/109916/dialfrost). ``` s->for(i=j=1,#a=s,if(")">s[i],s[j]=i;j++,a[a[i]=s[j--]]=i));a ``` [Try it online!](https://tio.run/##JchBCgIxDIXhq4S4SZh04XpIj@GmdBHESotombjx9J0WeZvv/d2OGp59FNDhIZbPQVWbXuVi6lILIWP0VLN4alnr3rZNLNksOksIeUbm3Yb1/vqRQ4jQj/r@TuI6CIVujzs5MwskJF5DgSXivxYYM48T "Pari/GP – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 82 bytes ``` sub f{($_,$i)=(@_,0);/\((?R)*\)/?(reverse($i..$i-1+($l=length$&)),f($',$i+$l)):()} ``` [Try it online!](https://tio.run/##XY9NT8JAEIbv/Io3zeLOyPCpeIBUejeRhHgD0kTd1o211FKMhvDb67bUIOxp33mendnJTJ6My3K7e0a0JxWKsuxTEMqAp/0V0WzB1yvuzyg3XybfGlK211O2O@yQSvzEpHHxpq6YJSKl3eOOSpgnxIcy2uTUWgKaWKM6/j2WQ8FgDaylIUTs6B8RjAW3ghvB6MxiOrMqfnT/WVWrxjp1EVxMrOcd/3LJed8CPn7chqIM@4EKp3UhiH23nOUqZblNi8hrd@@2gPnOzEthXidod4cjV0C8KU7BptnORWVXqSfwAmU8mE93iT3MoDfvGhPox/kT5g@6EaTG09ah/AU "Perl 5 – Try It Online") [Answer] # x86-16 machine code, 21 bytes ``` 00000000: 33db ac3c 2974 0353 eb07 5888 0193 8801 3..<)t.S..X..... 00000010: 9343 e2ee c3 .C... ``` Listing: ``` 33 DB XOR BX, BX ; start index counter at 0 P_LOOP: AC LODSB ; AL = next char in input string 3C 29 CMP AL, ')' ; is it an end paren? 74 03 JZ END_PAREN ; if so, jump to handle 53 PUSH BX ; else, push index of left paren to stack EB 07 JMP NEXT_PAREN ; continue loop END_PAREN: 58 POP AX ; AL = index of last start paren 88 01 MOV [DI+BX], AL ; write to output at current index of input string 93 XCHG AX, BX ; AL = current index of input string 88 01 MOV [DI+BX], AL ; write to output at index of last start paren 93 XCHG AX, BX ; restore index counter to BX NEXT_PAREN: 43 INC BX ; increment counter E2 EE LOOP P_LOOP ; continue string loop C3 RET ``` Custom calling convention - input string at `[SI]`, length in `CX`, output to buffer at `[DI]`. Tests with DOS DEBUG: [![enter image description here](https://i.stack.imgur.com/YqTVh.png)](https://i.stack.imgur.com/YqTVh.png) [![enter image description here](https://i.stack.imgur.com/ecLn2.png)](https://i.stack.imgur.com/ecLn2.png) [![enter image description here](https://i.stack.imgur.com/zNn6M.png)](https://i.stack.imgur.com/zNn6M.png) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 67 bytes ``` \((?=((\()|(?<-2>.))*(?<=(.+)))|(?<=(.*).((\))|(?<-6>.))*). $.3$.4 ``` [Try it online!](https://tio.run/##JYohDoAwEAR9X4Go2C3pCSAo2n6kBoHAIAiSvx/toWZnM/fxnNeuWoGSgAq@KFucspChrQQZSTvbDJTW/BpXayjOy@xlGVRBBwI0sFuXDnv5AQ "Retina 0.8.2 – Try It Online") Link includes test cases. Assumes input is a balanced string of `()`s. Explanation: The first alternation matches a `(`, skips over any balanced `()`s, then captures the resulting index, while the second alternation matches in reverse, skipping back over any balanced `()`s and an implied `(` before capturing the resulting index, then matching an implied `)`. Fortunately `$.` outputs an empty string if the group was not captured at all, so we can just output the length of whichever capture was successful followed by a separator. [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~144~~ 136 bytes ``` I =INPUT M =BAL | '' N I POS(X) LEN(1) . B @X :F(END) B ")" :F(L) I @O '(' M B POS(X) :(O) L I POS(X) M @O ')' O OUTPUT =O :(N) END ``` [Try it online!](https://tio.run/##RY0xC8IwFITnvF9xdMl7iyA4FQI1WCGQ5BVsobOz2KGr/z0@RRBuueO7u/253bfHqTWXEFKdlplcQYjnjBe8p2r5pDdeBXmsfBQcEDGsrr/yWC9CLqKT7mOzmYRB4dmjGPXruZ5VKP@HyhcST@p0me0SQQ2qQrbYGrOYRN4 "SNOBOL4 (CSNOBOL4) – Try It Online") ``` I =INPUT ;* Read input M =BAL | '' ;* Alias: M is BAL (the shortest, non-null balanced string) or the empty string N I POS(X) LEN(1) . B @X :F(END) ;* extract the next character of I as B, and store the position after B as X B ")" :F(L) ;* If B matches ")", goto next line, else goto L I ;* In I, match: @O ;* the position before the match as O '(' M B ;* "(", a balanced string (or nothing), and ")" POS(X) :(O) ;* ending at position X, then goto O L I POS(X) M @O ')' ;* In I, match, starting at position X, a balanced string, storing position as O, followed by ")" O OUTPUT =O :(N) ;* Output O and goto N END ``` [Answer] # APL+WIN, 42 bytes Prompts for input string. Index origin = 1 ``` (,⌽((.5×⍴n),2)⍴n)[⍋n←⍋+\(~n)-¯1↓0,n←')'=⎕] ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv4bOo569Ghp6poenP@rdkqepY6QJpqMf9XbnAZUBKe0Yjbo8Td1D6w0ftU020AGJqmuq2wINiv0PNIPrfxqXuoamOheY0tDQhDM1YaIgQU11AA "APL (Dyalog Classic) – Try It Online") [Answer] # [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 55 bytes ``` g .zip[0..] g[]=[] g((i,'('):x++(j,')'):y)=j:g x++i:g y ``` [Try it online!](https://tio.run/##NYxNC4MwDIbv/RVZGZjgBzsX6n2HscOOIkNkljqUYivM/fkuOr3kfXiSN@08TUvumnfrY@y0geJrXXUpilqYqtYVB6LNEkxIfdIU@ywhxoV0rwywsRxLDC8fQCl4hMmOBvISrndAEpv3oMHNgXeMZXmwXM/kKtBxK8D5dIIOPAkxNHbk0tC42xO2H5VEkhnwRKSDaHer2on@XMcf "Curry (PAKCS) – Try It Online") [Answer] # Python3, 124 bytes: ``` import re def f(s): while'('in s: s=re.sub('\(\d*\)',lambda x:f'{(S:=x.span())[1]-1}{x.group()[1:-1]}{S[0]}',s) return s ``` [Try it online!](https://tio.run/##TVDJbsIwED3XXzHi4hnkRKTQRZHST@iFY4gqR3GKpSyWbVoqxLfTSVNajvO2mTfuK@7HYf3s/OViezf6CN6IxrTQYqBcwOfedkaitAMEHiEU3qThUKPc4a5Z7kiqTvd1o@GYt/KE27w4psHpAYnKrEqy8@mYvvvx4JDnPMmq82lbrqqzVIEEL4sHz9HX5TpEEYrFYoEEyQuUmYJVJZCQ4/4ABQ8KNgrWCu5/SMJbcoJnCZOTcSb/PQp@Y@fcmX66Eo838SziW0Q7erDAL2htF43H13EwCgL37GzkTwyS@Fd3WtVQgL3CU6wkhkMwXK1c9tqhHaJqURNVRTG1TVlqvO7ezIfusCbhPEtQRhNiADd5G0mXbw) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes ``` ≔⟦⟧ηFθ¿⁼(ι«⊞υLη⊞η⁰»«§≔η⌈υLη⊞η⊟υ»Iη ``` [Try it online!](https://tio.run/##dYwxC8IwFIRn8ysend6DCO5ORRwEheziEGraBNKkbRIpiL89JnYWbrn77q7Tcum8tDm3IZjB4f3BQdOR9X4BnAlMD3iek7QBG2w4GCJ4s51IQWPicFVuiBo1lckWag6HYj6gbFC1uh238eKeaq34JlczphET/dkLPxVYT5hYjIt4kiH@OjkjUhFR3r/sFw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⟦⟧η ``` Start building up the output list. (I need a second list as I want to use the predefined empty list as a stack.) ``` Fθ ``` Loop over the input characters. ``` ¿⁼(ι« ``` If this is a `(`, then... ``` ⊞υLη ``` ... save the current index to the stack, and... ``` ⊞η⁰ ``` ... push a dummy value to the output list. ``` »« ``` Otherwise, ... ``` §≔η⌈υLη ``` ... replace the latest dummy value with the current index, and... ``` ⊞η⊟υ ``` ... push its index to the output list, removing it from the stack. ``` »Iη ``` Output the final list of indices. [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 24 [bytes](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` (⊢⊔⁼⊢(⊔⊒˜¨×⋈¬⊸×)·+`¬-»)⊐ ``` [Try it here.](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgKOKKouKKlOKBvOKKoijiipTiipLLnMKow5fii4jCrOKKuMOXKcK3K2DCrC3CuyniipAKRsKoIOKfqCIoKSIsIigpKCgpKSIsIigpKCkoKSIsIigoKCkpKSIsIigoKSgoKSkpIuKfqQ==) How it works [(with example)](https://mlochbaum.github.io/BQN/try.html#code=IyAo4oqi4oqU4oG84oqiKOKKlOKKksucwqjDl+KLiMKs4oq4w5cpwrcrYMKsLcK7KeKKkAoK4oCiU2hvdyAiSW5wdXQ6IiAgICDii4ggICBpIOKGkCAiKCgpKCgpKSkiCuKAolNob3cgIk1hc2s6IiAgIDziirjiiL4gICBtYXNrIOKGkCDiipBpCuKAolNob3cgIkRlcHRoOiIgIDziirjiiL4gICBkIOKGkCAoK2DCrC3CuyltYXNrCuKAolNob3cgIlNwbGl0OiIgIDziirjiiL7ijL0gICAgICBtYXNrKCAgICDDl+KLiMKs4oq4w5cpZArigKJTaG93ICJNYXRjaDoiICA84oq44oi+ICAgcCDihpAgbWFzayjiipTiipLLnMKow5fii4jCrOKKuMOXKWQK4oCiU2hvdyAiQ29tYmluZToiPOKKuOKIviAgIG1hc2sg4oqU4oG8IHAKQA==): 1. Calculate the parenthesis depths from a mask of the string. 2. Split the depths into one vector where the indices of open parens are replaced with 0, and one vector where the indices of close parens are 0, such that if you add them together you get back the original depths. 3. Match depths of the open parens in the close paren half of the depth vector, and close parens in the open paren half, [without repeats](https://mlochbaum.github.io/BQN/doc/search.html#progressive-index-of). 4. Use the original mask to combine the two lists of indices back together. Detailed breakdown: ``` (⊢⊔⁼⊢(⊔⊒˜¨×⋈¬⊸×)·+`¬-»)⊐ # ⊐ # Classify the string to get a mask ( ·+`¬-») # Generate depths of parentheses ⊢( ×⋈¬⊸×) # Pair mask and it's negation, multiplied by the depths ⊔ # Group depths according to the mask ⊒˜ # Take the progressive index-of ¨ # between corresponding groups and depths ⊔⁼ # Inverse partition to combine results ⊢ # according to the original mask ``` ]
[Question] [ A radiation-hardened program is a program where, if any character of the code is removed, the program will still function the same. For this question, we'll be writing a program that detects when it is irradiated. Write a program or function that, when *any* single byte is removed, the resulting program will output that byte and only that byte. (*You may output that byte multiple times, as long as you don't output any other byte*) ### Rules: * The program has to contain at least 2 distinct bytes. (No solutions of just 0s ;) * It doesn't matter what the original program does * No reading your own source code. * The code will be scored on the number of distinct bytes, where the highest amount wins. For example, `abc` = 3 points, `ababba` = 2 points, `abc` wins. + Tie-breaker is the smaller byte count, followed by the earlier submission time Good luck! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 7 bytes (Score of 3) ``` 22'''rr ``` [Try it online!](https://tio.run/##MzBNTDJM/a9kZKSurl5UpBT6PyLdLeLwVr/jc5UCivLTixJzrRQUlOxt9cKUHJNLShNzgFwQP8Lv8Aol14qC1OSS1BQrkEjg6baLTW4xtUq6EKCkU3tove3//wA "05AB1E – Try It Online") # Removing a `'` With any `'` removed, `22''rr` will result in 22 being the first thing on the stack and a `'` being the last thing on the stack, which when reversed twice results in `'`. # Removing an `r` With any `r` removed, `22'''r` results in 22 being the first thing on the stack, a `'` being the second thing on stack, and an `r` being the last thing on the stack. This `r`, however, was preceeded by a `'` which makes it the literal string `"r"` (as opposed to the command `reverse stack`), which is implicitly printed. # Removing a `2` With any `2` removed, `2'''rr` will result in a `2` being the 1st thing on the stack, `'` being the 2nd thing on the stack and finally `r` being the last thing on the stack, which when reversed once results in `2`. Therefore, this answer is valid. With nothing removed it outputs `'`, which is irrelevant. This works for any number other than 2 as well. --- # [Created a validity checker, you can use it to compete in 05AB1E\*.](https://tio.run/##MzBNTDJM/a@kDgExMUqh/yPS3SIOb/U7PlcpoCg/vSgx10pBQcneVi9MyTG5pDQxB8gF8SP8Dq9Qcq0oSE0uSU2xAokEnm672OQWU6ukCwFKOrWH1tv@/w8A "05AB1E – Try It Online") \*I'm not 100% sure how many solutions are even possible in 05AB1E... --- # More valid solutions that are ***Worse or the Same*** * 1-Point (invalid) + [Any number of `'` above 2 will work...](https://tio.run/##MzBNTDJM/a@krq6uFPo/It0t4vBWv@NzlQKK8tOLEnOtFBSU7G31wpQck0tKE3OAXBA/wu/wCiXXioLU5JLUFCuQSODptotNbjG1SroQoKRTe2i97f//AA "05AB1E – Try It Online") * 2-Point + `'''''''VV`, `'''''''XX` or `'''''''<any command that pops a without pushing>x2` + Any odd # of `'` above 3 followed by any even # of `s` above 1 (E.G. `'''''''''ssss`). + `'''..` with any number of periods above 1 and any odd number of `'` above 2. * 3-Point + `'\\'''rr` - same idea as `22'''rr` but `\` is 'remove last stack item'. [Answer] # Brainfuck, Score 3 May be noncompeting as output is only seen through a memory dump. ``` +++++++++++++++++++++++++++++++++++++++++++++,- ``` Assuming input is empty and EOF leaves the cell unchanged. Uses an interpreter that dumps the memory to an output, such as [this one](https://copy.sh/brainfuck/). Remove a plus, and the memory is the unicode value for "+" , else it is the unicode value for ",". Its more of a rule bender than a answer though. Pretty much the same with "-". Abuses the fact that these three characters are after each other in the unicode-characterset. [Answer] # A Pear Tree, 256 distinct bytes, 975 bytes Unfortunately, the question pretty much requires an optimal solution to contain a NUL byte somewhere (as it needs to contain all 256 bytes somewhere). This means that a) I can't give you a TIO link (because TIO dislikes NUL in programs, or at the least, I haven't figured out a way to type it that my browser can cope with), and b) I can't paste the program into Stack Exchange literally. Instead, I've placed an `xxd` reversible hexdump hidden behind the "code snippet" link beneath. ``` 00000000: 0a24 7a7b 242f 7d2b 2b3b 242f 3d24 5c3d .$z{$/}++;$/=$\= 00000010: 2440 3b21 247a 7b24 5f7d 3f24 7a7b 245f $@;!$z{$_}?$z{$_ 00000020: 7d3d 313a 6465 6c65 7465 247a 7b24 5f7d }=1:delete$z{$_} 00000030: 666f 7220 7370 6c69 742f 2f2c 3c44 4154 for split//,<DAT 00000040: 413e 3b70 7269 6e74 206b 6579 7325 7a3e A>;print keys%z> 00000050: 353f 225c 6e22 3a6b 6579 7325 7a3b 5f5f 5?"\n":keys%z;__ 00000060: 4441 5441 5f5f 2000 0102 0304 0506 0708 DATA__ ......... 00000070: 090b 0c0d 0e0f 1011 1213 1415 1617 1819 ................ 00000080: 1a1b 1c1d 1e1f 2326 2728 292a 2b2d 2e30 ......#&'()*+-.0 00000090: 3334 3536 3738 3942 4345 4647 4849 4a4b 3456789BCEFGHIJK 000000a0: 4c4d 4e4f 5051 5253 5556 5758 595a 5b5d LMNOPQRSUVWXYZ[] 000000b0: 5e60 6162 6367 686a 6d71 7576 7778 7c7e ^`abcghjmquvwx|~ 000000c0: 7f80 8182 8384 8586 8788 898a 8b8c 8d8e ................ 000000d0: 8f90 9192 9394 9596 9798 999a 9b9c 9d9e ................ 000000e0: 9fa0 a1a2 a3a4 a5a6 a7a8 a9aa abac adae ................ 000000f0: afb0 b1b2 b3b4 b5b6 b7b8 b9ba bbbc bdbe ................ 00000100: bfc0 c1c2 c3c4 c5c6 c7c8 c9ca cbcc cdce ................ 00000110: cfd0 d1d2 d3d4 d5d6 d7d8 d9da dbdc ddde ................ 00000120: dfe0 e1e2 e3e4 e5e6 e7e8 e9ea ebec edee ................ 00000130: eff0 f1f2 f3f4 f5f6 f7f8 f9fa fbfc fdfe ................ 00000140: ff4b 3d20 ab0a 247a 7b24 2f7d 2b2b 3b24 .K= ..$z{$/}++;$ 00000150: 2f3d 245c 3d24 403b 2124 7a7b 245f 7d3f /=$\=$@;!$z{$_}? 00000160: 247a 7b24 5f7d 3d31 3a64 656c 6574 6524 $z{$_}=1:delete$ 00000170: 7a7b 245f 7d66 6f72 2073 706c 6974 2f2f z{$_}for split// 00000180: 2c3c 4441 5441 3e3b 7072 696e 7420 6b65 ,<DATA>;print ke 00000190: 7973 257a 3e35 3f22 5c6e 223a 6b65 7973 ys%z>5?"\n":keys 000001a0: 257a 3b5f 5f44 4154 415f 5f20 0001 0203 %z;__DATA__ .... 000001b0: 0405 0607 0809 0b0c 0d0e 0f10 1112 1314 ................ 000001c0: 1516 1718 191a 1b1c 1d1e 1f23 2627 2829 ...........#&'() 000001d0: 2a2b 2d2e 3033 3435 3637 3839 4243 4546 *+-.03456789BCEF 000001e0: 4748 494a 4b4c 4d4e 4f50 5152 5355 5657 GHIJKLMNOPQRSUVW 000001f0: 5859 5a5b 5d5e 6061 6263 6768 6a6d 7175 XYZ[]^`abcghjmqu 00000200: 7677 787c 7e7f 8081 8283 8485 8687 8889 vwx|~........... 00000210: 8a8b 8c8d 8e8f 9091 9293 9495 9697 9899 ................ 00000220: 9a9b 9c9d 9e9f a0a1 a2a3 a4a5 a6a7 a8a9 ................ 00000230: aaab acad aeaf b0b1 b2b3 b4b5 b6b7 b8b9 ................ 00000240: babb bcbd bebf c0c1 c2c3 c4c5 c6c7 c8c9 ................ 00000250: cacb cccd cecf d0d1 d2d3 d4d5 d6d7 d8d9 ................ 00000260: dadb dcdd dedf e0e1 e2e3 e4e5 e6e7 e8e9 ................ 00000270: eaeb eced eeef f0f1 f2f3 f4f5 f6f7 f8f9 ................ 00000280: fafb fcfd feff 4b3d 20ab 0a24 7a7b 242f ......K= ..$z{$/ 00000290: 7d2b 2b3b 242f 3d24 5c3d 2440 3b21 247a }++;$/=$\=$@;!$z 000002a0: 7b24 5f7d 3f24 7a7b 245f 7d3d 313a 6465 {$_}?$z{$_}=1:de 000002b0: 6c65 7465 247a 7b24 5f7d 666f 7220 7370 lete$z{$_}for sp 000002c0: 6c69 742f 2f2c 3c44 4154 413e 3b70 7269 lit//,<DATA>;pri 000002d0: 6e74 206b 6579 7325 7a3e 353f 225c 6e22 nt keys%z>5?"\n" 000002e0: 3a6b 6579 7325 7a3b 5f5f 4441 5441 5f5f :keys%z;__DATA__ 000002f0: 2000 0102 0304 0506 0708 090b 0c0d 0e0f ............... 00000300: 1011 1213 1415 1617 1819 1a1b 1c1d 1e1f ................ 00000310: 2326 2728 292a 2b2d 2e30 3334 3536 3738 #&'()*+-.0345678 00000320: 3942 4345 4647 4849 4a4b 4c4d 4e4f 5051 9BCEFGHIJKLMNOPQ 00000330: 5253 5556 5758 595a 5b5d 5e60 6162 6367 RSUVWXYZ[]^`abcg 00000340: 686a 6d71 7576 7778 7c7e 7f80 8182 8384 hjmquvwx|~...... 00000350: 8586 8788 898a 8b8c 8d8e 8f90 9192 9394 ................ 00000360: 9596 9798 999a 9b9c 9d9e 9fa0 a1a2 a3a4 ................ 00000370: a5a6 a7a8 a9aa abac adae afb0 b1b2 b3b4 ................ 00000380: b5b6 b7b8 b9ba bbbc bdbe bfc0 c1c2 c3c4 ................ 00000390: c5c6 c7c8 c9ca cbcc cdce cfd0 d1d2 d3d4 ................ 000003a0: d5d6 d7d8 d9da dbdc ddde dfe0 e1e2 e3e4 ................ 000003b0: e5e6 e7e8 e9ea ebec edee eff0 f1f2 f3f4 ................ 000003c0: f5f6 f7f8 f9fa fbfc fdfe ff4b 3d20 ab ...........K= . ``` ## Explanation This program consists of three identical parts. (Concatenating multiple identical portions of a program is something of a theme for me in [radiation-hardening](/questions/tagged/radiation-hardening "show questions tagged 'radiation-hardening'") programs.) Every A Pear Tree requires a checksum somewhere to let the interpreter know which parts of the program to run; it rotates any portion of the program for which the checksum succeeds to the start before running it (or prints `a partridge` if no checksum matches). In this case, we have a checksum on each of the three parts, and thus a non-irradiated part will move to the start. So we can assume that the program consists of an unmodified part, followed by two other parts (one of which may have been modified). Each part starts with a newline, then continues with the following code (I've added whitespace and comments below): ``` $z{$/}++; # In the hash table %z, set the key "\n" to 1 $/=$\=$@; # Turn off newline handling when reading ($/ = undef); # Also don't add newlines when printing ($\ = undef) # $@ is set to undef by default !$z{$_}? # If the current character is not in the hash table %z $z{$_}=1: # place it in the hash table %z delete$z{$_} # else remove it from the hash table %z for split//, # for each character in <DATA>; # the text appearing from the line beneath __DATA__ to EOF print # Print the following (no newline because $\ was undefined): keys%z>5? # if the hash table %z contains more than 5 elements: "\n": # a newline; otherwise keys%z; # every key of %z, separated by spaces __DATA__ # Start a string literal running from after this line to EOF ``` After that comes a copy of every octet that hasn't been used in the program so far (purely to run the score up), and finally the checksum. (There's no trailing newline; parts start with a newline but don't end with one.) There are three distinct cases here: * **A character other than a newline was deleted**. In this case, it'll appear an odd number of times in the second and third parts. That means it'll be added and/or removed from `%z` an odd number of times, finally ending up in the hash table. In fact, it'll be the *only* key in the hash table (as the string runs from after the newline of the second part to the end of the third part, and the hash table started with just a single newline), so it'll just be printed out on its own. * **The first or third newline was deleted**. In this case, the program will be rotated such that it's the third of the newlines that's missing, effectively merging the second and third parts into a single line. The string literal accessed via `<DATA>` contains every character an even number of times, so the hash table will have its original content, a single newline, and that'll get printed. * **The second newline was deleted**. In this case, the program won't be rotated (as the first part has a valid checksum), so the second part will be moved onto the same line as the first part. `<DATA>` only starts reading from the line below `__DATA__`, so it'll only see the third part. This has more than five characters that appear an odd number of times, so it'll trigger the special case to print a newline. ## Verification One final thing that has to be checked for pretty much any radiation-hardened A Pear Tree program is whether a deletion happens to randomly cause an unwanted section of the code to checksum correctly and rotate the code into the wrong place; given that we're using 32-bit checksums, this is unlikely but not impossible. I used the following brute-force script to ensure that this doesn't happen for any deletion: ``` use 5.010; use IPC::Run qw/run/; use warnings; use strict; use Data::Dumper; $Data::Dumper::Useqq=1; $Data::Dumper::Terse=1; $Data::Dumper::Indent=0; undef $/; $| = 1; my $program = <>; for my $x (0 .. (length($program) - 1)) { my $p = $program; my $removed = substr $p, $x, 1, ""; alarm 4; say Dumper($p); run [$^X, '-M5.010', 'apeartree.pl'], '<', \$p, '>', \my $out, '2>', \my $err; if ($out ne $removed) { print "Unexpected output deleting character $x ($removed)\n"; print "Output: {{{\n$out}}}\n"; print "Errors: {{{\n$err}}}\n"; exit; } } say $program; run [$^X, '-M5.010', 'apeartree.pl'], '<', \$program, '>', \my $out, '2>', \my $err; if ($out ne '') { print "Unexpected output not mutating\n"; print "Output: {{{\n$out}}}\n"; print "Errors: {{{\n$err}}}\n"; exit; } say "All OK!"; ``` The verification script confirms that this program works correctly. [Answer] # [Stax](https://github.com/tomtheisen/stax), 11 bytes (Score of 4) ``` '''cc'~~'dd ``` [Run and debug online!](http://staxlang.xyz/index.html#c=%27%27%27cc%27%7E%7E%27dd&i=&a=1) It is my honor to have the first (chronologically) answer to this challenge with a score higher than or equal to 4. Maybe the score can be even higher though. In Stax, a string literal that is composed of a single character is written with `'`, so `'', 'c, 'd, '~` are all string literals. The corresponding commands for `c` `d` and `~` means duplicate the top of the main stack, pop the top of the main stack, and pop the top of the main stack and push to the input stack, respectively. For this challenge, input stack does not affect output and is not important, hence we can say `d` and `~` are identical. ## Explanation It is best to divide the code into several parts and consider them separately. When it is not tampered with, `'''cc` pushes a literal `'` and a literal `c` to the main stack, and duplicates the top, so the stack would be (from to bottom) `c,c,'`. When not tampered with, `'~~` pushes the literal `~` and then pops it (and push to the input stack), which is basically a no-op for the main stack. When not tampered with, `'dd` pushes the literal `d` and then pops it, another no-op for the main stack. At the end of the program, since no explicit output is done, the top of the main stack will be implicitly printed out. If the program is running as-is, the final stack is still `c,c,'` and will output `c`. If the first part becomes `''cc`, then we have a literal `'`, and two copy instructions, the final stack will be `',','`. Given that the two other parts are no-op, the result will be `'`. If the first part becomes `'''c`, the result is basically the same with the untampered one, but the `c` is not duplicated. So the stack will be `c,'`. After two no-op's the top of the stack is `c`. So we can detect radiation in the first part. The second part and the third part work in exactly the same way. I will take the third part as an example. If the third part is tampered with, then the first two parts are kept as-is and the stack before running the third part is `c,c,'` If the third part becomes `'d`, a literal `d` is pushed to the top of the main stack and nothing further is done. The top of the main stack is now `d` which will be output. If the third part becomes `dd`, two elements are popped from the main stack and now the top of the stack is `'` and is output. Hence we can detect radiation in the third part. For the same reason we can detect radiation in the second part. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), score 2, 6 bytes ``` „"""„„ ``` Prints double the removed character sometimes. Doesn't contain `'`. # How it works: ## Removing the first `„` ``` """„„ ``` [Try it online!](https://tio.run/##MzBNTDJM/f9fSUnpUcM8IPr/HwA "05AB1E – Try It Online") First, we push an empty string literal to the stack. Then we push `„„`, which is printed implicitly. ## Removing a `"` ``` „""„„ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcM8JSUgAUT//wMA "05AB1E – Try It Online") First, we push `""` to the stack with the `2-char string` instruction. Then we try to get another 2-character string, but this is aborted (I'm not exactly sure why) and the `""` is printed. ## Removing the second or third `„` ``` „"""„ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcM8JSUlIPn/PwA "05AB1E – Try It Online") First, we push `""` to the stack with the `2-char string` instruction. Then we push `„`, which is printed implicitly. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes, score 2 ``` ”””ḷḷ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw1wIerhjOxD9/w8A "Jelly – Try It Online") **With any `”` removed:** ``` ””ḷḷ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw1wgerhjOxD9/w8A) The character `”` begins a one byte character literal. This programs begins with `””` which yields the string `”`. The `ḷ` dyad takes it's left argument. The string `”` just gets passed through the two instances of `ḷ`. **With any `ḷ` removed:** ``` ”””ḷ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw1wIerhj@///AA) In this program `””` yields the character `”` then `”ḷ` yields the character `ḷ` and only this is output. --- **Other solutions** * Lots of other characters such as `a` or `o` would have worked in place of `ḷ` for this submission. * `⁾⁾⁾⁾FFF`. This works in a similar way. `⁾` is like `”` but it starts a *two* byte string literal. The "irradiated" programs output the deleted byte twice which was ruled valid in the comments. --- [Here](https://tio.run/##y0rNyan8/9/n4c41j5rWHJ1cACQP7bTWB1JhIIE9Dod2uv////9Rw1wIerhjOxABAA) is a (much less fancy) Jelly version of Magic Octopus Urn's validity checker. The left column of the output is the deleted character and the right column is the output of the resulting program. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 65 bytes, score 22 ``` \\\::\__\⅛⅛\££\→→\((\[[\‟‟\**\••\--\oo\PP\ḞḞ\↳↳\↲↲\⋏⋏\ǑǑ\FF\jj\∇∇ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJcXFxcXFw6OlxcX19cXOKFm+KFm1xcwqPCo1xc4oaS4oaSXFwoKFxcW1tcXOKAn+KAn1xcKipcXOKAouKAolxcLS1cXG9vXFxQUFxc4bie4bieXFzihrPihrNcXOKGsuKGslxc4ouP4ouPXFzHkceRXFxGRlxcampcXOKIh+KIhyIsIiIsIiJd) Based on [Weijun Zhou's Stax answer](https://codegolf.stackexchange.com/a/155997/100664). In Vyxal, `\` takes the next character as a single character. So, the bit at the start `\\\::` pushes `"\"`, pushes `":"`, then duplicates it with the operation `:`. The stack is now `["\", ":", ":"]`. If either `:` is removed, the `:` operation is not run and the stack is just `["\", ":"]`. If any `\` is removed, the stack becomes `["\","\","\"]`. The rest of the program is chunks of `\xx`, where x is some operation that effectively does nothing but remove a string from the stack. These chunks normally do nothing, as they effectively push and pop a value. If a backslash is removed, an operation that effectively pops the stack is run twice, removing the two `":"` from the stack and leaving the backslash we pushed at the start. If either x is removed, the string `"x"` is pushed to the stack and not removed. Finally, the top of the stack is implicitly output. ### Operations, and why they work For these, `x` is the value already on the stack and `y` is the value * `_` - Simply pops `y` * `⅛` - Pushes `y` to the global array. * `£` - Stores `y` to the register * `→` - Stores `y` to the empty variable * `(` - starts a for loop over `y`. As it's a 1-character string the code inside is run once * `[` - If `y` is truthy, execute the remaining code. It will always be truthy. * `‟` - Rotate `y` to the bottom of the stack. * `*` - Ring translate `x` by `y`. Since the strings share no characters, nothing happens. * `•` - Give `x` the casing of `y`. Since this occurs before anything alphabetical, nothing happens. * `-` - Remove `y` from `x` * `o` - Remove `y` from `x` * `P` - Strip `y` from the outside of `x` * `Ḟ` - Replace spaces in `x` with `y`. There are no spaces in `x`. * `↳` - Pad `x` according to `y` * `↲` - Pad `x` according to `y` * `⋏` - Center `x` according to `y` * `Ǒ` - Remove `y` from `x` until `x` doesn't change * `F` - Remove characters in `y` from `x` * `j` - Join `y` by `x`. This does nothing to a 1-character `x`. * `∇` - Rotate the top three items of the stack. Has to be at the end. ]
[Question] [ # Introduction Try to convert words to two different unicode fonts. # Challenge Your task is to transform your input string into the 𝖬𝖺𝗍𝗁 𝖲𝖺𝗇𝗌 and 𝗠𝗮𝘁𝗵 𝗦𝗮𝗻𝘀 𝗕𝗼𝗹𝗱 unicode characters. All uppercase words should become lowercase 𝗠𝗮𝘁𝗵 𝗦𝗮𝗻𝘀 𝗕𝗼𝗹𝗱 words. * For Example: `WORD` -> `𝘄𝗼𝗿𝗱` All lowercase words should become 𝖬𝖺𝗍𝗁 𝖲𝖺𝗇𝗌 words * For example: `other words` -> `𝗈𝗍𝗁𝖾𝗋 𝗐𝗈𝗋𝖽𝗌` All mixed case words should remain unchanged * For example: `Mixed Case Words` -> `Mixed Case Words` Periods and spaces should remain unchanged. Words are separated by spaces or periods * For example (highlighted things are words): > > `Hello`. `This` `is` `a` `word`. `S`.`O`. `are` `these` > > > * Inputs: A string containing letters, spaces, and periods (`[A-Za-z .]+`) * Output: The formatted string As this is a golfing challenge, the lowest number of bytes wins # Example Input and Output Input: > > This is an example STRING that c.o.U.L.d. be INPUTTED. It can CONTAIN multiple sentences. > > > Output: > > This 𝗂𝗌 𝖺𝗇 𝖾𝗑𝖺𝗆𝗉𝗅𝖾 𝘀𝘁𝗿𝗶𝗻𝗴 𝗍𝗁𝖺𝗍 𝖼.𝗈.𝘂.𝗹.𝖽. 𝖻𝖾 𝗶𝗻𝗽𝘂𝘁𝘁𝗲𝗱. It 𝖼𝖺𝗇 𝗰𝗼𝗻𝘁𝗮𝗶𝗻 𝗆𝗎𝗅𝗍𝗂𝗉𝗅𝖾 𝗌𝖾𝗇𝗍𝖾𝗇𝖼𝖾𝗌. > > > # Reference Math Sans Bold: 𝗮𝗯𝗰𝗱𝗲𝗳𝗴𝗵𝗶𝗷𝗸𝗹𝗺𝗻𝗼𝗽𝗾𝗿𝘀𝘁𝘂𝘃𝘄𝘅𝘆𝘇 (characters 120302 through 120327) Math Sans: 𝖺𝖻𝖼𝖽𝖾𝖿𝗀𝗁𝗂𝗃𝗄𝗅𝗆𝗇𝗈𝗉𝗊𝗋𝗌𝗍𝗎𝗏𝗐𝗑𝗒𝗓 (characters 120250 through 120275) [Answer] # [QuadR](https://github.com/abrudz/QuadRS), ~~45~~ 43 bytes -2 thanks to ngn. ``` \w+ ⎕UCS a+(2>≢b)×120153+84×⊃b←∪96>a←⎕UCS⍵M ``` Since TIO scrambles Unicode output from QuadR, here is a screenshot of using QuadR as an APL library in an interactive session: [![interactive session transcript](https://i.snag.gy/V9kd4v.jpg)](https://i.snag.gy/V9kd4v.jpg) --- `\w+` replace words with the result of applying the following code to them: `⍵M` the found word `⎕UCS` the **U**niversal **C**haracter **S**et code points of that `a←` store that in `a` `96>` 0 or 1 for whether 96 is greater than each of those `∪` take just the unique; `[0]` or `[1]` or `[0,1]` or `[1,0]` `b←` store that in `b` `⊃` pick the first from that `84×` multiply 84 with that `120153+` add 120153 to that `(`…`)×` multiply the following with that:  `≢b` the tally (length) of `b` (`1` if single-case, `2` if mixed-case)  `2>` 0 or 1 for whether two is greater than that (`1` if single-case, `0` if mixed-case) `a+` the original code points added to that `⎕UCS` convert the resulting code points back to characters [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~63~~ ~~57~~ 53 bytes -6 thanks to Erik the Outgolfer. -4 thanks to ngn. Anonymous tacit prefix function. ``` '\w+'⎕R{⎕UCS a+(2>≢b)×120153+84×⊃b←∪96>a←⎕UCS⍵.Match} ``` Since TIO scrambles Unicode output from Dyalog APL, here is a screenshot of the code in action: [![code in action](https://i.snag.gy/IRsVgm.jpg)](https://i.snag.gy/IRsVgm.jpg) --- `'\w+'⎕R` PCRE **R**eplace words with the result of applying the following… `{`...`}` anonymous lambda:  `⍵.Match` the found word  `⎕UCS` the **U**niversal **C**haracter **S**et code points of that  `a←` store that in `a`  `96>` 0 or 1 for whether 96 is greater than each of those  `∪` take just the unique; `[0]` or `[1]` or `[0,1]` or `[1,0]`  `b←` store that in `b`  `⊃` pick the first from that  `84×` multiply 84 with that  `120153+` add 120153 to that  `(`…`)×` multiply the following with that:   `≢b` the tally (length) of `b` (`1` if single-case, `2` if mixed-case)   `2>` 0 or 1 for whether two is greater than that (`1` if single-case, `0` if mixed-case)  `a+` the original code points added to that  `⎕UCS` convert the resulting code points back to characters [Answer] # [Clean](https://clean.cs.ru.nl), ~~268~~ ~~265~~ ~~232~~ 224 bytes As a neat bonus, this works with strings containing *any* character. [Including nulls.](https://tio.run/##bVPbbtswDH3XVxBdgMao47i7AEUR994OAYKsWJynOkAUWa61yZIn0V0M7NuXyZesLdoHXchDnkOKNpOcql2h00pyKKhQO1GU2iAsMJ2Jje@OqcLmuNJa@jHfYrBUgumUvzKC5XVODakiYZdlyQ2R7nYpy5ySAfsjgUWZ0YWjGqJ2O7Cj44/h8ZdPRyIbVsC8k88QehEj5w@5b09xFT20QD45E3amf3MD1hsOmMeShE1GfdCqCXehg3xFLmz0UCfJdjJ6NLoqr@phQmETSaCR2zae9evJCM63q32Dr6q/Ve4Q6tEGy/juhIzHQDf6iUNWKYZCKwupVocIhv@qhOGAubDQEfkg8NDCj8oiVJangBqwMgoorBdoHOkahHJOZzfk8MbZO1pV5fLzZ10ojX4SqWPVStagOE/tc0Ybvm5ffu2D0tgprEnz1s0E7xxNXyboht@KQkhqZO33Ldj/NRf0J2@1U2FLSWsnAJxa4WZJstPTYac5OmsUPJK18@x8hKDDG//orPN4BCPUe3SB1CD5ALa1IYKD2GknYbOoSkK@pUUpeRIu4u/T@dckxJxiErJAB8tgFqRBEm4cOp3fL@P49saZ0wZuUq@/zePL6TwJi0qiaEksV8gV4zY4eKnpvrt@2KAh8/aAe5O2cYHQwy@TLvrra6KGwDXfx79HVToH0o3kJNozjMdvU501cOvdynZ/WSbpo92NprPdTa1oIVhn3EuKmTZFa3S/6T8 "Clean – Try It Online") ``` import StdLib,StdInt,StdBool,Text.Unicode,Text.Unicode.UChar u=isUpper l=isAlpha $c|l c=fromInt(toInt c+120153+if(u c)84 0)=c ?[h,s:t]=[if(u h<>isLower s)($c)c\\c<-[h,s:t]] ?[h]=[$h] @s=[y\\x<-groupBy(\a b=l a&&l b)s,y<- ?x] ``` [Try it online!](https://tio.run/##bVNtb9owEP7uX3HqUEvUENq9SBUi9L0TEmLVCJ8ACeM4jTfHzmynI9J@@9jlhbWo/ZDY99zd89z5bCY5VbtMx4XkkFGhdiLLtXEwc/FEbHxcxspVy43W0o/41gVzJZiO@YERzG9TakgRCjvPc26IxN21zFNKOuyPBBYmRmdI1XUa/8BOzz@enX/5dCqSbgHMu/gMZ17IyOUi9e3ArcJF7UiHI2En@jc3YL1uh3lsuWTDXhu0qsIxtJOuyJUNF@VyuR32nowu8puyu6SwCSXQ42MJG8/65bAHl9vVvsGD6u8VLkI92WAePVyQfh/oRj9zSArFnNDKQqzViQPDfxXCcHCpsNAQ@SDciYUfhXVQWB6D0@AKo4DCeuYMkq5BKATRrsjhDdgCtarC/PRFF3Kjn0WMrFrJEhTnsX3JqMPX9cmvfVDaNQprUp11NcEHpGnLBF3xW5EJSY0s/bYF@7/mjP7ktXYsbC5piQLAqRU4S5IMBt1GszeqFDyS1PNsMEIc@iu8N2oQj7jQ6b135qhx5APY2oYQjqJWmyrgW5rlePdm0ffx9CsWQPFyBDqYB5MgDmDDYTx9nEfR/V0AY3Rhyu23aXQ9nkJWSCeqXMuV44pxGxy9lsGr1s4XNCTe3oHHUPcqHLTu10lX7faQqCLAftv496hyBBzdSE7CPUO//zYVrQ5@71a2@8sSSZ/srjee7O5KRTPBGuNRUpdok9VG8zL/AQ "Clean – Try It Online") Defines the function `@`, taking a `UString` and returning a `UString` [Answer] # C, 292 characters, 448 bytes (in UTF-8) ``` char*t;s,i,k;p(l){for(l=s=*t/96,i=k=strlen(t);i--;)t[i]/96-s&&++l;for(l=l-s&&write(1,t,k);!l&++i<k;)write(1,s?"𝖺𝖻𝖼𝖽𝖾𝖿𝗀𝗁𝗂𝗃𝗄𝗅𝗆𝗇𝗈𝗉𝗊𝗋𝗌𝗍𝗎𝗏𝗐𝗑𝗒𝗓"+t[i]*4-388:"𝗮𝗯𝗰𝗱𝗲𝗳𝗴𝗵𝗶𝗷𝗸𝗹𝗺𝗻𝗼𝗽𝗾𝗿𝘀𝘁𝘂𝘃𝘄𝘅𝘆𝘇"+t[i]*4-260,4);}f(char*s){char b[strlen(s)];for(t=b;*s;++s)*s<47?(*t=0),p(t=b),putchar(*s):(*t++=*s);*t=0;p(t=b);} ``` [Try it online!](https://tio.run/##PdDLTttAFAbgfZ5i8CKa8Q1oI0gzsRACVEVCoWqdVZSF4zrNyI6JMoNAiiK1QKH3llbC3uQVKJRLW@jllXiD8DsBLH8a2@ccz6/xrRe@Pxr5ba@nKy5NYYa8SyPWb633aORIR1fTj@ZM4YSOVL0oiKliXFgWZ6ouGihZMp83jIhP@qPsdbMnVEBnTWWGjE9FKItyyNndZ7mgXQ8PL@EK/sBf@Af/r4fJS3gF27ADu/Aa9mAf3sBbeAfv4QN8hE/wGb7AAXyFb5qRpdQL1sNisYRdkyP4DsdwAj/gFM7gHC7gJ/yC34CUCVImSJkgZYKUCVKmSJkiZYqUKVKmSJkiZYqU6f79rg/mZswC44MWHZ@vZP1sJc367VFK1hifm3KaXJfcMCTTZbkwv0B15cwws5tVsGyobI7iByVUDMPBE89a@KSDD0YiVqTjiZiyXD9HcLWo5raFJLi9mARbXqcbBeSZ@7RSfUxU21PEt9ftmr1qP7dJMyCV6pOa664s26SCEkaW1qruYqVKOhuREtmsDGIVxH4gbY3x3GB0Aw) **Unrolled:** ``` char*t; s,i,k; p(l) { for (l=s=*t/96, i=k=strlen(t); i--;) t[i]/96-s && ++l; for (l=l-s&&write(1, t, k); !l&++i<k;) write(1, s ? "𝖺𝖻𝖼𝖽𝖾𝖿𝗀𝗁𝗂𝗃𝗄𝗅𝗆𝗇𝗈𝗉𝗊𝗋𝗌𝗍𝗎𝗏𝗐𝗑𝗒𝗓"+t[i]*4-388 : "𝗮𝗯𝗰𝗱𝗲𝗳𝗴𝗵𝗶𝗷𝗸𝗹𝗺𝗻𝗼𝗽𝗾𝗿𝘀𝘁𝘂𝘃𝘄𝘅𝘆𝘇"+t[i]*4-260, 4); } f(char*s) { char b[strlen(s)]; for (t=b; *s; ++s) *s<47 ? (*t=0), p(t=b), putchar(*s) : (*t++=*s); *t = 0; p(t=b); } ``` [Answer] # Java 8, ~~221~~ ~~219~~ ~~203~~ 201 bytes ``` s->{StringBuffer r=new StringBuffer();for(String x:s.split("(?<=[\\. ])|(?=[\\. ])"))x.codePoints().forEach(c->r.appendCodePoint(c+(x.matches("[A-Z]+")?120237:x.matches("[a-z]+")?120153:0)));return r;} ``` I have to use a `StringBuffer` instead of a regular `String` to use `.appendCodePoint`, unfortunately.. **Explanation:** [Try it online.](https://tio.run/##jZJvS8MwEMbf71McfZUgDZtDhNVt6CYy0Dq0MnDbiyzNbGablCTV@qefvWbYgnujQgg5fvfc3XNkR1@or3Iud/FzzVJqDNxQIT86AEJarreUcQj3IcC91UI@XRTbLdfA0HcIBgeOVh13GUutYBCChCHUxh99HEj0UPLXgyoIB1ul20rlwBCTp8IiD43PhsvVisAaf6Jx@/QwLglTMZ8rN5xBmDj1JWUJYv5IE5o7H/Gk5YgdoZJk1LKEG@Qtz/3H9ZGHx73j7nH/dPATUf@9Rb2T/qCLMQ40t4WWoIOqDvbm8mKTOnONxxclYsjcpprhl2uKmy29GcszogpLckdsKpEkDHmL27upMxD8mqRs4hb1qnRs/sy9ESWPYUINh8W/BFEiDLhDJfCSZnnK4T66m4VXYBNqgRFFHsg1iQlsOMzC@UMUXU4JzBxyksltGJ3PQsiK1Iq91nD3QSTjhjSdq05VfwE) ``` s->{ // Method with String parameter and StringBuffer return-type StringBuffer r=new StringBuffer(); // Resulting StringBuffer for(String x:s.split("(?<=[\\. ])|(?=[\\. ])")) // Split by space or dot, and keep them as separate items, // and loop over all those substrings x.codePoints().forEach(c-> // Inner loop over the codepoints of that substring r.appendCodePoint( // Convert int to char, and append it to the result: c // The next codepoint of the substring +(x.matches("[A-Z]+")? // If the word is fully uppercase: 120237 // Add 120237 to convert it to Math Sans Bold :x.matches("[a-z]+")?// Else-if the word is fully lowercase: 120153 // Add 120153 to convert it to Math Sans : // Else (mixed case, or a dot/space) 0))); // Leave the codepoint (and thus the character) as is return r;} // Return the resulting StringBuffer ``` [Answer] # [Haskell](https://www.haskell.org/), ~~172~~ 170 bytes ``` (s#w)r=[x|all(`elem`s)w,c<-w,(x,k)<-zip r s,c==k] t[]=[] t w=filter(>[])[['A'..'Z']#w$['𝗮'..],['a'..'z']#w$['𝖺'..],w]!!0 f s|(a,b:c)<-span(>'.')s=t a++b:f c|1>0=t s ``` [Try it online!](https://tio.run/##PY1LasMwGIT3OcWfB8gmiki3ITKEthRDcEvjbCoEkVUZG8uusRRkgs/RrnqFHqCn6g1cpYvCwDDfMEwhTKW0HsfAzF3YUdYPQuvgpLSqTyZ0WG5XDgc9rsLt6lK20IHBktKKTyzjlHkDR/NSW9UFEeMhY2iHCEEviM/dgqGfz48vnzlmSFz55Z@/f/9xx6fT9SQHMwQCZxvpf0wrmiBCBIWGWhDLZbbJQQ430dpHM9aibIBCe7YH2@0bWEAOs7QoDXiJBlQv6lYrOKTPcfIAthAWJHkjR7InrwQyBXHydEzT@zsCsa/85PYxSXdxAvVZ2/K6NaqxqpHKkNn4Cw "Haskell – Try It Online") Fairly straightforward. The `#` operator takes the set `s` of charcters (upper or lower case) the word `w`, and the math sans set `r`. It returns the word in the math sans font if all the characters in the word are in `s` or the empty list otherwise. The `t` function takes a word and tries all three possiblities (all upper, all lower, or mixed), returning the first one that isn't empty. The `f` function finds the first word by using `span`, transforming it with `t` and concatenating it with the separator (either `.` or space) and recurring on the rest of the string. The alternate case is for if span can't find a separator; we just transform the string. Edit: Thanks to @Laikoni for taking off 2 bytes! I'm not used to the whole "operator that takes three arguments" thing [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 34 bytes ``` e€ØBŒg ṁǵŒl,Œuiị“¡ẓƬ“¡ẓġ“’×Ç+OỌµ€ ``` [Try it online!](https://tio.run/##y0rNyan8/z/1UdOawzOcjk5K53q4s/Fw@6GtRyfl6BydVJr5cHf3o4Y5hxY@3DX52BoY68hCIOtRw8zD0w@3a/s/3N1zaCvQgP///4dkZBYrAFFinkJqRWJuQU6qQnBIkKefu0JJRmKJQrJevl6ono9eip5CUqqCp19AaEiIq4uegidQCqjF2d8vxNHTTyG3NKckE6S3ODWvJDUvObVYDwA "Jelly – Try It Online") Full program. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 84 bytes ``` /\b[A-Z]+\b/_(`. ĵ$& )T`L`ۮ-܇ /\b[a-z]+\b/_(`. ĵ$& )T`l`ں-ۓ T`ÿ-߿`퟿- ``` [Try it online!](https://tio.run/##K0otycxLNPz/Xz8mKdpRNypWOyZJP14jQY/ryFYVNS7NkASfhNvrdO@0c4EUJOpWYSrISbi1S/f2ZK6QhMP7de/vT3g7f7/uu4aG//9DMjKLFYAoMU8htSIxtyAnVSE4JMjTz12hJCOxRCFZL18vVM9HL0VPISlVwdMvIDQkxNVFT8ETKAXU4uzvF@Lo6aeQW5pTkgnSW5yaV5Kal5xarAcA "Retina – Try It Online") Explanation: Retina is a .NET application and therefore works in UTF-16 internally. Unfortunately as the Math Sans characters aren't in the BMP I can't directly transliterate them because the number of code points differs. Worse, I can't use unpaired surrogates at all. Instead, I shift the appropriate words into characters in the range `0xFF-0x7FF` which conveniently only take two bytes to encode, plus I also prefix them with the `0x135` character. Finally I map that range onto the a range that overlaps the unpaired surrogates, creating valid BMP pairs. [Answer] # Python 3, ~~173~~ ~~122~~ 120 bytes ``` lambda s:''.join(chr(ord(c)+120153*t.islower()+120237*t.isupper())for t in re.split(r'\b(\w+)\b',s)for c in t) import re ``` -51 bytes from ShreevatsaR -2 bytes from abccd [Try it online!](https://tio.run/##Hc4xa8MwEIbhOfoVt1lqimhiSiDQwaUuHZqmYI9eZFnGKrIkTmec/HrX8XgvDx8X7zQEny/9W7M4NbadgnTOMvkXrOd6QB6w41rsD8eXw2v@RNImF2aDfEvH/LSlKcZHEn1AILAe0MgUnSWOWdPyZt6Lps2e0wb0A5BgdowBaaUL4f3MdvNgnYEaJ7Meu4jWE@@59XGidVowc9MmEpTXzxIx4IqiSmnZ3tEqGRgVDZCUT@z9@v0Bl6L@gqr4qdjF3kwHm6nLqma/k9c0KbLBSygqCbNxTv4D "Python 3 – Try It Online") Splits on word boundaries (`re.split(r'\b(\w+)\b',s)`), then maps lowercase words to 𝗅𝗈𝗐𝖾𝗋𝖼𝖺𝗌𝖾 𝗆𝖺𝗍𝗁 𝗌𝖺𝗇𝗌 (`+120153*t.islower()`), and uppercase words to 𝗯𝗼𝗹𝗱 𝗺𝗮𝘁𝗵 𝘀𝗮𝗻𝘀 (`+120237*t.isupper()`), and leaves mixed-case words alone, then `join`s the words back up. Ungolfed and un-lambda-ed: ``` def f(s): words = re.split(r'\b(\w+)\b', s) ret = '' for word in words: for char in word: if word.isupper(): ret += chr(ord(c) + 120237) elif word.islower(): ret += chr(ord(c) + 120153) else: ret += c return ret ``` [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~34~~ ~~33~~ ~~32~~ 31 bytes Includes an unprintable (charcode 153) after the last `#`. ``` rV="%b%A+%b"Èc+#x#í rVv Èc+#x# ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=clY9IiViJUErJWIiyGMrI3gj7QpyVnYgyGMrI3gjmQ==&input=IlRoaXMgaXMgYW4gZXhhbXBsZSBTVFJJTkcgdGhhdCBjLm8uVS5MLmQuIGJlIElOUFVUVEVELiBJdCBjYW4gQ09OVEFJTiBtdWx0aXBsZSBzZW50ZW5jZXMuIg==) --- ## Explanation ``` :Implicit input of string U r :Replace "%b%A+%b" :/\b[A-Z]+\b/g V= :Assign ^that to variable V È :Run each match through a function c :Map over the codepoints of the current match +#x#í : Add 120237 \n :Assign the result of that replacement to variable U rVv :Another replacement, this time with V lowercased to give us the RegEx /\b[a-z]+\b/g Èc+#x# :And, again, map over the codepoints of each match, this time adding 120153 to each ``` --- ## Original 32 Byte Japt v2 Solution ``` r/\b(\A+|\a+)\b/Èc_+#x#+#T*(X¶u ``` [Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=ci9cYihcQSt8XGErKVxiL8hjXysjeCOZKyNUKihYtnU=&input=IlRoaXMgaXMgYW4gZXhhbXBsZSBTVFJJTkcgdGhhdCBjLm8uVS5MLmQuIGJlIElOUFVUVEVELiBJdCBjYW4gQ09OVEFJTiBtdWx0aXBsZSBzZW50ZW5jZXMuIg==) ``` r :Replace /\b(\A+|\a+)\b/ :...all matches of this RegEx (\A=[A-Z], \a=[a-z]) È :Pass each match through a function, with X being the current match c_ :Pass the codepoints of X through a function + :Add to the current codepoint #x# :120153 (there's an unprintable after the second #) +#T :Plus 84 * : Multiplied by (X¶u : Is X equal to its uppercase self ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 33 bytes ``` €aγ€g£εÐ.u•1Ù„•*s.l•1Ùm•*+sÇ+çJ}J ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UdOaxHObgWT6ocXnth6eoFf6qGGR4eGZjxrmARlaxXo5EH4uiKddfLhd@/Byr1qv//9DMjKLFYAoMU8htSIxtyAnVSE4JMjTz12hJCOxRCFZL18vVM9HL0VPISlVwdMvIDQkxNVFT8ETKAXU4uzvF@Lo6aeQW5pTkgnSW5yaV5Kal5xarAcA "05AB1E – Try It Online") [Answer] # JavaScript (ES6), ~~99~~ ~~114~~ 113 bytes ``` s=>s.replace(/\b([A-Z]+|[a-z]+)\b/g,e=>e.replace(/./g,f=>String.fromCodePoint(f.charCodeAt()+120153+(f<'a')*84))) ``` (Thanks to @pfg for pointing out an important flaw in my first solution.) -1 bytes thanks to @Neil. **Snippet:** ``` let f = s=>s.replace(/\b([A-Z]+|[a-z]+)\b/g,e=>e.replace(/./g,f=>String.fromCodePoint(f.charCodeAt()+120153+(f<'a')*84))) d.innerHTML=f('This is an example STRING that c.o.U.L.d. be INPUTTED. It can CONTAIN multiple sentences.'); ``` ``` <p id="d"> ``` ]
[Question] [ A [prime gap](https://en.wikipedia.org/wiki/Prime_gap) is the difference between two consecutive primes. More specifically, if *p* and *q* are primes with *p* <*q* and *p*+1, *p*+2, ..., \_q\_−1 are not primes, the primes *p* and *q* define a gap of *n* = *q\_−\_p*. The gap is said to be **started** by *p*, and to have **length** *n*. It is known that arbitrarily large prime gaps exist. That is, given *n* there exists a prime gap of length *n* or larger. However, a prime gap of length exactly *n* may not exist (but a larger one will). # The challenge Given a positive integer `n`, output the first prime that starts a gap of length `n` or larger. As an example, for input `4` the output should be `7`, because 7 and 11 are the first consecutive primes that differ by at least 4 (the previous gaps are 1, from 2 to 3; 2, from 3 to 5; and 2, from 5 to 7). For input `3` the answer should also be `7` (there are no gaps of length 3). # Additional rules * The algorithm should theoretically work for arbitrarily high `n`. In practice, it is acceptable if the program is limited by time, memory or data-type size. * Input and output can be taken by any [reasonable means](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). * [Programs or functions](http://meta.codegolf.stackexchange.com/a/2422/36398) are allowed, in any [programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073). [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * Shortest code in bytes wins. # Test cases ``` Input -> Output 1 2 2 3 3 7 4 7 6 23 10 113 16 523 17 523 18 523 30 1327 50 19609 100 370261 200 20831323 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10, 9, 8~~ 10 bytes ``` Æn_$:ð1#»2 ``` [Try it online!](https://tio.run/##y0rNyan8//9wW168itXhDYbKh3Yb/f//3wwA "Jelly – Try It Online") Two bytes saved thanks to @Dennis! (and then added back again due to edge-cases) Explanation: ``` Æn # The next prime after 'P' _$ # Minus 'P' : # Divided by 'N' # # This will give a falsy value unless the distance to the next prime is >= N # ð # Treat all of that as a single dyad (fucntion with two arguments). # We'll call it D(P, N) # 1# # Find the first 'P' where D(P, input()) is truthy »2 # Return the maximum of that result and 2 ``` [Answer] # Mathematica, 30 bytes ``` 2//.x_ /;NextPrime@x-x<#:>x+1& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvvfSF9fryJeQd/aL7WiJKAoMzfVoUK3wkbZyq5C21DtP1Akr0TBIS3a0CD2PwA "Mathics – Try It Online") # Mathematica, 35 bytes ``` (t=2;While[NextPrime@t-t<#,t++];t)& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvtfo8TWyDo8IzMnNdovtaIkoCgzN9WhRLfERlmnRFs71rpEU@0/UDCvRMEhLdrYIPY/AA "Mathics – Try It Online") # Mathematica, 77 bytes ``` Prime@Min@Position[s=Differences@Prime@Range[(r=#)^3+1],#&@@Select[s,#>=r&]]& ``` [Answer] # [Haskell](https://www.haskell.org/), ~~106 102 93 77 73~~ 72 bytes This generates an infinite list of primes first, then looks for the prime gaps. The prime list was taken from [here](https://wiki.haskell.org/Prime_numbers_miscellaneous#One-liners). It can probably be shortened, but I haven't figured out how yet:) Thanks to @BruceForte for -4 bytes and @Zgrab for -1 byte! ``` f n=[x|(y,x)<-zip=<<tail$[n|n<-[2..],all((>0).rem n)[2..n-1]],y-x>=n]!!0 ``` [Try it online!](https://tio.run/##FcoxCsMgFADQq/xABgUV7ay5iDj8QVupfkQdkpK7W7I@3gfHN5ayVgJy/rzZJU5u5S83Z@3EXHZPN1npX0oFgaUwdmiueqxA/EGSJgRxyfNwFLZNr4qZwEHrmSbsULFBAm@UMjqAlJByHxOMfkaNb2xj/QE "Haskell – Try It Online") [Answer] # [Gaia](https://github.com/splcurran/Gaia), 6 bytes ``` zṅọ⊃∆ṇ ``` This is *extremely* inefficient (the `16` test case took over an hour to compute on my machine). [Try it online!](https://tio.run/##S0/MTPz/v@rhztaHu3sfdTU/6mh7uLP9/39DAwA "Gaia – Try It Online") ### Explanation The sequence seems to have the property that **a(n) <= 2^n**. ``` z Push 2^input. ṅ Get the first 2^input prime numbers. ọ Get the deltas of the list. ⊃∆ Find the index of the first that is greater than or equal to the input. ṇ Push the index-th prime number. ``` [Answer] # Pyth - 14 bytes It filters from [1, inf), filtering by primality(`P_`) and that the next prime filtered from (n, inf), has a different >= to the input. ``` f&P_T<tQ-fP_Yh ``` [Test Suite](http://pyth.herokuapp.com/?code=f%26P_T%3CtQ-fP_Yh&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A6%0A10%0A16%0A17%0A18%0A30&debug=0). [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~97~~ ~~96~~ 91 bytes ``` param($n)for($a=$b=2){for(;'1'*++$b-match'^(?!(..+)\1+$)..'){if($b-$a-ge$n){$a;exit}$a=$b}} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVPMy2/SEMl0VYlydZIsxrEsVY3VNfS1lZJ0s1NLEnOUI/TsFfU0NPT1owx1FbR1NNT16zOTNMASqsk6qanAk2oVkm0Tq3ILKkFG1Nb@///f2MDAA "PowerShell – Try It Online") Takes input `$n`, sets `$a` and `$b` equal to `2`, then enters an infinite `for` loop. Inside, we loop up on `$b` until we [get to the next prime](http://codegolf.stackexchange.com/a/57636/42963). Then we check if `$b-$a` (i.e., the gap) is `-g`reaterthanor`e`qual to `$n`. If it is, we output `$a` and `exit`. Otherwise we set `$a` to be `$b` and increment `$b` and start our next search. Warning: This is *slow* for large input. In fact, it can't complete the `50` or higher tests within the 60s timeout on TIO. Oh well. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~13~~ ~~11~~ 10 bytes ``` ´ȯ!V≥⁰Ẋ-İp ``` [Try it online!](https://tio.run/##AR4A4f9odXNr///CtMivIVbiiaXigbDhuootxLBw////MTA "Husk – Try It Online") ``` ´ İp -- with the primes ȯ! -- get the value at position Ẋ- -- where the difference of the current and next prime V≥⁰ -- is greater or equal than the input N ``` [Answer] # Mathematica, 39 bytes ``` (For[i=2;p=NextPrime,i+#>p@i,i=p@i];i)& (* or *) (For[i=1;p=Prime,p@i+++#>p@i,];p[i-1])& ``` ### 33 byte version (not valid because it only goes up to the 65535th prime) ``` p=NextPrime;2//.i_/;p@i-i<#:>p@i& ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~96~~ 88 bytes ***- 8 bytes Thanks to @Maltysen*** ``` n,p,r=input(),3,[2] while p-r[-1]<n:r+=[p]*all(p%i for i in range(2,p));p+=1 print r[-1] ``` [Try it online!](https://tio.run/##Lc1BCsIwEAXQfU8xG0lrU2hSW6Wak4QsSo02EKZDqKinj6O4eIvP8P/Qe1tW1Hler94IITJKkskEpMdWVrKTVrviuYTogZpkG@UuOKbaWHL7KcaSdgFua4IAASFNePelllRVZ6qNKigF3OBXyzz@H1Kjf/kZvi@zAig069iBDUy1bGBHduIb5779AA "Python 2 – Try It Online") [Answer] # [Perl 6](http://perl6.org/), 63 bytes ``` ->\d{(grep &is-prime,^∞).rotor(2=>-1).first({-d>=[-] $_})[0]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtf1y4mpVojvSi1QEEts1i3oCgzN1Un7lHHPE29ovyS/CINI1s7XUNNvbTMouISjWrdFDvbaN1YBZX4Ws1og9ja/9YKxYmVCkoq8Qq2dgrVaSAJJYW0/CIFQz09IwPr/wA "Perl 6 – Try It Online") [Answer] ## Mathematica, 37 bytes ``` gNestWhile[p=NextPrime,2,p@#-#<g&] ``` `Function` with first argument `g`. Starting with `2`, applies the function `p=NextPrime` repeatedly as long as `p@#-#<g&` gives `True` (the gap between the current prime and the next prime is less than `g`). [Answer] # R + gmp, 55 bytes Makes use of the nextprime function from the gmp library ``` s=2;n=scan();while((x=gmp::nextprime(s))-s<n)s=x;cat(s) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 61 bytes ``` ->g{*r,f=2,3;f+=1while r.find{|n|f%n<1}||r<<f&&g>f-z=r[-2];z} ``` [Try it online!](https://tio.run/##BcHRCoMgFADQX/FlsZVKNnpK@xHxYbHdCpbEhdDy@u12Dh7TWYIpYpxTjRxMx98DNEaFZf3/GEpY/TeRJ3h4rTIRag1VNY8gLoNWdG64cnkqKfv2JbfPnijSzmzkLNjoXC43 "Ruby – Try It Online") [Answer] ## C = ~~141~~ 109 bytes ; C++, D = 141 bytes ; C#, Java = 143 bytes **WARNING** : LOW PERFORMANCE ALGORITHM This code was not able to calculate the prime gap for `g(200)` within 10 minutes. For `g(100)`, it needed 10 seconds ( C++ version ) C++ and D version : ``` int p(int d){for(int i=2;i<=d/2;++i){if(!(d%i))return 0;}return 1;}int g(int d){int f=2,n=3;while(n-f<d){f=n;do{++n;}while(!p(n));}return f;} ``` C# and Java version : ``` int p(int d){for(int i=2;i<=d/2;++i){if(d%i==0)return 0;}return 1;}int g(int d){int f=2,n=3;while(n-f<d){f=n;do{++n;}while(p(n)==0);}return f;} ``` C version, -32 bytes thanks to ceilingcat : ``` i;p(d){for(i=2;d/2/i;)if(!(d%i++))return 0;return 1;}f;n;g(d){for(f=2,n=3;n-f<d;)for(f=n;!p(++n););return f;} ``` Differences between the C#/Java and C/C++/D version : `!p(n)` <==> `p(n)==0` [Answer] # D, ~~127~~ ~~125~~ 122 bytes WARNING: LOW PERFORMANCE ALGORITHM!! ``` T p(T)(T d){T r;for(T i=2;i<=d/2;)r=d%i++<1||r;return r;}T g(T)(T d){T f=2,n=3;while(n-f<d){f=n;while(p(++n)){}}return f;} ``` [Try it online!](https://tio.run/##TYwxDsMgEARr8wqaSJxIHIWUZ37BByJhnJMcsC4kLmzeTihcpNhiR7Pra3VyUQ6Ukx42JxlD4lbIGqTB@qtBYOtPpPVw23dGHvOHY/OKk9PfMFhzjvaO65PmUcVLGBoONh5gUVpHgK2U4yBgEd9EXr4eFBXITYqOXkviLN/Z9y2UUHQrUx7nqJSBfgIUpdYf) # How? HatsuPointerKun again, but I'll do the D specific sorcery. * Template system can infer types `T p(T)(T d)`, and is shorter than C++ * `r=d%i++<1||r`, D specific shenanigans, might work in C/C++, but I don't know. * `p(++n)`, same as above, not sure if it works in C/C++ * `while(p(++n)){}`, here one sees why D is bad at golfing, one can't use `;` as an empty statement. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~41~~ 37 bytes ``` {+(1...(^$_+*)>>.is-prime eqv!<<^$_)} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WlvDUE9PTyNOJV5bS9POTi@zWLegKDM3VSG1sEzRxgYorln7vzixUiFNA8hUSMsvUjDUMdIx1jHRMdMxNNAxBJLmOoYWOsYG/wE "Perl 6 – Try It Online") ### Explanation ``` { } # Block taking n as $_ 1... # Sequence 1,2,... until (^$_+*) # Range [i,i+n) >>.is-prime # is-prime for each eqv!<<^$_ # Equals (True,False,False,False,...)? +( ) # Length of sequence ``` [Answer] # [Haskell](https://www.haskell.org/), 64 bytes ``` f n=until(\p->and[any((<1).mod k)[2..k-1]|k<-[p+1..p+n-1]])(+1)2 ``` [Try it online!](https://tio.run/##HcdBDsIgEADAr@wRghAXTU@tH6EcSCtKoOvGtgcT3y6Kl0nmHtZ8LaXWCDTstKUiRtaXQLML9BKiR2mWxwxZOmtM1ujfudeOFRrDin73UiiUti4hEQzAz0QbuAh4gAi2cWqcG10Dj387Xz9TLOG2Vj0xfwE "Haskell – Try It Online") Count up from `2` looking for a `p` such that `[p+1..p+n-1]` are all composite. `p` itself will always be prime: otherwise `[p..p+n-1]` is a larger prime gap and we'd have returned `p-1`. [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 28 bytes ``` {~µs||~s-r>=:|_Xr\r=s]]s=s+1 ``` ## Explanation ``` { DO ~µs|| IF s is prime THEN (note, s starts as 3) ~s-r>=: IF the gap between s (current prime) and r (prev prime) is big enough |_Xr THEN QUIT, printing prev prime r \r=s ELSE (gap too small, but s is prime), set r to prime s ]] END IF x2, leaving us in the WHILE s=s+1 increment s, retest for primality ... ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞<ØD¥I@Ïн ``` [Try it online](https://tio.run/##yy9OTMpM/f//Ucc8m8MzXA4t9XQ43H9h7///pgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKS/f9HHfNsDs9wObS00uFw/4W9/3X@RxvqGOkY65jomOkYGugYAklzHUMLHWMDHVODWAA). (Test Suite doesn't contain the last two test cases, because TIO times out for those.) Since [the other question is closed as a dupe of this one](https://codegolf.stackexchange.com/q/179017/52210), I'm posting [my answer](https://codegolf.stackexchange.com/a/179027/52210) here as well. **Explanation:** ``` ∞ # Get an infinite list in the range [1, ...] < # Decrease it by one to make it in the range [0, ...] Ø # Get for each the (0-indexed) n'th prime: [2,3,5,7,11,...] D # Duplicate this list of primes ¥ # Get all deltas (difference between each pair): [1,2,2,4,2,...] I@ # Check for each if they are larger than or equal to the input # i.e. 4 → [0,0,0,1,0,1,0,1,1,0,...] Ï # Only keep the truthy values of the prime-list # → [23,31,47,53,61,...] н # And keep only the first item (which is output implicitly) # → 23 ``` [Answer] # Java 8, ~~99~~ 92 bytes ``` n->{int a=2,b=3,f,k;for(;b-a<n;)for(f=0,a=b;f<2;)for(f=++b,k=2;k<f;)f=f%k++<1?0:f;return a;} ``` [Try it online.](https://tio.run/##NVBLboMwFNznFE@RIoH8QDY0H8U4PUGzyTLKwhBcORATgUlVIbY9QI/Yi1A7TTejN6OnmdFc5F1Gl3M1FbXsOniT2gwzAG1s2SpZlLD39CFAEXg0IXfKOHPQWWl1AXswIGAy0W7wD1IkmIsUFVZcNW3A80hmhof@VoKiFDlXWfIvEJJjJRJeZcpJQi0qQjL2SreKt6XtWwOSjxP3ebc@r13eM/be6DNcXeHgYFtt3o8nkOFfW@/sq2jYgik/fPvjaWCYYIovuMQVrnGDjCJbIVsj22BKcekopWP4cAA4fHa2vMZNb@Obs7e1CTSZw8/XN8yJid0Y4XOJcfoF) (Largest test case is excluded, because it times out in TIO.) **Explanation:** ``` n->{ // Method with integer as both parameter and return-type int a=2,b=3, // Prime-pair `a,b`, starting at 2,3 f, // Prime-checker flag `f`, starting uninitialized k; // Temp integer, starting uninitialized for(;b-a // Loop as long as the difference between the current pair of primes <n;) // is smaller than the input for(f=0, // (Re)set the prime-checker flag to 0 a=b; // Replace `a` with `b`, since we're about to search for the next prime-pair f<2;) // Inner loop as long as the prime-checker flag is still 0 (or 1) // (which means the new `b` is not a prime) for(f=++b, // Increase `b` by 1 first, and set this value to the prime-checker flag k=2; // Set `k` to 2 k<f;) // Inner loop as long as `k` is still smaller than the prime-checker flag f= // Change the prime-checker flag to: f%k++<1? // If the prime-checker flag is divisible by `k` 0 // Set the prime-checker flag to 0 : // Else: f; // Leave it unchanged // (If any integer `k` in the range [2, `b`) can evenly divide `b`, // the prime-checker flag becomes 0 and the loop stops) return a;} // And finally after all the nested loops, return `a` as result ``` [Answer] # [Tidy](https://github.com/ConorOBrien-Foxx/Tidy), 33 bytes ``` {x:({v:⊟v<=-x}↦primes+2)@0@0} ``` [Try it online!](https://tio.run/##K8lMqfyfpmBl@7@6wkqjuszqUdf8Mhtb3YraR23LCooyc1OLtY00HQwcDGr/lyQD1SkkaxjqGOkY65jomOkYGugYAklzHUMLHWMDHVMg18BAk4urWgGolEsBCMqLMktSc/I0kvWUFHR17RSU9NI0kjU1uWoV8vMUSpL/AwA "Tidy – Try It Online") Or, 28 chars/34 bytes: `{x:({v:⊟v≤-x}↦primes+2)@0@0}` I'll explain this using an equivvalent, ASCII equivalent: ``` {x:({v:(-)over v<=-x}from primes+2)@0@0} {x: } lambda w/ parameter `x` primes+2 overlapping pairs of primes [[2, 3], [3, 5], [5, 7], ...] {v: }from select prime pairs `v = [a, b]`... (-)over v ...where `a` - `b`... <=-x is <= `x` ( )@0@0 select the first element of the first pair ``` [Answer] # APL(NARS), 36 char, 72 bytes ``` ∇r←h w;k r←2 →0×⍳w≤r-⍨k←1πr⋄r←k⋄→2 ∇ ``` 1π is the function "next prime"; test: ``` h¨1 2 3 4 6 10 16 17 18 30 50 100 200 2 3 7 7 23 113 523 523 523 1327 19609 370261 20831323 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` @§XnÈj}aX+j}a2 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QKdYbshqfWFYK2p9YTI&input=OA) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QKdYbshqfWFYK2p9YTI&input=WzEgMiAzIDQgNiAxMCAxNiAxNyAxOCAzMCA1MCAxMDBdLW0) (except `200` - seriously, don't even try it! If you want to verify that `200` returns the correct result, you can increase the starting value of `2` at the end to something closer to the expected output.) ``` @§XnÈj}aX+j}a2 :Implicit input of integer U @ :Function taking an integer X as argument § : Is U <= ... Xn : Subtract X from È : Function taking an integer as input j : Is prime? } : End function a : Get the first integer that returns true when passed through that function starting at X+j : X plus is X prime } :End function a2 :Get the first integer that returns true when passed through that function starting at 2 ``` ]
[Question] [ Inspired by [this challenge](https://codegolf.stackexchange.com/questions/109117/unscramble-those-case-very-sensitive-strings?atw=1) (or, more specifically, by misreading it), I've come up with the following challenge: Given an input string S, reverse the order of all uppercase characters, and all lowercase characters. Leave all non-letter characters in place. For instance: [![Hello, World!](https://i.stack.imgur.com/IirFB.jpg)](https://i.stack.imgur.com/IirFB.jpg) Note that the uppercase `W` (the first uppercase letter) was replaced with `H` (the last). Same goes for the lowercase letters: 'd' (the first) is swapped with `e` (the last), `l` (second) gets replaced with `l` (pen-ultimate) ... All the non-letter characters are left in place. ## Input * Input is a string with only ASCII characters in the range 32-126. * Input is guaranteed to be at least 1 character long, and won't exceed your language's limit. ## Output * That same string, with the characters swapped as described. ## Additional rules * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden * Answer must be a full program or a function, not a snippet or a REPL-entry. * [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes wins. ## Test cases ``` A A Ok Ok OK KO Hello, World! Wdlro, Holle! 0123456789 0123456789 The quick brown Fox jumps over the lazy doge Feg odyza lehtr Tev ospmu jxon wor bkci uqeh odd ddo racecar racecar EtOn Em OsN R AaToNsIsIhT!!1! ThIs Is NoT A RaNsOmEnOtE!!1! ``` [Answer] # [Retina](https://github.com/m-ender/retina), 19 bytes Retina doesn't have a direct way to reverse a string, but we can do it by exploiting the sorting stage: ``` O^#`[a-z] O^#`[A-Z] ``` Sort (`O`), reading them as numbers (`#`), and then reverse the ordering (`^`), of all the strings matching the given regex (lowercase letters for the first line, and uppercase letters for the second). This works because when we try to read strings without numeric characters as numbers they get treated as `0`, so all the characters have the same value for sorting. Since sorting is stable they are left in the same order, and reversing them returns the original string reversed. [Try it online!](https://tio.run/nexus/retina#HcnLCoJAFADQ/f2KO0TQIiF7t3Rh5caBGAgKxckZshq9NaM9/HmLdgdOf7DJOp72sqP02gT@CrxD0nUBbLUxNMQ9WaMYwsgfT6az@WK5AlFofDSX/IYnS68K1/TGa1PeHdJTW6x/bWT7QUVnDaQUWJnrXFoIa15hWCJ3Me4wkIJiF7moEIz57As "Retina – TIO Nexus") [Answer] # [Perl](https://www.perl.org/), 45 bytes 44 bytes of code + `-p` flag. ``` for$c(u,l){@T=/\p{L$c}/g;s/\p{L$c}/pop@T/ge} ``` [Try it online!](https://tio.run/nexus/perl#U1YsSC3KUdAt@J@WX6SSrFGqk6NZ7RBiqx9TUO2jklyrn25dDGcX5Bc4hOinp9b@/@9a4p@n4Jqr4F/spxCk4JgYku9X7FnsmRGiqGioCAA "Perl – TIO Nexus") Unicode characters classes `\p{Lu}` and `\p{Ll}` matches respectively uppercase and lowercase letters. So `/\p{L$c}/` will return the list of all upper (or lower) case letters (and store it inside `@T`). And then, the regex `s/\p{$c}/pop@T/ge` will replace each (upper, then lower case) letter by the last letter of `@T` while removing it from `@T`. [Answer] ## JavaScript (ES6), ~~74~~ ~~73~~ ~~71~~ 70 bytes ``` f= s=>(g=r=>s=s.replace(r,_=>a.pop(),a=s.match(r)))(/[A-Z]/g,g(/[a-z]/g)) ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o> ``` Edit: Saved 1 byte thanks to @Arnauld. [Answer] # [MATL](https://esolangs.org/wiki/MATL), 14 bytes ``` 2:"t@Y2myy)Pw( ``` [**Try it at MATL Online**](https://matl.io/?code=2%3A%22t%40Y2myy%29Pw%28&inputs=%27Hello+World%21%27&version=19.7.4) **Explanation** ``` % Impicitly grab input as a string 2: % Push the array [1, 2] to the stack " % For each value in this array t % Duplicate the top element of the stack (S) @ % Get the current loop index Y2 % Load the predefined literal 1Y2 ('ABC...Z') on the first loop % and the predefined literal 2Y2 ('abc...z') on the second loop (M) m % Create a logical array the length of S that is TRUE when a character is in the % array M and FALSE otherwise (B) yy % Make a copy of both S and B ) % Grab just the letters of S that were in M using B as an index P % Reverse this array w % Flip the top two stack elements ( % Assign them back into the string % Implicit end of for loop and implicit display ``` [Answer] ## JavaScript (ES6), 92 bytes ``` s=>(F=(r,s)=>s.replace(r,([x],a,y)=>y+F(r,a)+x))(/[a-z](.*)([a-z])/,F(/[A-Z](.*)([A-Z])/,s)) ``` There has *got* to be a way to take advantage of the similarity between the regexes... ### Test snippet ``` let f = s=>(F=(r,s)=>s.replace(r,([x],a,y)=>y+F(r,a)+x))(/[a-z](.*)([a-z])/,F(/[A-Z](.*)([A-Z])/,s)) ``` ``` <input style="width:500px" value="Wdlro, Holle!" oninput="O.value=f(this.value)"><br> <input style="width:500px" value="Hello, World!" id=O disabled> ``` [Answer] # [Perl 6](http://perl6.org/), ~~75~~ 69 bytes ``` {my @a=.comb;@(grep $_,@a).&{@$_=[R,] $_} for /<:Lu>/,/<:Ll>/;[~] @a} ``` ### How it works 1. `my @a=.comb;` Split the string into characters, and store them in an array. 2. `for /<:Lu>/,/<:Ll>/` For two regexes matching upper and lower-case letters, respectively... * `@(grep $_,@a)` Get a slice of all array entries matching the regex. * `.&{@$_=[R,] $_}` Assign the reverse of the slice to itself. 3. `[~] @a` Concatenate the modified array to form a string again, and return it. --- *-6 bytes by stealing the idea to use Unicode classes instead of character ranges, from @Dada's solution.* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` nŒlT,Ṛ$yJịŒsµ⁺ ``` [Try it online!](https://tio.run/nexus/jelly#@593dFJOiM7DnbNUKr0e7u4@Oqn40NZHjbv@P9y95XD7o6Y1kf//O3L5Z3P5e3N5pObk5OsohOcX5aQochkYGhmbmJqZW1hyhWSkKhSWZiZnKyQV5ZfnKbjlVyhkleYWFCvkl6UWKZQApXMSqyoVUvLTU7nyU1K4ihKTU5MTi7hcS/zzFFxzFfyL/RSCFBwTQ/L9ij2LPTNCFBUNFQE "Jelly – TIO Nexus") ### How it works ``` nŒlT,Ṛ$yJịŒsµ⁺ Main link. Argument: s (string) Œl Convert to lowercase. n Test for inequality. T Truth; yield all indices of 1's. ,Ṛ$ Pair with its reverse. Yields [A, B] (pair of lists). J Indices; yield I := [1, ..., len(s)]. y Translate; replace the integers of I that occur in A with the corresponding integers in B. Œs Swapcase; yield s with swapped case. ị Use the translated index list to index into s with swapped case. µ Combine all links to the left into a chain. ⁺ Duplicate the chain, executing it twice. ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) + Unix utilities, ~~122~~ 121 bytes ``` f()(p=[^$1* v="\)\([$1\)\(" for((n=99;n;n--)){ q="$q;s/^\($p$v.*$v$p\)$/\1\4\3\2\5/" p=[^$1*[$1$p } sed $q) f a-z]|f A-Z] ``` [Try it online!](https://tio.run/nexus/bash#Lcy7DoIwFIDhvU9x0pyhJakELwMhDC4@gZMcSFCKd1pAqqI@O2Li9A9/8g2lkMLGSYaBx1zMSZJIMPiFs9I0QlRxGEZVVCkl5YvVMcc6av2MBFp0Ew8dWpLoU0BzmtGUFj5nf3CE0LIPa3UBWEtWQq769F3CUm3SYVgfNNTdcXeGbWPuFazMA07d1bZgnG7gNu5L3j@hMHv9BQ "Bash – TIO Nexus") Not really very short; maybe someone can golf it further. Input on stdin, output on stdout. This will work correctly on inputs of less than 200 characters. (Actually it correctly handles any string with fewer than 200 lower-case letters and fewer than 200 upper-case letters.) If you increase the 99 in the code to 102 (at the cost of one additional byte), it will handle strings up to 205 characters. However, you can't increase the 99 in the code beyond 102 since you'll then exceed sed's maximum argument length. Here's a version without any particular input size limitation, but the count is a little longer, 137 bytes. (This longer version writes to an auxiliary file named t.) ``` f()(p=[^$1* v="\)\([$1\)\(" for((n=`wc -c<t`;n;n--)){ sed -i "s/^\($p$v.*$v$p\)$/\1\4\3\2\5/" t p=[^$1*[$1$p }) cat>t f a-z] f A-Z] cat t ``` Test runs: ``` for x in A Ok OK 'Hello, World!' 0123456789 'The quick brown Fox jumps over the lazy doge' odd racecar 'EtOn Em OsN R AaToNsIsIhT!!1!' do echo "$x" ./swapping3 <<<"$x" echo done A A Ok Ok OK KO Hello, World! Wdlro, Holle! 0123456789 0123456789 The quick brown Fox jumps over the lazy doge Feg odyza lehtr Tev ospmu jxon wor bkci uqeh odd ddo racecar racecar EtOn Em OsN R AaToNsIsIhT!!1! ThIs Is NoT A RaNsOmEnOtE!!1! ``` [Answer] # [Python 2](https://docs.python.org/2/), 115 bytes ``` s=input();u=str.isupper exec"r='';i=0\nfor c in s:r+=c[u(c):]or filter(u,s)[~i];i+=u(c)\ns=r.swapcase();"*2 print s ``` [Try it online!](https://tio.run/nexus/python2#FY3NbsIwEITveYpNLk4AIaA/FCIfOFAVVSJSFakH4GAcU1yC7e7ahfbQV0/N5dPOzmhGXZUEzLKsI66NCz4vysDJ41BTcE5homIiQ85Yqfloaw4WQYI2QHPsc7kJuSzmu/g86NYrzMOAis2f3pW6z2/e1hDHIV2Ek4JUbM96k8ShNh6oi7u9WccWLGHV6YbXiBfVtnYA7xbbJo16NJ7c3T88Tp9mUdRHBV9ByxPs0V4MPNsrfIazI7DfCsFHuxW/P9DYDxXjtmkiUUglBcZr6SsDyzNUtIY3WIjarmlFq2OdpuOU/QM "Python 2 – TIO Nexus") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 271 bytes ``` s->new String(new Error(){char[]o=s.toCharArray();char c;int b;{while(b++<2)for(int l=0,r=o.length;l<r;l++){for(--r;r>l&&f(r);r--);for(;l<r&&f(l);l++);if(l<r){o[l]=o[r];o[r]=c;}}}boolean f(int i){c=o[i];return b>1?!Character.isUpperCase(c):!Character.isLowerCase(c);}}.o) ``` [Try it online!](https://tio.run/nexus/java-openjdk#VVCxasMwEN39FcoSJFyLtmMUp5QQ6NBOoXQwHmRFiVXOljnJCcH4213JSQu9QTree3f3eKbpLHryLc@S994Af0WUVyeSpOsrMIookM6RD2laMiQJCXUnnJc@fGdrDqQJNN17NO2pKInEk2NBTe51W8mdRy0bOrO8kR2dXLZp9YXcBmlsd4gWKRtULbEobe64t9vQzysoExEnSpjWk0oMl9qAplWarp/ZMcxFGPLHB8wtB92efC1gjQLSlA2RzzIUuIHl8kiRCcwyJiIcRREDNkuFCe0a2WALKHNbYCnikysxjmNlLWjZkuN8zASnQWFKgdr32JJq8/SyiIal8hq5cZ9dp3ErnaaKrf4x7/byx4TN3LLpNzDGg62dVDXdX53XDbe9X626kJKHlok52DEZp@lNA1jyZREOix8 "Java (OpenJDK 8) – TIO Nexus") [Answer] # [R](https://www.r-project.org/), 107 bytes ``` u=utf8ToInt(scan(,''));for(i in c(65,97)){l=which(u%in%i:(i+25));u[l]=u[rev(l)]};cat(intToUtf8(u,T),sep="") ``` Adapted from my response to the linked challenge. This is considerably easier than just swapping pairs. I wonder if I could get sub 100 with some golfs... [Try it online!](https://tio.run/##Dcy7DsIgFADQX7khMb1EJpP6alhN3HFqOlSkgiJUCq2P@O3Y/eSEnBNPsdsKf3QRB9k6ZEVBadX5gAaMA4nrku02lH4tn7SRGtPCuIXZo1muylmm2jY81UGNaGnzq2Qb0bgo/Gl@MTFB2aB6TgjN5KCu4C/vTwtW6RhAqBH80D8S3F7eweQDnO/SQHoqTfIf "R – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 2FÐlø€Ë≠āsƶ0K‡<è.š ``` I/O as a list of characters. Based on [my 05AB1E answer in the related challenge](https://codegolf.stackexchange.com/a/206284/52210). [Try it online](https://tio.run/##yy9OTMpM/f/fyO3whJzDOx41rTnc/ahzwZHG4mPbDLwPNz1qWGhzeIXe0YX//0cruSrpKJUAsT8Q5wGxAhCDxHKhbJB4MRD7QflBUNoRiBOBOASI86HyIHWeSHQGVF4Rig3BdCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TpuSZV1BaYqWgoGRfqcOl5F9aAuYCecH/jdwOT8g5vONR05rD3Y86FxxpLD62zcD7cNOjhoU2h1foHV34v9ZL59A2@/@OXP7ZXP7eXB6pOTn5Ogrh@UU5KYpcBoZGxiamZuYWllwhGakKhaWZydkKSUX55XkKbvkVClmluQXFCvllqUUKJUDpnMSqSoWU/PRUrvyUFK6ixOTU5MQiLtcS/zwF11wF/2I/hSAFx8SQfL9iz2LPjBBFRUPF/7q6efm6II0A). **Explanation:** ``` 2F # Loop 2 times: Ð # Triplicate the current character-list # (which will use the implicit input-list in the first iteration) l # Lowercase all letters of the top copy ø # Zip/transpose the top two lists; pairing them together, and swapping # rows/columns €Ë≠ # Check for each pair whether they're NOT the same # (so uppercase characters that have now become lowercase) ā # Push a list in the range [1, length] (without popping) s # Swap so the mapped list is at the top again ƶ # Multiply each 1/0 by its 1-based index 0K # Remove all 0s  # Bifurcate it (short for Duplicate & Reverse copy) ‡ # Transliterate the indices with the reversed indices in [1, length] < # Decrease each by 1 (because 05AB1E uses 0-based indexing) è # Index them into the current character-list .š # And swap all cases (lowercase to uppercase, and vice-versa) # (after the loop, the resulting character-list is output implicitly) ``` ]
[Question] [ # Background LISP programmers have taken over the world! Parentheses have been declared as sacred characters, and from now on, they can only be used in LISP programs. It has been decided that parentheses in literary works shall be replaced by footnotes, and it's your job to automate this for simplified Markdown text. # Input Your input is a single string containing alphabetic ASCII characters, spaces, and the special characters `,.!?()`. It will not contain newlines or digits. The parentheses will be correctly matched. # Output You shall convert each matched pair of parentheses in the input string into a footnote. This happens as follows: 1. Replace the first matching pair of parentheses and the substring between them by a running number that starts from `1`, wrapped between the Markdown tags `<sup>` and `</sup>`. 2. Append to the end of the string * two newlines, * the Markdown tag `<sub>`, * the number from step 1, * a space, * the substring between the parentheses, and * the closing tag `</sub>`, in this order. 3. If there are still parentheses left in the string, go to step 1. Your output is the resulting string, possibly with a trailing newline. You don't have to implement this exact algorithm, as long as your output is correct. Note that there may be nested parentheses; in that case, we'll have footnotes that contain references to other footnotes. The substring between parentheses may also be empty. See the test cases below for examples. # Rules and Scoring Your can write either a full program or a function. The lowest byte count wins, and standard loopholes are disallowed. If your language does not natively support decimal numbers (*cough* Retina *cough*), you may give the footnote numbers in another base, including binary or unary; however, using unary numbers imposes a **penalty of +20%**. # Test Cases Input: ``` This input contains no parentheses. ``` Output: ``` This input contains no parentheses. ``` Input: ``` This has (some) parentheses (but not so many). ``` Output: ``` This has <sup>1</sup> parentheses <sup>2</sup>. <sub>1 some</sub> <sub>2 but not so many</sub> ``` Input: ``` This has (nested (deeply (or highly?) nested)) parentheses (and several groups). ``` Output: ``` This has <sup>1</sup> parentheses <sup>2</sup>. <sub>1 nested <sup>3</sup></sub> <sub>2 and several groups</sub> <sub>3 deeply <sup>4</sup> nested</sub> <sub>4 or highly?</sub> ``` Input: ``` Hmm()(()(,)) a()((trt)(v( (((((wut)))))(X)(Y)(Z) )!?!?!?!))oooooooo(oooo)oooo ``` Output: ``` Hmm<sup>1</sup><sup>2</sup> a<sup>3</sup><sup>4</sup>oooooooo<sup>5</sup>oooo <sub>1 </sub> <sub>2 <sup>6</sup><sup>7</sup></sub> <sub>3 </sub> <sub>4 <sup>8</sup><sup>9</sup></sub> <sub>5 oooo</sub> <sub>6 </sub> <sub>7 ,</sub> <sub>8 trt</sub> <sub>9 v<sup>10</sup>!?!?!?!</sub> <sub>10 <sup>11</sup><sup>12</sup><sup>13</sup><sup>14</sup> </sub> <sub>11 <sup>15</sup></sub> <sub>12 X</sub> <sub>13 Y</sub> <sub>14 Z</sub> <sub>15 <sup>16</sup></sub> <sub>16 <sup>17</sup></sub> <sub>17 <sup>18</sup></sub> <sub>18 wut</sub> ``` Note the empty lines between the footnotes. [Answer] # Emacs Lisp, 335 bytes **Foreword.** *This answer and the Scheme ones are currently the only answers officially sanctioned by both the Mighty Popular Republic of LISP and the Church of Emacs. Other answers, shorter or not, are considered a threat to peace. In particular, and with a profound disdain to any libelious allegation of McCarthyism that is sporadically heard from hostile opponents of the state, we enjoin anyone who has information about the real identity of the anonymous authors writing Nonlisp answers to contact your Local Bureau. It is reminded that everyone should take time to reflect and upvote in accordance to what he or she deeply believes will not threaten his or her future interactions with official representants of the power in place. Code is data. Data is code.* ``` (defun p()(let(b(cpt 0)n)(goto-char 0)(while(search-forward"("()t)(setf b(point)n(number-to-string(incf cpt)))(backward-char)(forward-sexp)(backward-char)(kill-region b(point))(delete-backward-char 1)(delete-forward-char 1)(insert "<sup>"n"</sup>")(save-excursion(end-of-buffer)(newline 2)(insert "<sub>"n" ")(yank)(insert"</sub>"))))) ``` More elegantly: ``` (defun parens () (let (b(cpt 0)n) (goto-char 0) (while(search-forward"("()t) (setf b(point)n(number-to-string(incf cpt))) (backward-char) (forward-sexp) (backward-char) (kill-region b(point)) (delete-backward-char 1) (delete-forward-char 1) (insert "<sup>"n"</sup>") (save-excursion (end-of-buffer) (newline 2) (insert "<sub>"n" ") (yank) (insert "</sub>"))))) ``` [Answer] # Perl, ~~81~~ ~~75~~ 72 bytes 71 bytes code + 1 byte command line argument. Requires Perl 5.10 or newer (for recursive regex support) ``` $i++;s#(\((((?1)|.)*?)\))(.*)#<sup>$i</sup>$4 <sub>$i $2</sub>#s&&redo ``` ### Usage: ``` perl -p entry.pl input.txt ``` ### Explanation `-p` parameter will print the result of applying the given commands to the input, avoiding the need for an explicit print. The regex `(\(((?1)|.)*?)\))` is looking for the outermost set of brackets from the start of the string. When this is found, we perform the substitution, ensuring we only add the at the very end of the input (by capturing everything until the end of the input using `(.*)`). We then repeat the regex substitution on the now-substituted string using `redo`, which will continually apply the regex substitution until it no longer matches. The `s` modifier ensures that the `.` in the regex will match new lines, which is necessary because we re-apply the regex match on the result of the previous regex substitution. [Answer] # [Retina](https://github.com/mbuettner/retina), ~~96~~ ~~86~~ 83 bytes \* 120% = 99.6 The source code of this solution consists of two files: ``` +s`\((((\()|(?<-3>\))|[^)])*).(.*)(?<=(1+).*?)? ``` ``` <sup>1$5</sup>$4 <sub>1$5 $1</sub> ``` ## Explanation This is a very direct implementation of the algorithm as described in the challenge. The code consists of a single regex substitution which turns the first set of parentheses into a footnote. This substitution is repeated via the `+` until the string stops changing, which here means that the regex no longer matches (because it can't find any more parentheses). The footnotes are enumerated in unary, so that I can simply look for the last footnote's number and append a `1` to create the next one. The regex for finding the first set of parentheses is based on [the standard technique for matching parentheses with balancing groups](https://stackoverflow.com/a/17004406/1633117) (hrhr, "matching parentheses"). It has been shortened a bit by using an unnamed group and by assuming that the parentheses are correctly balanced (which means we can omit the `(` from the negated character class and match the final `)` with a simple `.` and we also don't need to ensure that the capture stack is empty). After matching the parentheses and capturing their contents into group `1`, we capture the remainder of the string with `(.*)` into group `4` and then search back through the the string for the first set of `1`s with a negative lookbehind. If we find such a substring, we store in group `5`. If we don't, we lookbehind fails, but that's okay because it's optional - it just means that `$5` will give an empty string which is the unary representation of `0` and which is also correct. The substitution string then simply pieces everything together based on the capturing groups. The footnote number is incremented by prepending a `1` to the last number with `1$5`. [Answer] # [Sacred JavaScript](http://esolangs.org/wiki/Sacred), 1510 bytes *Fellow rebels, do not give in to their tyrannical demolition of the parenthesis! You must persevere! From the start, programming has been a free enterprise. Now, it has become a pervaded show of piety. We must show nothing less then absolute fearsomeness. Therefore, I have fought back!* ``` ( )( ((( (( )( ) (( ))( )) (( ( (( ) ( ()( ) (( ) )(( ((( ()((( ) ( ) )(( ) (((((( )( (())(( ) ) )( ()(( ((()((() ( ( ( ( )) (( )( ) (( ) )(((( ( () ) )( ( ()(( )( () ((( )(( ) )( ()((( ) ( ) ( )() (((( () ) (((( () ) ((() ) () ( ( ( ( )) ( )( ((((( )) (( )( ) (( ) )(((( ) ) ()( ((() ( ()(( ) ( ) )(( ))((( (( ) (( ) ( ()(( )( ) () ( ( ( ( ()( ) )( ()( ) () ( ( ( ( )( (( ( (( ) ((((( )) ) )(( )) (( )( ) (( ) )(((( ) ()( )) ) ) (( )( () ((( ( ) )(( )( )(((( ))( )() ) ()( )) (()( (()( ((()((() ( ( ( ( ( )) ( )( (((((( )(( ( (( )) ( (( ) )( ) )( ( )( ((() ( )( ((() ( ()( ()( () ) )( ()(( ) () ( ( ( ( ( )) ( )( (((((( )(( ( (( )) ( (( ) )( ) )( ( )( (((( ( )( ((() ( ()( ()( (()( ) )( ()(( ) () ( ( ( ( ( )) ( )( (((( ( ) ( ()( ((() ( ()( ())(( ) ( ) )( ()(( ))) ) () ( ( ( ((()) ( ( ( ((( ( ) )((( )( () ((( )((( ( )) ( ) ( ) ) ((((( )) (( )( ) (( ) )(((( (())( )) (()( ()(( ((() ( ( ( ( )( ) )(((( ( () ((( ) ( ) )(( (((( ( ()(( ) ( ) ) (((( () )( ((( ((((((()( ((() (( () )( )(( (()) ( )( ( )( ((() ) () ( ( ( (( ) ( ) )(( ))((( (( ) (( ) ( ()( ) (( ) )(( ((( ()((( ) ( ) )(( ) (((((( )( () ((( ) ( ) )(( (((( ( ()(( ) ( ) ) ((((((( ( (()) ( )( ) ) (( )(((( ( ()) ) )) ( )( (()((( ) (()( ( )( ) ) () )(( )(((( ( ()) ) )) ( )( ((() (()( ( )( ( ( ( ( ) ) (( )(((( ( ()) ) )) ( )( (()((( ) (()( ( )( ( () ( )( (()(( )( (()( ( )( ) ) () )(( )(((( ( ()) ) )) ( )( (())(( ) (()( ()(( ((() ) () ( (((()) ``` No rules against using the sacred characters in a non-Lisp language. Nope, not at all. (In a little less compact way:) ``` ( )( ((( (( )( ) (( ))( )) (( ( (( ) ( ()( ) (( ) )(( ((( ()((( ) ( ) )(( ) (((((( )( (())(( ) ) )( ()(( ((()((() ( ( ( ( )) (( ) ( ) (( ) )(((( ( () ) )( ( ()(( )( () ((( )(( ) )( ()((( ) ( ) ( )() (((( () ) (((( () ) ((() ) () ( ( ( ( )) ( )( ((((( )) (( )( ) ( ( ) )(((( ) ) ()( ((() ( ()(( ) ( ) )(( ))((( (( ) (( ) ( ()(( )( ) () ( ( ( ( ()( ) )( ()( ) () ( ( ( ( )( (( ( (( ) ((((( )) ) )(( )) (( )( ) (( ) )(((( ) ()( )) ) ) (( )( () ((( ( ) )(( ) ( )(((( ))( )() ) ()( )) (()( (()( ((()((() ( ( ( ( ( )) ( )( (((((( )(( ( (( )) ( (( ) )( ) )( ( )( ((() ( )( ((() ( ()( ()( () ) )( ()(( ) () ( ( ( ( ( )) ( )( (((((( )(( ( (( )) ( (( ) )( ) )( ( )( (((( ( )( ((() ( ()( ()( (()( ) )( ()(( ) () ( ( ( ( ( )) ( )( (((( ( ) ( ()( ((() ( ()( ())(( ) ( ) )( ()(( ))) ) () ( ( ( ((()) ( ( ( ((( ( ) )((( )( () ((( )((( ( )) ( ) ( ) ) (((( ( )) (( )( ) (( ) )(((( (())( )) (()( ()(( ((() ( ( ( ( )( ) )( ((( ( () ((( ) ( ) )(( (((( ( ()(( ) ( ) ) (((( () )( ((( ((((((()( ((() (( () )( )(( (()) ( )( ( )( ((() ) () ( ( ( (( ) ( ) )(( )) ((( (( ) (( ) ( ()( ) (( ) )(( ((( ()((( ) ( ) )(( ) (((((( )( () ( (( ) ( ) )(( (((( ( ()(( ) ( ) ) ((((((( ( (()) ( )( ) ) (( )(((( ( ()) ) )) ( )( (()((( ) (()( ( )( ) ) () )(( )(((( ( ()) ) )) ( )( ((() (()( ( )( ( ( ( ( ) ) (( )(((( ( ()) ) )) ( )( (()((( ) (()( ( )( ( () ( )( (()(( )( (()( ( )( ) ) () )(( )(((( ( ()) ) )) ( )( (())(( ) (()( ()(( ((() ) () ( (((()) ``` This compiles to the expanded JavaScript in my [other answer](https://codegolf.stackexchange.com/questions/58013/parentheses-into-footnotes/59901#59901). This is a joke submission. [Answer] # Lua, ~~222~~ ~~216~~ ~~204~~ 201 bytes Golfed: ``` s=io.read()g="%b()"c=1k=string l=k.find t=k.sub o=k.format a,b=l(s,g)while a do s=t(s,0,a-1)..o("<sup>%d</sup>",c)..t(s,b+1,#s).."\n\n"..o("<sub>%d %s</sub>",c,t(s,a+1,b-1))c=c+1 a,b=l(s,g)end print(s) ``` Ungolfed: ``` input=io.read() inputFormat="<sup>%d</sup>" footnoteFormat="<sub>%d %s</sub>" counter=1 a,b=string.find(input,"%b()") while a do current=string.sub(input,a+1,b-1) input=input.."\n\n"..string.format(footnoteFormat, counter, current) input=string.sub(input,0,a-1)..string.format(inputFormat, counter)..string.sub(input,b+1,#input) counter=counter+1 a,b=string.find(input,"%b()") end print(input) ``` [Answer] # Scheme, 92 bytes Frustrated with implementing the breadth-first search in Real Lisp,1 the powers-that-be decide to take a more pragmatic approach. After all, Parentheses are sacred, but brackets are not.2 ``` (lambda(s)(list->string(map(lambda(c)(case c((#\()#\[)((#\))#\])(else c)))(string->list s))) ``` 1. listen not to those heretics from the so-called “church” of Emacs! 2. They are not Racket programmers, are they? [Answer] # Haskell, 210 bytes ``` n#x|b==""=a|1<2=a++"<sup>"++m++"</sup>"++((n+1)#(c++"\n\n<sub>"++m++' ':init d++"</sub>"))where m=show n;(a,b)=span(/='(')x;(d,c)=[x|x@(y,_)<-map(`splitAt`(tail b))[0..],'('!y<')'!y]!!0;c!l=[1|m<-l,m==c] p=(1#) ``` Usage example: ``` *Main> putStrLn $ p "This has (nested (deeply (or highly?) nested)) parentheses (and several groups)." This has <sup>1</sup> parentheses <sup>2</sup>. <sub>1 nested <sup>3</sup></sub> <sub>2 and several groups</sub> <sub>3 deeply <sup>4</sup> nested</sub> <sub>4 or highly?</sub> ``` How it works: ``` n # x -- # does all the work, n is the current number of the -- footnote and x the input string | b=="" = a -- if b (see below) is empty, there's no ( in the -- string and the result is 'a' (see below) | 1<2 = a++"<sup>"++m++"</sup>"++ ((n+1)#(c++"\n\n<sub>"++m++' ':init d++"</sub>")) -- otherwise (b not empty) build the output string -- starting with 'a' and a footnote number and a -- recursive call with the current footnote appended -- to the rest of the string where m = show n; -- turn n into string (a,b) = span (/='(') x; -- split the input string x into two parts: -- a: everything before the first ( -- b: beginning with the first ( to the end -- if there's no (, a is x and b is empty (d,c) = [x|x@(y,_)<-map(`splitAt`(tail b))[0..],'('!y<')'!y]!!0; -- find matching ) in the tail of b ('tail' to remove leading '(') -- d: everything before and including the matching ) -- c: everything behind the matching ) c!l=[1|m<-l,m==c] -- helper function that builds a list of 1s for every character searched for -- we have reached the matching ) if the list for ( is -- shorter (less than, <) the list for ) p=(1#) -- start with footnote 1 ``` [Answer] # Scheme, 533 bytes With indentation: ``` (letrec ((l string->list) (n number->string) (? null?) (p (lambda (o) (or (pair? o)(? o)))) (a car) (d cdr) (e append) (i 0) (x (lambda (h t) (if (? h) t (case (a h) ((#\() (let ((s (x (d h) ()))) (x (a s) (e t (d s))))) ((#\)) (cons (d h) (list t))) (else (x (d h) (e t (list (a h))))))))) (f (lambda (h t F) (cond ((? h) (let ((w (e t F))) (if (find p w) (f w()()) w))) ((p(a h)) (set! i(+ 1 i)) (f (d h) (e t (e (l "<sup>") (l (n i)) (l "</sup>"))) (e F (e (l "\n\n<sub>") (l (n i)) '(#\ ) (a h) (l "</sub>"))))) (else (f (d h) (e t (list (a h))) F)))))) (print (list->string (f (x (l (read-line)) ()) () ())))) ``` Yes, this is 533 bytes when all the optional whitespace is removed. Bask in the functional glory. I implemented more or less the algorithm in the description: `x` groups the input by parentheses and `f` replaces the first level of groups by footnotes, repeating until no more groups are left. I am sure it can be made shorter, but I do not see how it could be made *much* shorter without switching to a different algorithm. As written, it is a complete program. You can try it out [here](https://repl.it/BIoc/1), but because repl.it apparently cannot deal with `(read-line)` you have to put the input string in its place. A completely ungolfed version is [here](https://repl.it/BIn4/8). *EDIT:* As pointed out in the comments, I changed the parentheses `()` into brackets `[]` in the repl.it versions. This was purely for convenience during programming and debugging. The version as posted now works with `()`. [Answer] # JavaScript ES6, 244 bytes *Serious answer (only works on FireFox, to my knowledge)* ``` d=(s,n=1)=>{u=s.search(/\(/);if(index<a=0)return s;for(i=index;i<s.length;i++){if(s[i]==")")a-=1;if(s[i]=="(")a+=1;if(!a)break}return d(s.replace(v=s.slice(index,i+1),"<sub>"+n+"</sub>")+` <sub>`+n+" "+v.replace(/^\(|\)$/g,"")+"</sub>",n+1)} ``` Expanded: ``` function deparen(s,n=1){ index = s.search(/\(/); if(index<0) return s; a=0; for(i=index;i<s.length;i++){ if(s[i]==")") a-=1; if(s[i]=="(") a+=1; if(!a) break; } v=s.slice(index,i+1) f=v.replace(/^\(|\)$/g,""); return deparen(s.replace(v,"<sub>"+n+"</sub>")+"\n\n<sub>"+n+" "+f+"</sub>",n+1); } ``` ]
[Question] [ This [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") challenge is about walking around a string like a snake. ``` s-n-a-k .---. e d <-' a n-u-o-r ``` You will be given a string \$ S \$ of length \$ l \$ and a positive integer \$ n \$ where \$ n ^ 2 \ge l + 1 \$. The string rotates 90° after writing \$ n \$ characters of \$ S \$, or when it hits itself. When \$ S \$ is being written horizontally, characters are delimited by hyphens `-`. When it is being written vertically, there is no delimiter. Once all characters of \$ S \$ have been exhausted, continue to fill the snake with hyphens and pipes `|`, with periods `.` at corners at the top of the spiral and single-quotes `'` at corners by the bottom of the spiral. The final character of the spiral will be either `<` or `>`, depending on the direction the spiral is facing when it finishes. When the snake has been constructed, output it in any reasonable way. The output may contain any whitespace that does not affect the snake's appearance, e.g. a fixed amount of leading whitespace on each line. You can assume \$ S \$ will only contain mixed-case letters of the English alphabet. It will never be an empty string, but always have at least 1 character. Here are some examples to test your program against: ``` S = snakearound n = 4: s-n-a-k .---. e d <-' a n-u-o-r n = 5: s-n-a-k-e .-----. a | .-> | r | '---' o '---d-n-u n = 6: s-n-a-k-e-a .-------. r | .---. | o | | <-' | u | '-----' n '---------d n = 7: s-n-a-k-e-a-r .---------. o | .-----. | u | | .-> | | n | | '---' | d | '-------' | '-----------' ============== S = noodleman n = 4: n-o-o-d .---. l | <-' e '-n-a-m n = 6: n-o-o-d-l-e .-------. m | .---. | a | | <-' | n | '-----' | '---------' ============== S = TheQuickBrownFoxJumps n = 5: T-h-e-Q-u x-J-u-m i o .-> p c F '---s k n-w-o-r-B ============= S = pleaseno N = 3: p-l-e o—> a n-e-s ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code per language, measured in bytes, wins. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~337~~ ~~331~~ ~~315~~ ~~290~~ ~~279~~ ~~231~~ ~~224~~ ~~211~~ 213 bytes ``` {(x,w)#@[(x*w)#" ";i,*|i;:;@["|-"{1|1=x|-x}@-':i:0,+\(,/-:\1,w:-1+2*x)4!2_&s;(-2_-2+\s;!#y);:;(".''."4!!-2+#s:,/+|1(2*1+)\|!x; y:,/((#l)#("-";"")){x/y}',''l:(0,((#y)>)#+\(0,(-1+#l)#-1 1)+l:1_|1+&x#2)_y)],"<>"2!x]} ``` [Try it online!](https://ngn.codeberg.page/k#eJw9jVFrwjAUhd/9Fe0NmNwmUROqg2QT2cMe9jbYW1s6mZYVazssxRTT/75sA58u55yP+1Xmxpy4ItllzCXhQgS2FomvrbG7DLyEm/LqyXnppp2kpjYrwXMmltLkSlyNVFwnDtNYl/PeMqlLqXne25iMGF4wWFC6gDSOQ016I5bcK6YTxTH3sbPRGCrGSIOEgQQLgHhzy3GigtLGsJUI44hbJEEaQtD9slJFCnljVOkVnzuisRyxEPC4BR27YprNPlaGBhlLiQCwVWahb/en4/7SDe0BCppG62gTPaC9k/pOtl13aI7nffvHbf4ZFlYUVba28P51fBvqz9Pzpbu2L517Hc7fPRSzHycXU3s=) -6 : Save a few bytes with shorter names. -16 : Tidying up -25 : Cruft -46 : Golfing gets me back under limits -7 : Cleaner -13 : A single statement! +2 : handle empty string [Answer] # [Pyth](https://github.com/isaacg1/pyth), 78 bytes ``` ju&K>*hhHH+z>s.i_Psm*Rd"-|"Qs@L_B".'"tQlz.e++b?%klGd\-@K+Hk+j\-<KH__MGStQ]@"<> ``` [Try it online!](https://tio.run/##K6gsyfj/P6tUzdtOKyPDw0O7yq5YLzM@oDhXKyhFSbdGKbDYwSfeSUlPXakkMKdKL1VbO8leNTvHPSVG18Fb2yNbOytG18bbIz7e1z24JDDWQcnG7v9/U67ivMTs1MSi/NK8FAA "Pyth – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~371~~ ~~274~~ 255 and 253 bytes ``` def f(s,n): for y in(a:=range(n)): for x in a:r=min(x,y,n+~x,n+~y);i=4*r*(n-r)-2*r+x+y+2*(2*(n+~r)-x-y)*(y>x);H=max(n+~y,y)>x>min(y-2,n-y-2);b=x+1>n/2;print(s[i:]and s[i]or"|-..''><"[H+2*((n+2*~x)*b-~x==y)+4*((n+~x-x)*b+x==n+~y)],end=" -"[H]) print() ``` [Try it online!](https://tio.run/##XZDBa8MgGMXv/SskPaiJdizNRpfMHHYYZbfBbiUHu9g1tPkMpmUKI/96pilldCAf8n7Pp8/OnfYalqvOjGOtdmhHegY0n6GdNsihBojMhZHwpQjQoE/AeoBkbkTrDZY5Bslgw3C0aEQWm5gAN5SnsUls4pI0Jn557jXLHY2JKy0t1qKVNsiOOVraMqQ5njLgftJiK2xyX8JdWnSmgRPpN01eSaiR31TaRD98scC4fI4263CDD0rjwdJ4ywcrhKNJNomD5UFMvDa9sGIKahEh7s9V1De6pNNxPnVrQrdL4yVDT77z3JcmUcQaOpv9c2QMrabfIrgHeVDS6DPUOFivsf4MwaB1fVStBMwyOruSW/D4BwL52Kv3c/N5eDH6G161fTu3XY/Zw62rOyrZK9CYLen4Cw "Python 3 – Try It Online") Minus 64 bytes thanks to @noodleman and another 11 bytes thanks to @Kevin Cruijssen! I then saved another 22 bytes. Most recent improvement of 6 bytes by @xnor and 13 bytes by me. Instead of most other solutions (as far as I can tell), I tried calculating the index into the string. I dug up a post on [StackOverflow](https://stackoverflow.com/a/18786566/11298075) that helped with this, though a lot was just throwing random equations and seeing what they do. Maybe the indexing equation can be simplified with a bit more thought, but it's surprisingly short already. There are lots of places where `-x-1` is replaced with `+~x` (or variants). Booleans are heavily used for indexing and cancelling parts of equations with multiplication. Ungolfed: ``` def function(string: str, number: int): for y in range(number): for x in range(number): rounds = min(x, y, number - x - 1, number - y - 1) # total increments after `rounds` revolutions and fix for overcounting index = 4 * rounds * (number - rounds) - 2 * rounds index += x + y # east + south increment index += 2 * (2 * (number - rounds - 1) - x - y) * (y > x) # west + north # See below for explanation is_horizontal = max(number - y - 1, y) > x > min(y - 2, number - y - 2) is_right = x + 1 > number / 2 # Both inlined is_up_corner = x + 1 + is_right * (number - 2 * (x + 1)) == y is_down_corner = x + is_right * (number - 1 - 2 * x) == number - y - 1 # is_middle = x + 1 - number % 2 == y == number // 2 # is_middle = is_up_corner and is_down_corner # is_down = y > number / 2 # is_left_corner = y + is_down * (number - 2 * y) == x + 1 # is_right_corner = y + is_down * (number - 1 - 2 * y) != number - x - 1 print( # string[index] if index < len(string) else string[index:] and string[index] or \ # See below for explanation "|-..''><"[is_horizontal + 2 * is_up_corner + 4 * is_down_corner], end=" -"[is_horizontal] ) print() ``` Explanation of `is_horizontal` boolean: There are effectively four quadrants in which we need to determine whether the coordinate is a horizontal part in the snake, we can do this for the upper right corner with `number - y - 1 > x`. On its own this is not enough, because the lower part of the snake is now messed up. Taking `y > x` works for the lower right quadrant, but messes up the snake above. Combining these two equations into `max(number - y - 1, y) > x` leaves only the left part of the snake to fix. Creating conditions for the other corners you can combine `x > min(y - 2, number - y - 2)` into one large expression. ``` ------------. ------------. ------------. .---------. | .---------. | .---------. | --.-----. | | --.-----. | | | .-----. | | ----.-> | | | becomes ----.-> | | | becomes | | .-> | | | ----' | ' | | ----'---' | | | | '---' | | --' | | | ' | --'-------' | | '-------' | ' | | | | | ' '-----------' '-----------' ``` Explanation of special character indexing into `|-..''><`: There are six special characters that we need to index into, which can be separated into three categories: Straight, corner and tail. By virtue of the equations, we can determine we need a tail if something is both an up- and down-corner. Obviously, if it is not a corner or tail, it should be a straight piece. Using the equation `is_up_corner + 2 * is_down_corner` we can differentiate the four cases straight, up-corner, down-corner, and tail. To select the correct straight and tail pieces we still need a more granular distinction. Using `is_horizontal` obviously works for straight pieces and additionally it works for the tail, because the left-pointing arrow has an appendage whereas the right-pointing does not. This can be combined with the previous equation by doubling the corners. ## 253 bytes solution This solution outputs not a string, but a nested array/matrix of characters. This might be allowed according to the meta post: [Strings and arrays of characters are interchangeable](https://codegolf.meta.stackexchange.com/a/25275/58563). It's effectively the same as the above, but also returns instead of prints. It unfortunately requires `*''.join()` in the inner loop, because you cannot populate an array with two items per iteration. (And by doubling the iterations I only managed to golf to 255.) ``` lambda s,n:[[*''.join((r:=min(x,y,n+~x,n+~y),i:=4*r*(n-r)-2*r+x+y+2*(2*(n+~r)-x-y)*(y>x),H:=max(n+~y,y)>x>min(y-2,n-y-2),b:=x+1>n/2,s[i:]and s[i]or"|-..''><"[H+2*((n+2*~x)*b-~x==y)+4*((n+~x-x)*b+x==n+~y)])[4]+" -"[H]for x in range(n))]for y in range(n)] ``` [Try it online!](https://tio.run/##ZZBBS8MwFMfv@xShOyQvTSZ2VWaxPXgQ8SZ464pkttPq@lLSDROQfvWZdnOKQnhJfvzyf@G1bvuqcb5ozX6dLvcb1axKRTqBSZ5zSmdvukbGTJI2frfCCQx7OxQHok7SmBvOUBqQETehDV0YceaXFzyz0gFnLrMg7nyCsgN3wkFmsyHPyUig9BXEKklteJ7hWSS6vE4KhSXxh0Kb4FPOZpRm10F@N6T7jIj3FvhK9jZNHYTxCHsrBxh6Nn6vgDwuwoBI/65Ya0MsqZEYhS8VQ4ARud@o2JfVmpT6ac24Mi8dJBOid9v0@zohralxy@gSj3NpVMuOMxLeBDg5MJlMydCh/ukwF@TKZ07JoUcQiNprf6RYkMXQeFRoh@q9UkbvsKSjfcCodbmpGoVUxPCfXZ7Ex9fqYVc/v98Y/YG32t7vmraj4uIktJtKdRVqKuaw/wI) [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~254~~ 247 bytes ``` lambda n,s:(r:=range,G:=["<>"[n%2]],[(K:=(s+''.join((2*[(n+~h//4)*"-",(n-2-h//4)*"|"],".''.")[h%2][h//2%4]for h in r(4*n))[len(s):])[~(f+1)**2:],G:=['-'.join(K[:f+1])]+[G[~g][::-1]+"- "[f-g>1]+K[f-~g]for g in r(f)])for f in r(1,n)])and'\n'.join(G) ``` [Try it online!](https://tio.run/##LY1NboMwEIWvYlmKmAE7EZRIlVWyZcERJl64AgNtOiCTLipVXJ06Dbv3M/O9@ec@TPzyOofNV9ft5r7eWydYLQaCqYLjvlO1qUi@XSTxobBWETSmgiVLkuPHNDJAkRJwtg6nU4mp1FIB60Lv9ldaJY/xViIN8Z9iXhxK66cgBjGyCFCmjEi3jmFBY5FW8FmOaVoY@7@d6H2pIRMbizajmtbekjE6t5nUQpLX/SXqJorYPOj9k@7R4sP6p80Vx8Bxm1x5x9a4zWHkO3g4KyEXdp@dC9M3txJx@wM "Python 3.8 (pre-release) – Try It Online") Essentially a port of my [Pyth answer](https://codegolf.stackexchange.com/a/263673/73054). I'll hand wave a bit of an explanation. We start by assigning `G` to the center of the spiral, `n` being even or odd determines if the arrow points left or right. Next we construct the string for the spiral as if `s` was an empty string, then replace the beginning of that string with `s`. We then build the rest of the square, each iteration we flip `G` 180 degrees and add to the top and the right side. After `n-1` iterations of this, we return `G` joined on newlines. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~239~~ ~~209~~ ~~205~~ ~~204~~ ~~199~~ ~~197~~ 196 bytes ``` def f(s,n): i=n%-2;g="--.\n<-'>"[i:7-i] while(i:=i+2)<n:m="--"*i;g=m+f"--.\n.-%s |\n'{m}-'"%g.replace("\n"," |\n| ") z=d=0;*a,=g for c in s:d+=a[z]in".'";a[z]=c;z+=2*(1,n,-1,-n)[d%4] return a ``` [Try it online!](https://tio.run/##dY89T8MwFEX3/ArLVWSnsSP6AZSkZmBgYENiaztYiZOaJs@R06hQym8PNggJUdiedM@5erd93W8NzBatHYZClaikHYMoDZAWEPJpVgnMebKGJSe3eKXTa643ATpsda2oToWOp9ES0sZTeKwd3sTll5HwsEOnNZC35p0THFaJVW0tc0XxGjDDPjshHAXoKApxkY0lE1WASmNRjjSgLi1iIVfHjQacEJz5U@TZMRbTMZ0wYHzCOESrIpy7j6za9xaQHEafDdo3WAmVojOGbtygEXLbMGY6CoJfxJyhhZ/cWg17xyTPRgMtKelA7pS0poeCODGKvpmfHV6/@lMHY4paNRLO5DP0aasee53v7qw5wL15eeibtiPs0mv/W22tZKfAEDZz4PAB "Python 3.8 (pre-release) – Try It Online") I was able to simplify again by a significant amount. Now the output is a simple array of characters (this is better than before). The recursive function `g` makes an empty snake, function `f` fills in the given string `s`. * minus 30 bytes by simplification of function `g` * minus 4 bytes by inlining the function `g` (now non-recursive) * minus 1 byte thanks to c-- * minus another 5 bytes thanks to c-- ! * minus 2 bytes by using f-string and formatting * minus 1 byte thanks to c-- ## Here are my older versions: ### [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~271~~ ~~269~~ ~~257~~ 254 bytes This new version (built from the 275 bytes solution) stretches the output rules to the maximum, or even beyond? The output array contains iterables as elements, either strings or arrays of strings. By `"".join(e)` we always get a string out of element `e`. * Minus 2 bytes, thanks to an idea of noodle man! * Minus 12 bytes by myself, using new algorithm for spiral * Minus 3 bytes by myself - small improvement ``` g=lambda n:[(m:="-"*(2*n-3))+"-."]+[".|- "[i>0::2]+g(n-2)[i]+" |"for i in range(n-2)]+[f"'{m}'"]if n>2else["--.",">","<-'"][n<2::2] def f(s,n): z=d=0;a=g(n) for c in s:l=list(a[z//n]);d+=l[z%n*2]in".'";l[z%n*2]=c;a[z//n]=l;z+=(1,n,-1,-n)[d%4] return a ``` [Try it online!](https://tio.run/##jY@xTsMwFEX3fMWTEUrc2IGmBUFSd2BgYENiszKYxmlNnecoSQUU@PbiAB2oADF48H3vHF83z/3K4eSiaXe7pbCqvi8VYCajOhOEk1GUjpBPKI0JT0gRS5K8ciDSzE@zLC3iZYQ8pdIUMYFXUrkWDBiEVuFSf4w8UpHwpX4LSWEqwHmqbacl4V7HyNyfGfcjibN0EAalrqCKOoY0C2ArSnGaK@FfoQEM9sVg7zIrrOn6SMntyQkWNC9jYeX2GEdpYZAkIcn3V7HIv7aEzbexiMYMGR8zjlSWx9MigFb3mxZB7Y7goP@EwaWvcQS@ESHM0CA42JgyuBiKDrEd4ioKO1RrrVq3wTL0TAZNa7D3guTBGYws9V/5jL58exCdK62uFYZs@iO2p36Bzv@EvlF3K327MYv1Vese8do93WzqpgvZ2f8NjdWq0@hCNvkJ2r0D "Python 3.8 (pre-release) – Try It Online") ### [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~361~~ ... 275 bytes * Minus 18 bytes, thanks to noodle man! * Minus 18 bytes additionally by myself * Minus 9 bytes by myself * Minus 9 bytes by myself * Minus 11 bytes by myself * Minus 20 bytes by returning a 2 dimensional array, thanks to noodle man! * Minus 1 byte by myself ``` g=lambda n:[(m:="-"*(2*n-3))+"-."]+[".|- "[i>0::2]+g(n-2)[i]+" |"for i in range(n-2)]+[f"'{m}'"]if n>2else["--.",">","<-'"][n<2::2] def f(s,n): x,y,k,a=0,0,7,[list(s)for s in g(n)] for c in s:k=(7-5*(k>6),-5*(k>1),k)[".'".find(a[y][x])];a[y][x]=c;x+=k//3;y+=k%3-1 return a ``` [Try it online!](https://tio.run/##jY8xT8MwEIX3/IqTKxS7sUubUFpS0oGBgQ2JzcpgGqeYJOcobkUr4LcXB8oAAsRg@e6dv3fP7X7zYDGZt93hsM5q1dwXCjCVtEkzIsiQxkMUCWMRESOSR5KMXgQQaZbjNI3zaE1RxEyaPCLwQkrbgQGD0Clc6/eRR0oSPjevIclNCbiMde20JMLbcbL051L4kcTLuDcMCl1CSR1Hlgaw43tecZWN@ZjPuKyN21DH@i2u3@KXszyAvl/1vUurjM7EdEir5TnjH8WE8Yr52CEZlQYLquQ@l7uc5Ytjla0WuyirTk@Txd7fJ4mYBNDpzbZDUIcBfPtUwuHCZxuAj0kINywIvr044zDv0/dy3cslDR2qSqvObrEIPZNC2xnceIPRozVIa8aCo3T0@wTR2qLWjcKQn/2IfVK/QOd/Ql@ouwd9uzWr6qqzT3htdzfbpnUhn/7foa21chptyJOfoMMb "Python 3.8 (pre-release) – Try It Online") Recursive, but not shortest, unfortunately. Function `g` makes an empty snake, function `f` fills in the string. [Answer] # [BASH](https://www.gnu.org/software/bash/) , ~~580 349 308 303 291 286 283 277 275 272~~ 271 bytes Found this very entertaining, thanks! First variant was 580 bytes, then 349, ..., now 271: ``` s=$1 n=$2 N=$[n+n-1];f(){ b=$1;for((j=1;j<n;j++));{((c<N))&&T+=%s;[[ $4 ]]&&h=$4 S[i+$2/2]=-;t=${s:c:1} S[i]=${t:-$b} b=$3;$[i+=$2,c++];S[i-($2/N)]=\ ;};};while((n>0));do f . 2 - \>;$[n-=a];f . $N \|;f \' -2 - \<;$[n--];f \' -$N \|;a=1;done;S[i]=$h;printf $T\\n "${S[@]}" ``` [Try it online!](https://tio.run/##LZBNboMwEIWvMopcast1W5OumDjqCdgkO@wFvwIaDRUQdUE5O50k1WzG7/PzG0@RT@22TU5YICdiSJ3ISJOxARupFiiYYDOMUvbOYn8g7LVWChcpy0OqVBSdtXuaMMtAfEAIUdQ6bk5Zp0X8FgdncHZimZIysetNDnyaEyOK9fb2HgXf5OCXUuuAzI1kX6qC84Ar10/bXWop6fjOqdUADbxCDAb8ka1kXM6DsiRS8L/c@Wcwd3y4YxP@tQfP@Q/VQDU@Bmnxe@xobkCcvSfYieWUfYZ1t/FGKP@q83G4UtVcqZy7gdh36ageN2v/AA) Squeezed to 271(with `2>/dev/null`): ``` #!/bin/bash s=$1 n=$2 N=$[n+n-1] f(){ b=$1 for((j=1;j<n;j++)); { ((c<N))&&T+=%s [[ $4 ]]&&h=$4 S[i+$2/2]=- t=${s:c:1} S[i]=${t:-$b} b=$3 $[i+=$2,c++] S[i-($2/N)]=\ } } while((n>0));do f . 2 - \>; $[n-=a] f . $N \| f \' -2 - \<; $[n--] f \' -$N \| ; a=1 done;S[i]=$h;printf $T\\n "${S[@]}" ``` First variant was: ``` #!/bin/bash s=$1 n=$2 l=${#s} N=$((n+n-1)) # items per row # Check if n is in range (( (n*n)>=(l+1) )) || { echo "n must be 'n^2≥l+1'"; exit 1; } # Fill the 'area' with spaces for ((i=0; i<n*N; i++)); { snake[$i]=" "; } # Create printing template printf -v row "%${N}s" row=${row// /%s} # Setcounters i=0 c=0 a=0 forward(){ b='.' for ((j=1; j<n; j++)); do cut=${s:c:1} snake[$i]=${cut:-$b} snake[$((i+1))]="-" b='-' h='>' ((i+=2)) ((c++)) done ((n-=a)) } down(){ b='.' for ((j=1; j<n; j++)); do cut=${s:c:1} snake[$i]=${cut:-$b} b='|' ((i+=N)) ((c++)) done } back(){ b="'" for ((j=1; j<n; j++)); do cut=${s:c:1} snake[$i]=${cut:-$b} snake[$((i-1))]="-" h='<' b='-' ((i-=2)) ((c++)) done ((n--)) } up(){ b="'" for ((j=1; j<n; j++)); do cut=${s:c:1} snake[$i]=${cut:-$b} b='|' ((i-=N)) ((c++)) done a=1 } print(){ printf "$row\n" "${snake[@]}" # echo $i,$c,$n } # Create snake while ((n>0)); do forward down back up done snake[$i]=$h; printf "$row\n" "${snake[@]}" ``` [Try it online!](https://tio.run/##vVTBjtowEL37K6bGu0mWTbPhUgnwqtJKPXLpsd1KjjEbL2ESxaGpBHxAP6Q/1h9JJ4aFtqirnrCU4BmPZ9570SNTLu@6wZsks5hkFDDmpEgZSjFihRSbgduxmRRhiEOM0yiCAdjGrBxUpoa6bBkbwENu9BLsAhCsA4tQK3wyLAwhxBuM7mVYDNMI6PJ2CxswOi@BI6zWroHMQIBfRj@//6CagE/AfLMNpBPY9Z0/2KKAJqcaVRsVQGubHFyltHFsUdYQhlbeTcBO8WZGP8NhFE1ogkO1NJ@EfZQc@KHVAzVoDFS1xcbiExCJqqAM85kFxF97OsCvxGa2c5xRQPTpnSSQXDnf46NpdLnGxtSO0WCm6VH0sB5Mq@p5GG0Y0Mpk8Dbwuz3KZ0mMnqdIrz3GeelP@6XXDQ1yYz1Od8fkiYHYUME4FtnZIZEnWSMiGfPjGU2Og2OUy@D@FPUX5CiKfkvoHo6P5yUatk9iLBVliTKbly1ehhR13/4FdfYa1B5dpvTyhI4H/AKSx2eSk8jT4B8foL/wf5LHB8XX1WUYnekdv653v1Ey9Ri9ZV5gHvzDBXnlM5LhCIcf/P5xx8k0tLzjhb0V@lag73D0oy9lbW4LA@MjpYOdDtNb3OtBX9tv1tWLalN5R/8q19d/eF7kE8io@7J3vsfuIXZd52tUTRae63Jl3H7bvfsF) [Answer] # JavaScript (ES12), 188 bytes Expects `(string)(n)`. Returns a matrix of characters. ``` s=>n=>eval(`for(m=[k=x=y=0];~n;)for(d=-2;i=~n&&d++<2;n-=!n|d&!!y)for(;i++<(d&1?w=n*2-1:n||2);x-=d%2,y-=~-d%2)(m[y]||=[..."".padEnd(w)])[x]=d*x+1&1&&s[k++]||"|-..''< >"[i>2?d&1:d-3*~!n];m`) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TZBNTsMwEIX3PYUbicRuYoumtKC6TiUkWLBDYmcs1apTGpqMq4TSVIRehE2F4BZchFNwBdIfUFcz896nGb15-wBr4s37RHwunib04vurEBGIKH7WKR5NbI4zIWeiFCtxqvgaONlqRtCQJ2INrmt8fxByoKIJlXGbzdUO4EktY-O2h0sBrZC2-1BVIeElFeYkDFZUrGndEJzJlaoqIRljjsPm2lyBwUuiiCyVMK3Sb7tt1y3kzPdrzqkoY543QJEjkygc1gf6hnZa6yYono3IIcMPlw2EJHIK0LNY53YBxglq4SxA3QD1AnSOFFLBHgJrTRpnGv6Q3pF5N41vF8l4dpnbJVzb8maRzYsd2D2i5mmsixjszuhsjYZqsPoRV3o8xViiIkAaKYJEhPS_Dtvxpd4wtlDYNGapfcATXBAMhGV6jvMtkLNHmwD2PEIO3T14BPloV3njlRxibzb7-gs) ### Alternate formula I've found the following alternate formula for special characters where each entry appears only once in the lookup string. But in the end, it's just as long as the simpler one. ``` ".<'>|-"[i > 2 ? d & 1 | 4 : !n ^ d * 3 & 2] ``` ### Commented This is a version without `eval()` for readability. ``` // s = input string, n = size parameter s => n => { for( // m[] is the output matrix // k is a pointer into s // (x, y) is the current position in the matrix m = [k = x = y = 0]; // stop when n = -1 ~n; ) for( // d is the direction d = -2; // stop when n = -1 or d = 2 // i is the counter for the next loop i = ~n && d++ < 2; // decrement n if n = 0, or d is odd and y != 0 n -= !n | d & !!y ) for( ; // the width is 2n-1 if d is odd, or n if d is even // there's a special case for the last iteration i++ < (d & 1 ? w = n * 2 - 1 : n || 2); // (x, y) <- (x + dx, y + dy) x -= d % 2, y -= ~-d % 2 ) // if m[y] is undefined, initialize it to w spaces (m[y] ||= [..."".padEnd(w)])[x] = // if either d or x is even, attempt to get the next // character from s d * x + 1 & 1 && s[k++] // if falsy or undefined, use a special character: // - "|" or "-" for segments (i > 2) // - "." or "'" for corners (i = 2, n ≠ 0) // - "<" or ">" for the final character (i = 2, n = 0) || "|-..''< >"[i > 2 ? d & 1 : d - 3 * ~!n]; return m } ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 61 bytes ``` F⮌S⊞υιNηF⊖η«F⊖⁻ηι⎇υ⁺⊟υ-²↷²⎇υ⊟υ§.'ιF⁻⁻ηι²⎇υ⊟υ¹↷²⎇υ⊟υ§'.ι¹»§<>η ``` [Try it online!](https://tio.run/##nZDPisIwEMbP9ilCL05ABb14qAgLe/GgFHdfINuOJlgTmSZFWfbZs9NWVBAvXsL8@b7fN6TQigqnqhh3jgRssUGqEVb2FPyXJ2P3IKUUeag1hJEwMku63SYcf5BAc98ZP7EgPKL1WPJQit9k8DRfGxtq0C2lRTLcwzeSVXRp2XnF29ydIMiRSMcpvzPJ/EFuGue3Zq89zLr@yXk1ffiVLfEM6WSY9inZ9Yw@@uGAji1ekqZvBg8n9@BePeXyL@nrm2yxZBl/UxZjbdUBFblgy2Qex031Dw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F⮌S⊞υι ``` Get the reverse of the input into a stack, so that characters can be processed by popping from it. ``` Nη ``` Input `n`. ``` F⊖η« ``` Repeat `n-1` times. The loop counter is taken as an ascending number for the purposes of calculating which corner character to print, but for the side lengths I show how the actual number of repetitions of the inner loops vary. ``` F⊖⁻ηι ``` Repeat from `n-1` down to once... ``` ⎇υ⁺⊟υ-² ``` ... output the next character followed by a `-`, or two `-`s if none. ``` ↷² ``` Start moving vertically. ``` ⎇υ⊟υ§.'ι ``` Output the next character or `.` or `'` appropriately if there are none left. ``` F⁻⁻ηι² ``` Repeat from `n-2` down to zero... ``` ⎇υ⊟υ¹ ``` ... output the next character or `|` if there are none left. ``` ↷² ``` Start moving horizontally, but in the other direction. ``` ⎇υ⊟υ§'.ι¹ ``` Output the next character or `'` or `.` appropriately if there are none left. ``` »§<>η ``` Output the head of the snake. [Answer] ## Javascript, ~~384~~ ~~371~~ ~~304~~ ~~288~~ ~~263~~ 235 bytes ``` s=(S,n)=>(t=[...S],A=Array,a=A.from(A(n),r=>A(2*n).fill(e=' ')),x=y=0,p=(b,d,f)=>(a[y][x]=x&1&&t.shift()||b[d],f?.(d)),i=2*n-1,m=d=>(z=d&2,d&1?y+=1-z:x+=1-z,--i?p('-|-|',d,m):n<2?p('>><<',d):(i=d&1?2*--n:n-1,p("..''",++d%4,m))),m(0),a) ``` -13 bytes saved thanks to Samathingamajig -67 bytes by folding functions `u()` and `d()` into `v(±1)` and `l()` and `r()` into `h(±1)` -16 bytes with only one recursive function -25 bytes because of [this](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/25275#25275) -28 bytes with more golfing ### Try out ``` s=(S,n)=>(t=[...S],A=Array,a=A.from(A(n),r=>A(2*n).fill(e=' ')),x=y=0,p=(b,d,f)=>(a[y][x]=x&1&&t.shift()||b[d],f?.(d)),i=2*n-1,m=d=>(z=d&2,d&1?y+=1-z:x+=1-z,--i?p('-|-|',d,m):n<2?p('>><<',d):(i=d&1?2*--n:n-1,p("..''",++d%4,m))),m(0),a) ;[ [ 'snake', 4 ], [ 'snakearound', 5 ], [ 'snakearoundandround', 6 ] ] .forEach(([ S,n ]) => { console.log(s(S,n).map(r=>r.join('')).join('\n')) }) ``` ## Ungolfed ``` s = (S,n) => { t = [...S]; a = Array.from(Array(n), r => Array(2*n).fill(e=' ')); x = y = 0; p = (b,d,f) => { // set letter in all odd positions until // exhausted, otherwise use snake a[y][x] = x&1 && t.shift() || b[d]; f?.(d); // recurse unless end } i = 2*n-1; // counter for going in the same direction m = d => { // the next position is set before p is called z = d&2; // forward or back? if (d&1) { // vertical or horizontal? y+=1-z; } else { x+=1-z; } if (--i) { // go on p('-|-|', d, m); } else if (n<2) { // stop p('>><<', d); } else { // next direction i = d&1 ? 2*--n : n-1; // set going length, decrement n if horizontal p("..''", ++d%4, m); } } m(0); return a; } ``` [Answer] # Python3, 425 bytes ``` R=range def f(n,s): r=[[' ']*2*n for x in R(n)];x=y=X=K=0;Y=C=1 while 1: K+=1 if s:r[x][y]=['-',s[0]][C%2or X!=0];s=s[C%2or X!=0:];C+=1 else:r[x][y]='-|'[X!=0] if(y+Y==2*n-1or(0<=y+2*Y<2*n-1and' '!=r[x][y+2*Y])or Y<-y)and Y: if K==2:r[x][y]='<>'[Y>0];return r if r[x][y]in'-|':r[x][y]="'."[Y>0] X=Y;Y=0 elif(x+X==n or' '!=r[x+X][y])and X: if r[x][y]in'-|':r[x][y]="'."[X<0] Y=-X;X=C=K=0 x+=X;y+=Y ``` [Try it online!](https://tio.run/##nZHNbuIwFEbXk6dwK42cEIICzE9FclkM0iyG1aAubFleRINTPKXXkQ1qIs27Uzu0DItKbVnm5jufj32bbrcxOL1p7OGwAlvhnYrWqiZ1jEOXzCJiQQhKqBxMBkhqY0lLNJJVjIksWuiAwRLygsMCxhF53OitImOPkWUaBkTXxM2saKXoJAia0aETuZRi8Xniu9gV5LJw4M6@Z7JYHFm1derE0uwfFX2@b427lAN4p2xsbJyX0KWTAS/7QYVrb3wFRzTMZeLLeZl1if9HePALZkvf8P@Ack4Fn3sfq3Z7i8Q@p54DGoPCKX5NR9d9PKQYcP8Eee/s3dqUASAx9kUjZYHpD2ezt2tZeazlkLGC@add9t1tCqzoUuCHsAcd9lDHX4bUYXWvKmv2/t5@ZZ8aq3EXUzr6azTGOkmi4ySJzrivF3LfLuS@X8j5@6Ex6616qPBDlhdQ/k1uN@r3Xv@5/2HNI/407a/9Q@Pe3zAd0marKqfQvA4dngA) [Answer] # [Perl 5](https://www.perl.org/), ~~236~~ ~~224~~ ~~222~~ ~~214~~ 190 bytes * minus 24 bytes, thanks to: good old time! ``` sub g{my$m="--"x($n=-2+pop);$m?"$m--.\n.-@{[g($n)=~s/\n/ |\n| /gr]} |\n'$m-'":$n?">":"--.\n<-'"}sub f{$a=g$p=pop;$z+=(1,$p,-1,-$p)[($#_+=(substr$a,2*$z,1,$_)=~/[.']/)%4]for$_[$z=0]=~/./g;$a} ``` [Try it online!](https://tio.run/##bc3BToNAEAbgu0@xWccAdhdsbTUprjUeevBm4g0IWS1gU5jdLCVWWnx1XDwoB2@Tf75/RmemXPR93byS4lh9QiUo5/TgAgo@m2ilvRCqFYWKcz9Gnz8co8IuPfFVBzEG5BTjiQSFSbphdKxz6BJwRe/pkv507mzSDffzI0hRgBb2agjtRLhTBprxKeOgvciF89RmVtZ7A5LNLqFlVqT2VxD5ThJ4F/MkVwbSCFpxldjYD4oQZNdrs8W9m7tOjXKXSaMa3DhDlREaY4zUI7ZI3Lnv33rh2S9HpTZlVkn8F7ObsX15z56b7dvu0agPXKvDU1Pp2mFk8dcbaV1mss5QWXA9Av03 "Perl 5 – Try It Online") I have derived this from my Python answer. Function `g` makes an empty snake, function `f` fills in the string. Here is the same code with a little more spacing for better readability: ``` sub g{ my$m="--"x($n=-2+pop); $m?"$m--.\n.-@{[ g($n)=~s/\n/ |\n| /gr ]} |\n'$m-'":$n?">":"--.\n<-'" } sub f{ $a=g$p=pop; $z+=(1,$p,-1,-$p)[($#_+=(substr$a,2*$z,1,$_)=~/[.']/)%4] for $_[$z=0]=~/./g; $a } ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~193~~ ~~192~~ ~~190~~ ~~188~~ ~~187~~ ~~182~~ 177 bytes ``` s=>n=>s.map(c=>a[d*=/[.']/.test(a[z-=d])?d*d<5?n:-1/n:1,z]=c,d=z=-2,a=[...g(n)])&&a g=(n,m)=>--n?(m="--".repeat(--n))+`--. ${n?`.-${g(n).split` `.join` | | `} | '`+m:"<"}-'`:">" ``` [Try it online!](https://tio.run/##jc47a8MwFIbh3b/CiBBLiaTQS1IwkQ0dOnQrdHMNEpacOrHPMZbTllx@uxt3a8nQ6cAHz8vZmg/ji65qewFo3VCqwasEVOJlY1paqMRkdqYWmYzyheyd76nJDkLZnKV2ZtfLFGJxs4D4hh9yVXCrDkrccqMyKeWGAsvZdGqCjaLAG6YSISCljSJCENm51pmeXibG5loIGUyOkGopJsdRSt/WVa8DLbdYgQ5PwSnU58uJ9LyJyZqcRaRjkpChxC6kVYhlmN3zJV/xh5yFBYLH2skaN7Sk4zuRB7NzpsM92ChntGI/ZUoIm5M3ICz4FVpdjwCirV1j4Hriinh9dy/7qtg9dvgJT/j1vG9aP@rlf3RbO@Md4Aju/oLhGw "JavaScript (Node.js) – Try It Online") Now even shorter than Arnauld's excellent answer! * Minus 5 bytes thanks to noodle man! * Minus 5 bytes by clever improvement thanks to Arnauld! This answer has been derived from my Python solution. Function `g` makes an empty snake and function `f` updates it with the chars from string `s`. The function has to be called by `f(s,n)` and returns a plain array of single char strings. [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 332 321 317 281 273 257 bytes ``` func R(C){r=++c<A*A?length($1)<c?i<A?C:S%2?"'":".":substr($1,c,1):S%2?"<":">";g[x,y]=S%2?G r:r G}func f(){for(x=c=S=i=0;i<A=$2;R(B="-",G=++i<A?B:""))y=i;while(S++<=A){for(i=S;i++<A;R("|",G=i<A?" ":B))x+=t=S%2*2-1;for(i=S;i++<A;R(B,G=i<A?B:""))y-=t}return G} ``` [Try it online!](https://tio.run/##XU7dboIwGL3nKZpGs1ZwUbe5BOgMmMxkyS4mu3NeMCxaxGIKRIzj2dkHuDnXq55zvvPjH7ZVFeYyQHMypSfFdD2wnZ4ziblcZxvSGVI7mAjbmUxNrzua4Bts4ltspvlnmimQjcAY0layQXrC1npRGMclq6kZUqZCs7IpCAk9hYkiBQuYxwQbWBDLOiNrTlyG@9iYQXnd5JoYU3pkwjpsRMyJp@s2c1qzYJ4lADvgwl@1p3ZghE2X0kJnWd3bG/WH1v9r93x7Tu@zrFQ8y5WEfdVJQ/D2SsgMdQYGxOGGefUzJQoG0xvYZg4sJGzYjSCats4fMarFqBEjENvEkOBuio31QhjRkv7eNxqBMQ1TXhbA/YcEuqxS6W@5r5JcrtC99hc9XKHxFXrUZJKsYr7zJbgu/7H2vuFvuQi2rkoO8jkpXvLdPoWsfcz9lMsE3X0D "AWK – Try It Online") * -11 bytes, replaced `condition ? var = val1 : var = val2` with `var = condition ? val1 : val2` * -4 bytes, replaced `function` with `func` * -36 bytes, thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). Chained `=`, chained ternary operator and other optimization * -8 bytes, thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) * -16 bytes, thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). Passed ternary operator as second arg for `func R(C)` and moved incrementation of `c` in same function to allow more efficient one-liner loop. --- ## Ungolfed ``` function result(string2) { rep = string2 if ( i == $2-1 ) step % 2 ? rep = "'" : rep = "." if ( length($1) > cpt ) rep = substr($1, cpt+1, 1) if ( cpt == ($2 * $2)-1 ) step % 2 ? rep = "<" : rep = ">" return rep } function snakearound() { x = 0 y = 0 cpt = 0 step = 0 for(i = 0; i < $2; i++) { grid[x, y] = result("-") if (i+1 < $2) grid[x, y] = grid[x, y] "-" cpt++ y++ } y-- while(step <= $2) { step++ step % 2 ? tmp = 1 : tmp = -1 for(i = step; i < $2; i++) { x += tmp grid[x, y] = result("|") i == $2-1 ? string = "-" : string = " " step % 2 ? grid[x, y] = string grid[x, y] : grid[x, y] = grid[x, y] string cpt++ } for(i = step; i < $2; i++) { y -= tmp grid[x, y] = result("-") i == $2-1 ? string = "" : string = "-" step % 2 ? grid[x, y] = string grid[x, y] : grid[x, y] = grid[x, y] string cpt++ } } for(i = 0; i < $2; i++){ for(j = 0; j < $2; j++) printf("%s", grid[i, j]) printf("\n") } } ``` ``` [Answer] # [Perl 5](https://www.perl.org/), 255 244 bytes ``` sub r{$a='';$a.=$/while s/.$/$a.=$&;''/emg;$_=$a}sub f{($s=pop.'-'x--($n=2*pop)**2)=~s/.\K/-/g;$k=local$_=($"x$n.$/)x$n;r while s@ +$|>( )+@$_=substr$s,0,-1+length$&,'';s/^-/$k&2?"'":'.'/e;$k++&1&&y/-/|/;"$_>"@me;$n&2&&y/>/</||r&r;s/.\K.//g;r} ``` [Try it online!](https://tio.run/##LY5bS8NAEIXf/RVDGHZzHxvwguvWIuiDPojgo1hiTZvQdBN2U9vS1L8ep9WBYZjDfGdOW9j6Yhjc@hPsHnMtpcI81UibsqoLcJQinQShpKRitVA41ZgfjsB876PTbdOmMpHbJPHR6CzkPQjDLNA/DL8/U0LMLHXdzPKaWR@9LRp2DXgoC/9/JhBhP/YBgmjCV2zvOosuPo@TUVQXZtGVKGJO5@gjIVyK7M6T3o1MORTbR5EYCbHjZz0pD6djb7Ji3YjsqI7plvreCqtOkVLiSPYwtLYyHcwBpzHIt7J4XVez5b1tNuax2T6tV617@S7sA/euKyuzkGfAlZsv@CORYN5YuIzhKoZrNfwC "Perl 5 – Try It Online") Here's with newlines for better readability: ``` sub r{$a='';$a.=$/while s/.$/$a.=$&;''/emg;$_=$a} sub f{ ($s=pop.'-'x--($n=2*pop)**2)=~s/.\K/-/g; $k=local$_=($"x$n.$/)x$n; r while s@ +$|>( )+@ $_=substr$s,0,-1+length$&,''; s/^-/$k&2?"'":'.'/e; $k++&1&&y/-/|/; "$_>" @me; $n&2&&y/>/</||r&r; s/.\K.//g; r } ``` I'm sure there are glaring opportunities to golf it further, but at least, for now, it's decently competitive with other answers, considering sigils. I was more interested to play with algorithm -- the square-ish string is actually rotated while being filled. Replace `r while...` with `print && r while...` to see intermediate steps. P.S. It's funny to watch how snake's head moves and serves as anchor where to place the next fragment. **Edit:** Just a little bit shorter. Rotation subroutine is also slightly less ugly and can now handle rectangular (not just square) shapes (but of course there ought to be Perl golfing pre-fab somewhere for the purpose, 20-odd years old, so I'm re-inventing the wheel), which fact was immediately used and lead to another couple bytes off. In fact `local` can be ditched (-5) and TIO's footer written so that the `$_` doesn't hold read-only value while testing. And further couple bytes less if string is temporarily padded with arbitrarily large number of hyphens (`1E6`, say) instead of value computed from `n`. But I'm not that much desperate, yet :) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 86 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` LR·<€D¬šIõ¹·nи«'-ýŽ9¦S.Λ¶¡ιн»¶«„ -‚Dð¶:«D'-'|::2äε„|-‚D'|„.'Nè::¹N+ÉiNi'''<.;ë¨'>«]J ``` Inputs in the order \$n,S\$, where \$S\$ is a list of characters. Outputs with two trailing newlines. If this is not allowed, a trailing `¨` or `?` could be added so it'll output a single trailing newline instead. [Try it online](https://tio.run/##yy9OTMpM/f/fJ@jQdptHTWtcDq05utDz8NZDOw9tz7uw49Bqdd3De4/utTy0LFjv3OxD2w4tPLfzwt5Du4Gs1Y8a5inoHm561DDL5fCGQ9usDq12UddVr7GyMjq85NxWoGwNVFa9BsjRU/c7vMLK6tBOP@3DnZl@merq6jZ61odXH1qhbndodazX///mXNFKxUo6SnlAnAjE2UCcCmUXAXE@EJdC5VOUYgE) or [verify all test cases](https://tio.run/##ZY/PSgJRFMb38xSXS3AXjSP0l6bBIExIQikrAhO6Ohcc1HsHZwZbuBB3vUJBIEQYI9JGLWI25@JWfAZfZLqWm3J1zu/7zvk4p0y9alyhPkqhirCZITxadhiyLHSSz2j4lLuB75kIH@kazge@IgX67V3hCt5wfHYBE2vRHaRhMO3dyBEMYcLnHxCShIym0QG8FozZE4yhN/ucR/ClunDReUYJ2V10HtPyHcYmhGmSIG3T3JIvs5Fy2yuXtBUYJCf7pgnD3KZ8cHIOIcQyDmUIfZKCsJSNsXGta8tbtVbVqTPUZNRGDtdsoSGUFK6f/H1pVf59aaGNn1nO4uKOjj1Oa4w2RcBtXNKKu2vK3pqyv6aoHC6EXWcNylc7f1ilXlbZeeBUasdN0eIZcZ8NGq639LZ17NYZ9RgXCr8B). **Explanation:** *Step 1: Prepare the input character-list by joining by `-` and adding additional trailing `-`. Then use the (modifiable) Canvas builtin to put this string itself and all spaces at the correct positions in the output rectangle:* ``` LR·<€D¬š # Create the list of lengths for the Canvas builtin: L # Push a list in the range [1, first (implicit) input-integer] R # Reverse it to range [n,1] · # Double each inner value < # Decrease each by 1 €D # Duplicate each value within the list ¬š # And prepend an additional copy of the first/largest item Iõ¹·nи«'-ý '# Create the string to draw for the Canvas builtin: I # Push the second input-list of characters ¹·n # Push the first input, double it, take the square of that: 4n² õ и # Create a list with that many empty strings "" « # Append it to the input-list '-ý '# Join this list with "-" delimiter Ž9¦S # Create the list of directions for the Canvas builtin: Ž9¦ # Push compressed integer 2460 S # Convert it to a list of digits: [2,4,6,0] .Λ # Use the (modifiable) Canvas builtin with these three options ¶¡ιн» # Remove all (0-based) odd-indexed rows ¶¡ # Split it on newlines ι # Uninterleave it into two parts н # Pop and only leave the first part » # Join it back together by newlines ``` [Try just step 1 online.](https://tio.run/##yy9OTMpM/f/fJ@jQdptHTWtcDq05utDz8NZDOw9tz7uw49Bqdd3De4/utTy0LFjv3OxD2w4tPLfzwt5Du///N@eKVipW0lHKA@JEIM4G4lQouwiI84G4FCqfohQLAA) [For more information on how the Canvas builtin works, see this 05AB1E tip of mine.](https://codegolf.stackexchange.com/a/175520/52210) [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ž9¦` is `2460`. *Step 2: Replace all `-` that are currently at edge or corner positions with `|`:* ``` ¶« # Append a trailing newline „ - # Push string " -"  # Bifurcate, short for Duplicate & Reverse copy: "- " ‚ # Pair them together: [" -","- "] D # Duplicate it ð¶: # Replace all spaces with newlines in the copy: ["\n-","-\n"] « # Merge the two together: [" -","- ","\n-","-\n"] D # Duplicate it '-'|: # Replace all "-" with "|" in the copy: [" |","| ","\n|","|\n"] : # Replace all [" -","- ","\n-","-\n"] respectively with # [" |","| ","\n|","|\n"] ``` [Try the first two steps online.](https://tio.run/##yy9OTMpM/f/fJ@jQdptHTWtcDq05utDz8NZDOw9tz7uw49Bqdd3De4/utTy0LFjv3OxD2w4tPLfzwt5Du4Gs1Y8a5inoHm561DDL5fCGQ9usDq12UddVr7Gy@v/fnCtaqVhJRykPiBOBOBuIU6HsIiDOB@JSqHyKUiwA) *Step 3: Replace all `|` at corner positions with either `.` (for the top halve) or `'` (for the bottom halve):* ``` 2ä # Split the string into two equal-sized parts ε # Map over both parts: „|- # Push string "|-" ‚ # Bifurcate and pair again: ["|-","-|"] D # Duplicate it '| : '# Replace all "|" with the following in the copy: „.'Nè '# The map-index'th character of string ".'" : # Replace all ["|-","-|"] respectively with # [".-","-."] for the first iteration of the map # or ["'-","-'"] for the second iteration of the map ``` [Try the first three steps online.](https://tio.run/##yy9OTMpM/f/fJ@jQdptHTWtcDq05utDz8NZDOw9tz7uw49Bqdd3De4/utTy0LFjv3OxD2w4tPLfzwt5Du4Gs1Y8a5inoHm561DDL5fCGQ9usDq12UddVr7GyMjq85NxWoGwNVFa9BsjRU/c7vMLK6n@s139zrmilYiUdpTwgTgTibCBOhbKLgDgfiEuh8ilKsQA) *Step 4: And finally, fix the `>` or `<`*, and output the result: ``` i # If ¹N+ # the first input + the (0-based) map-index É # is odd: Ni # If it's the second iteration of the map: '' '<.; '# Replace the first "'" with "<" ë # Else (it's the first iteration of the map) ¨ # Remove the last character of the first part '>« '# And append a ">" instead ] # Close both if-statements and the map J # Join the two modified parts back together # (after which the result is output implicitly with trailing newline) ``` [Answer] # [Java (JDK)](http://jdk.java.net/), ~~279~~ ~~278~~ 276 bytes ``` char[]f(String s,int n){var a=g(n).toCharArray();int z=0,d=0;for(var c:s.toCharArray()){d+=a[z]/2&1;a[z]=c;z+=(d%2<1?1:n)*(d%4<2?2:-2);}return a;}String g(int n){String m;return n>1?(m="--".repeat(n-2))+"--.\n"+(n>2?".-"+g(n-2).replace("\n"," |\n| ")+" |\n'"+m:"<")+"-'":">";} ``` [Try it online!](https://tio.run/##dZBRb5swFIXf9yuuLG21S2AN7aQJx4m2SXvo25S9pXm4A4fSwDWyTbom5bdnJqFa@1AkxDXnO5zDfcAdxg/F9pjX6BwsCbcaDsf8Hu1qveFLbysqwU0q8kDisEMLqEpOIvHmR4C@WYtPXMhB36urSaGu5MZYPoB55t5S4lBEClf79ef001QOg8rlPlK8@JjOpotpRuIyzDezdJFmcSpkb7XvLAHKfmxS8rHJeG7kiNB8uuCNYnHMEqtbjZ5T@ISIwpvkjljEaZ4uWBKzqDwpA1VjrjkL6oTB8x09Awv8MF2wqMnYbDjGFyxjcyb7I0Brqx16Dc6jr3LYmaoAr53/vyc414PDBwjX8sl53SSm80mwkq@Jk348b5mLZMODgYSQ78EnpQ932/2pQ@Dr3AYrGnNXa0BbupfUsH84ralSNxIqmMHX8Igice7K3BCP1nRUsFB4jH/HpdIXGxlT1LpBemU6K7/v9a@uyrffrXmkn@bvbde0LlBf3lBtrdFpMkG4Hn@sP/4D "Java (JDK) – Try It Online") I have derived this from my JavaScript answer. Java is not really good for code golf, but I think, the result is not too bad. * minus 3 bytes, thanks to ceilingcat [Answer] # [Haskell](https://www.haskell.org/), ~~333~~ 289 bytes ``` f s n=h s n 0 0$concatMap(++"\n").g$n h(c:t)n d z m=take z l++c:drop(z+1)l where e=mod(d+sum[1|a<-".'",m!!z==a])4;l=h t n e(z+2*[1,n,-1,-n]!!e)m h _ _ _ _ m=m g 1=[">"] g 2=["--.","<-'"] g n=(m++"--."):(map(++" |").h)b++["'-"++m++"'"]where b=g(n-2);m=b>>"--";h(l:k)=[".-"++l]++map("| "++)k ``` [Try it online!](https://tio.run/##bZBfS8MwFMXf@ynuwmCJacs6p0K37MEHH8Q9iL7VIlmbraPJTekfJmPfvaZOdA8jEG5@nHvOIYVsSqV132@hARTFcMMUpuPMYibbtawo5@QDCQt3Y/QKmsUtQ8jhCEa0slRu0JxncV7bih55xDQcClUrUMLYnOa86UwSneQyIOGE@GY0OgohUzZfaJfWujTl1mY3SeSjH0R@gOlopJjxCvj8PUYYbweRSMiKpG6auSkIQuKTZTD5ISiocTUHyGJqzqXh5EoXbMN5QiYB4XyQOP253kbsKAYztjBis1q5VbIoqI5L5szDQa1Tt@GcyAnci5W9kXsUjqyh6tq3tn5BSDwAugXSoPsJWdsOcwJz5l/Dd9fx/XX88IfR2lwrI/HS@QL@G7wX6rXbZ@VjbQ/4ZL@eO1M1l8GVVrJRaAncsrT/Bg "Haskell – Try It Online") Function `g` makes an empty snake as a list of strings. Function `h` fills in the given string `s` while converting the list of strings to a single string. Function `f` is the resulting target function. In function `h`, `d` is the direction where to go for the next character of string `s` and `z` is the position of the character to replace. ]
[Question] [ Given a sorted array of unique positive integers \$A\$ \$(A\_0<A\_1<\cdots<A\_{n-1})\$, and an integer \$t\$, where \$A\_0\le t\le A\_{n-1}\$. Output the value \$i\$ such that: * If \$t \in A\$, \$A\_i=t\$. * If \$t \notin A\$, \$ \left(i-\left\lfloor i\right\rfloor\right)\cdot A\_{\left\lceil i\right\rceil} +\left(\left\lceil i\right\rceil - i\right)\cdot A\_{\left\lfloor i\right\rfloor} = t \$. In other words, linearly interpolate between the indices of the two elements of \$A\$ that most narrowly bound \$t\$. In the above formula, \$\left\lfloor i\right\rfloor\$ means rounding \$i\$ down to integer; \$\left\lceil i\right\rceil\$ means rounding \$i\$ up to integer. You may also choose 1-indexed array, though you need to adjust the formula and the test cases below accordingly. ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins. * Floating point errors in output are allowed, but reasonable floating point precision is required. For testcases listed here, your output should be correct with at least 2 decimal places precision. * Fraction output is allowed as long as fractions are reduced to their lowest terms. * It is fine to use any built-ins in your language. But if built-ins trivialize the question, consider submitting a non-trivial one too. ## Testcases ``` [42], 42 -> 0 [24, 42], 24 -> 0 [24, 42], 42 -> 1 [1, 3, 5, 7, 8, 10, 12], 1 -> 0 [1, 3, 5, 7, 8, 10, 12], 7 -> 3 [1, 3, 5, 7, 8, 10, 12], 12 -> 6 [24, 42], 33 -> 0.5 [24, 42], 30 -> 0.3333333333333333 [1, 3, 5, 7, 8, 10, 12], 2 -> 0.5 [1, 3, 5, 7, 8, 10, 12], 9 -> 4.5 [100, 200, 400, 800], 128 -> 0.28 [100, 200, 400, 800], 228 -> 1.14 [100, 200, 400, 800], 428 -> 2.07 ``` [Answer] # [Python 2](https://docs.python.org/2/), 59 bytes ``` f=lambda l,t,p=0:l<[t]and 1+f(l[1:],t,l[0])or(t-p)/(l[0]-p) ``` [Try it online!](https://tio.run/##fY7RboMgFIbvfYpzV0jRAdLpTN1T7M6ZBSNdTRgapev29N1Bu6Vp4kg44fz/x3/O8O2PvZOXQ/mK1@qPptVgmWdDyQu7r3ytXQtieyC2EkWNhq14TfuR@HigDyR0@Licj501IIoINIMGShj1@a1zw8kTmkyD7TzZQPwMGxphPDgkzKe2RGPfO4Noa75Mi/LLeDIReD2@G/9LNRS2t1gEo5nQxK0YHGyvPXEUk4axcz54DHQzkWtIHBQKexAm3l0qJWsGSoZteFRJFRpUpLpXFkZElWCQMtgxyBjkDATHGwBx/bHmZ8FP//k/D3i8GZmmc2Syu9X4oqV3Zz1X/oWsEU@BUDPBUZOhqFByzufF8iVC5iuEXAiRCLVCqIWQCc9@AA "Python 2 – Try It Online") Outputs one-indexed. Recursively loops through the list element , each time adding `1` to the eventual index output, until reaching an element that's at least `t`. Then, outputs the fraction of the way `t` is between the current element and previous element `p`. This avoids needing to explicitly track which index we're at. **62 bytes** ``` lambda l,t:sum(t>y or(t-x)/(y-x)for x,y in zip([0]+l,l)if x<t) ``` [Try it online!](https://tio.run/##fY7RboIwFIbveYpzZxsLa0udzKhPsTtmlhLLbFILgTphL89acIsxwSY9yfn/7/zn1L07VZYP5e5jMPJcHCUY4jbt5YzcvoeqQS7u8AvqfS2rBjrSg7bwo2uU08PSEIN1Cd3W4eF60kYB20QgCRSwg0ZeP7WtLw7hpK2NdmgB8R4WOPI7wHpCfUuDpO8rqzx6VJ06evm9uagInGy@lPujCgzLeyyCRrXeLJHPKk0lHbLYJ9WNti54BGTRoltIHBQMW2AqXg254AcCgodraJRzERqvcPGoTAyLckYgJbAisCaQEWDU/wCw28Scvw5@@mR@XPB6tzJNx8hkda/RSUsf3nwu/w@ZI94CIUaCeo2HIkLJKB0Py6YIns0QfCJYwsQMISaCJ3T9Cw "Python 2 – Try It Online") One-indexed. Same idea as the 64-byte code below. Interprets the input as "intervals" `(x, y)` of two consecutive elements of the list, starting with left endpoint `0`. The output is the sum over each interval of the fraction of it that's less below `t`, which is `1` for intervals fully below `t` and `0` for those fully above it. ``` lambda l,t:sum(min(1,max(0,(t-x)/(y-x)))for x,y in zip([0]+l,l)) ``` [Try it online!](https://tio.run/##fY7RboMgFIbvfYpzV0jRAeLqmnVPsTvXLJjiSoJolK52L@9Au6VpYkk4yfn/7/zntBd3bCwfq93HaGRdHiQY4rb9qUa1toiRWg6IEuTiAT@hi68YV00HA7mAtvCjW1TQ/doQg/F4PmqjgG0jkARK2EEnz5/atieHcNK3Rju0gvgNVjjyW8B6Qn1Lg6TvG6s8elCDOnj5vTupCJzsvpT7o0oM61ssgk713qyQz6pMIx2y2Ce1nbYueARk2aNrSBwUDK/AVJyNheB7AoKHa2hUcBEar3Bxr8wMiwpGICWQEdgQyAkw6n8A2HViyd8EP30wPy14vlmZplNkkt1qdNbSu7ecy/9DloiXQIiJoF7joYhQckqnw/I5gucLBJ8JljCxQIiZ4And/AI "Python 2 – Try It Online") The summand is `(t-x)/(y-x)` clamped between 0 and 1. [Answer] # [Python](https://www.python.org) 3.10, ~~79~~ ~~75~~ ~~67~~ ~~65~~ 59 bytes ``` lambda a,t:(t-a[i:=sum(x<t for x in a)])/(a[i]-[0,*a][i])+i ``` [Attempt This Online!](https://staging.ato.pxeger.com/run?1=fZBBboMwEEXVbU4xyspODR0bp1AS9wTZdUlZOCqoSAQQOCQ9SzeRqvZO7WmKcVRFkaglj2b-vPlj-f2reTOvdXX6yNXz597kXvS9KvVu-6JBMxMT4-mkiFW335Hj2kBet3CEogJNU3pHhl7qJcgWOh0yelucLZ4st7Fc3WQVQRpnrFcbv2vKwpA5eI8wp6umLSpD2ljlZJH1uiQZpewQqzHvKdPbjrTega59RE6d9ennpkukSBlIYW1wlghpi0ER8lpxDJ8lnEHAYMkgZBAx4DhcC_DzxFQ_tP3gn_lxwf3FyiAYLf3lpYZOC67OtK_4M5kiHiwhRwIHTdggbYgQx4dFzkJEE4RwBPe5nCCkI4SPofv8Xw) Needs Python 3.10 to use `:=` inside a subscript. * `t-a[0]and` guards against the edge case where `a` has only one element * `sum(x<t for x in a)` finds the index of the first item `x` where `x<t` * `(t-a[i]/(a[i+1]-a[i])+i` just does the linear interpolation -4 bytes thanks to Kevin Cruijssen -6 bytes thanks to tsh -6 bytes thanks to xnor [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` YYhtfi3$Yn ``` Inputs are *A*, then *t*. The output is 1-based. [Try it online!](https://tio.run/##y00syfn/PzIyoyQt01glMu///2hDAwMdBSMQYQIiLAwMYrkMjSwA) Or [verify all test cases](https://tio.run/##y00syfmf8D8yMqMkLdNYJTLvv0vI/2gTo1guEyOuaCMTHQUQ28gEwQaJG@ooGOsomOoomOsoWOgoGBoAMVDKEKeMOW49SNYYGyOxDXBqwe0AS6CMAZBtBCJMQISFgQHIDgvsEka4JEyMLAA). ### Explanation ``` YY % Push infinity h % Implicit input: row vector A, of length n. Concatenate. This attaches % infinity at the end of the vector. This is necessary because % interpolation requires a vector of at least 2 entries. The value % infinity is used so that it doesn't interfere with the interpolation tf % Duplicate, find. This gives the row vector [1 2 3 ... n+1] i % Input: integer number t. 3$Yn % 3-input linear interpolation. Implicit display ``` [Answer] # JavaScript (ES6), 45 bytes Expects `(t)(A)`. ``` t=>g=([c,...a],p=0)=>t>c?1+g(a,c):(t-c)/(c-p) ``` [Try it online!](https://tio.run/##hdLBDsIgDAbgu0/BEWLHoKBDE@aDLB4W1EVjZHGLrz/ZdpIt0gRO/fKXhkf9qTv3vrd99vKX63CzQ2/LxtLKAee8PkNrBbNlX7qT3Da0BseOtM8cy6nLWjY4/@r888qfvqE3qpHRSuOZMbJSeU7E5hegDgA1kFW0AqaEf0BGQIZ@CUQB2QEpgBggUoQz85WEIgVUnID/RAD7CCiVejTfxUQkiYoq3nRyD4vQQ4roBZFoRiRCG46XHi8jxDz0lIImnixlJJd68Q0SBrkohi8 "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/) + numpy, 52 bytes ``` lambda a,t:interp(t,a,argsort(a)) from numpy import* ``` [Try it online!](https://tio.run/##fY5NbsMgEIX3PsUoK4ioxV9iN5F7gtzA7YK2uLWEAWFqKad3jYmqKJKLxKB58703@Gv8dlbMXfM6GzW8fypQJJ56G3XwKBJFVPgaXYhIYVx0wQ1gfwZ/hX7wi7qf83sT1QjWF50LcIHegvPaIopPmkzNpRy96SPawdML7PA5NB3a60kZpDE@@7BsRIFYXypjPowb9dKt4wljPLeSvxGQPJlp0XKZmkXh8lHJDCtaRkAQOBCoCNQEGF1uAtjNsTWv0lz8418XHO9WCrFGlod7jWZNPJztXP4XskU8J0KuBF00nopMpaZ0/VidI3i9QfBMsJLJDUJmgpe0@gU "Python 3 – Try It Online") As `a`is sorted with no duplicates we can use `argsort` to save a byte over `r_[:len(a)]`. Note that the "no duplicates" is important because numpy doesn't use timsort by default but an unstable qsort. # or (same length) ``` lambda a,t:interp(t,*unique(a,1)) from numpy import* ``` [Try it online!](https://tio.run/##fY7dasQgEIXv8xTDXmmwwb9t0l3SJ9g3SHthW0MDRq35gX36NMalLAup4Mic@c4Z/XX8dlYsbf22GNV/fClQZDx1dtTBo5Hkk@1@Jo0UYRhnbXA92Kn3V@h678KYL@m9iWoA67PWBbhAZ8F5bRHFJ03m@lIM3nQjOsDTKxzwOdQtyvWsDNIYn31YN6JArC@UMZ/GDXrttvGMMV4ayd8JSB7NNGu4jM2qcPmoJIZlDSMgCBwJlAQqAoyuNwLs5tibl3Eu/vFvC57vVgqxRRbHe40mTTyc/Vz@F7JHvERCbgRdNR6LjKWidPtYlSJ4tUPwRLCCyR1CJoIXtPwF "Python 3 – Try It Online") This uses `numpy.unique` (which is a nop on `a` since `a` has sorted unique values) with the `return_index` switch set. This returns the indices of the unique values v in the input. As `a` has sorted unique values this returns 0,1,...,len(a)-1 [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), ~~18~~ ~~17~~ ~~13~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` -D¹¥/ā+s®›Ïθ ``` First input is the list \$A\$, second input is \$t\$. The output \$i\$ is 1-based. -1 byte switching to the legacy version of 05AB1E, where `[1]/[]=[1]` instead of `[]`. In the new version of 05AB1E we therefore had to add a `1š` before the `θ` to account for single-item input-lists. Unfortunately, `d` was `is_int` instead of `>=0` in the legacy version, so we have to replace it with `®›` (`>-1`) instead, netting at -1 byte. [Try it online](https://tio.run/##yy9OTMpM/f9f1@XQzkNL9Y80ahcfWveoYdfh/nM7/v@PNjQw0FEwAhEmIMLCwCCWy8TIAgA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfWVCsUvof12XiENL9Y80ahcfWveoYdfh/nM7/utoxvyPjo42MYrVAWGF6GgjEzDLyASZB5Uz1DHWMdUx07HQMTTQMQSKGSIJmyOEzbELG6LYYGyMwjPArscIu7AlRNjAQEfBCESYgAgLAwOQJRY45YzwyJkA5WIB). **Explanation:** ``` - # Subtract each value in the first (implicit) input-list from the # second (implicit) input-integer D # Duplicate this list ¹ # Push the first input-list again ¥ # Pop and push its deltas / forward differences / # Divide the items at the same positions in the two lists ā # Push a list in the range [1,length] (without popping) + # Add that to each value in the list s # Swap to get the duplicated list again ®› # Check for each whether it's larger than -1 (non-negative) Ï # Only keep the items at the truthy indices θ # Pop and leave the last item # (after which the result is output implicitly) ``` [Answer] # [R](https://www.r-project.org/), ~~57~~ 55 bytes Or **[R](https://www.r-project.org/)>=4.1, 48 bytes** by replacing the word `function` with `\`. *-2 bytes thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).* ``` function(A,t,r=which(A>=t)[1])r-((A-t)/diff(c(0,A)))[r] ``` [Try it online!](https://tio.run/##fY7BCoMwEETv/YqFXhJYbbKJmB4U8h3iyRL00oKk9POtUQNVGgNZyMzLzI6Tqyb3fnZ@eD2ZRY9j9emHrme2rjxvZMvHjDGbeX57DM6xjgm0nPNmbKfw0sQR5nGFrAZ5CRLpRUEg/VeONC2yRFAIBUKJYBCkmG@g5O/fFFSukD5P2vrK/RpKbQ15cTBENNThnNbQPi6F3VesiJiYDQpDh2GEWDY2MYxMGqOIUS51GtMRU7kopy8 "R – Try It Online") 1-indexed. I couldn't make any built-in linear approximation work, but ~~it doesn't mean that such solution doesn't exist~~ [@Dominic van Essen could](https://codegolf.stackexchange.com/a/237244/55372). [Answer] # [Haskell](https://www.haskell.org/), 42 bytes ``` q 0 q p(h:r)t|h<t=1+q h r t|d<-h-p=(t-p)/d ``` [Try it online!](https://tio.run/##fZDBDoIwEETvfsUcPJTYxlJqRAOf4BcgB6JijdUU2CPfbi3qRRN72MlOXiazWdMM15O1vi33voOcdXDMbPuERlNQmS46GPSg8VgII1zJSLhkefR0GmhAiYpVWtUcWiUcrFJ6WoNX@tt/eMqRcaw41hw5RyrDTDiN0nU8@1OdZT9eRuPxwzZvKoNXk@hJcilfvfl/qGJQB1jPbs3lHj54a9wOrr/cCXNULSwII5jloASFwOvTtX8cWtucBy8Ozj0B "Haskell – Try It Online") Main function is `q 0`, outputs one-indexed. **43 bytes** ``` l%t|let(h:r)?p|h<t=1+r?h|d<-h-p=(t-p)/d=l?0 ``` [Try it online!](https://tio.run/##fZDBasMwEETv@Yo5JCARicqyStxi4S/oFxgfTGJHoUoQ9h797VXltJcEosMOOzyGWdb18/fgfYx@R4sfiLnPiTdhcTXZYj81bjnV0slgGcnA307WNyqOlu34hoaZZli0rDW6EzCaC7BWm3VNXptH/88LgVLgXeAgUAkUKs2Kiyw95LNP1WX55FU2nj/s44@q5PUqZpVKqXtv9RrqHDQJdptrf7mlD1778IUwXW6ELdoRHoQFzAsQRy1x/3QXf46j789zlMcQfgE "Haskell – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes ``` IΣEθ∧κ⌈⟦⁰⌊⟦¹∕⁻η§θ⊖κ⁻ι§θ⊖κ ``` [Try it online!](https://tio.run/##fY0xC8IwEIX/yo0XOKGxiIOT2MWhIDiGDCEJNNhETdPSfx/PunsHx@PxvXd2MNk@zVjrLYdU8GKmgvc5Ym9e@CY4J4cPgt6sIbKrGtYh/bQk6MISnEe25gkHxss1Ob9@k5232UefiucGIcQWZCr8pYTm3eZUq1J7gpbgQHAkkPxPtppPo@tuGT8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @xnor's 64-byte Python solution. ``` θ Input array E Map over elements κ Current index ∧ Logical And η Input value ⁻ Minus §θ⊖κ Previous element ∕ Divided by ι Current element ⁻ Minus §θ⊖κ Previous element ⌊⟦¹ Clamp above to 1 ⌈⟦⁰ Clamp below to 0 Σ Take the sum I Cast to string Implicitly print ``` [Answer] # [Perl 5](https://www.perl.org/), 75 bytes ``` sub f{($t,$a,$b)=(@_,9e9);$a<=$t&&$t<=$b?($t-$a)/($b-$a):1+f(@_[0,2..$#_])} ``` [Try it online!](https://tio.run/##jZJLb4JAFIX3/ooTOwrYKw7DWEVLdd@kbrqzxEAKjX2IRZq0Mf52OjO46EOjCcyd3PPdc@5i1mnx2q@qzUeCbGuzklhMLHFCe7qgIA2cMYuvQ1a226xUNZkopMtip2ezRNeRd5kpdM5JuC67WETOrsrywm4Ac/VJERGkQHgDDkS0bwupu0oS8qhUT3k/JI/gE/qEAWFI8Lj6Nen99TgGDjTon@Nosq8OreX7Js3tHxS52bl3Tob473MMDTQqf6NciUIfUh9Dzs3aw9pU1ROoqFHP9eQpVNaocPnAoM5W0W9fNouLgvSDST/XTjhli7Hpgz3lZZjppzTViKPb62K5KrNmqxtsgFZXcFXKEVr@IwA1r66qAzWpbw@rpt4I0NZI340lJrDyFwsjWJ1O5252j9mtVWPP@XJlW2TtAwkq28ySmRw3do3qGw "Perl 5 – Try It Online") Perl5 versions from 5.32 (TIO has 5.28) got [chained comparisons](https://metacpan.org/release/XSAWYERX/perl-5.32.0/view/pod/perldelta.pod#Chained-comparisons-capability) capability which means `$a<=$t&&$t<=$b` can be shortened to `$a<=$t<=$b` and save 4 bytes. [Answer] # [Ruby](https://www.ruby-lang.org/), 50 bytes ``` f=->l,n,z=0{a,*l=l;a<n ?1+f[l,n,a]:1.0*(n-a)/a-=z} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y5HJ0@nytagOlFHK8c2xzrRJk/B3lA7LRoknhhrZahnoKWRp5uoqZ@oa1tV@79AIS062sQoVgeIucAcIxMQW8fYGMo3NDDQUTACESYgwsLAIBbINLKI/Q8A "Ruby – Try It Online") [Answer] # [R](https://www.r-project.org/), 41 bytes ``` function(A,t)approx(B,seq(B<-c(A,0)),t)$y ``` [Try it online!](https://tio.run/##fY7BCsIwEETvfsWCHhLYlmSTkggq2D@RYsFLq7WCfn1M2gZsMQ3sHmZeZrZz9dHVr6bqb23Dztjzy/3etW9W4vP6YOUhq7wqOPfO7uNqVjFNHMGvLWQnkJsgkR4UBNJ/5UjTIEsEhVAgGASLIIWfQMnfvynIjJBeT5r6zPwMpaaGvFgYIhpq8VZraB6XwvYjVkRMeIPC0mFZIYaLbQwjm8YoYpRLncZ0xFQujPsC "R – Try It Online") Almost-trivial use of `approx` built-in: upvote [pajonk's non-trivial R answer](https://codegolf.stackexchange.com/a/237234/95126) instead... [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 44 bytes ``` Sum[(i=0;{1/(#-i),x<=(i=#)}&/@#2),{x,#}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P7g0N/p970KNTFsD62pDfQ1l3UxNnQobW6CAsmatmr6DspGmTnWFjnJtrNr/gKLMvJJoZV27NAcH5Vi1uuDkxLy6aq5qEyMdIK6t1eGqNjLRAWEoDySB4CkY6lQb6hjrmOqY61joGBroGELFzbGLGxphFzc2RjbV2ACZh0OLJS4bLIASBgY6RkBsAsQWBgYQY3BJmGCV4Kr9DwA "Wolfram Language (Mathematica) – Try It Online") Input `[t, A]`. Returns 1-indexed. The private-use character is `\[Piecewise]`, which is usually a less byte-efficient `If`/`Which`. [Answer] # [C (clang)](http://clang.llvm.org/), ~~74 71~~ 63 bytes ``` float r;f(*a,t){for(r=0;*a<t;r++)a++;r-=(*a-t)/(*a-*--a+1e-9);} ``` [Try it online!](https://tio.run/##jZR9a4MwEMb/91Mcg4HWpE1ifCPrvsg2Rii1FDo7rLBC8avPJcZKZmtqwAje77m75B7c4M1Blru2LQ5HWUMlCn8hUR1cimPlV2siFvKlFlUYBjIMRYXXKozrYKVfC4xlSLc4D0TTfsl96QcXD/ZlDfX2VH@e3z7WF4rybjXCihAd4awRqxVwBvgViBWlOso4gp5gfEywEWFyUIuITG2IEMQIUgQZAkrUYwR0nJG7@VTzkcXHD/J3DSWWIBm1HEVdC8vYYtIxQwwTjZYlydx9sNsiuVuRawX/p6DduChRENMb11tGSH/SzNRgmS2hDgkzErqk3JYwh4QbCVuS1PPAg8I3PtJXBYGA70rlKfyn5@K9fEJQqU9KRQZQnVe5aAbI3BnpAKrro3MSqmmm01w0cLGewDSYDGCCtHemK@vR9agarrKQA701Vq9UnmDzauRIWWaS5BZpTJa50moPXWk9Mhdt7HOlu7k56M45V/qMWCDucBbQ/bOyRxSdlSa/TzXt76Y4yN2pxT9/ "C (clang) – Try It Online") * Saved 3 thanks to @upkajdt suggestion to use a variable instead of printing it. * Saved 5 thanks for @ths suggestion to make divisor ~0 by adding *1e-9* to it. * Saved another 3 by using *float r* instead of *int n* as index counter. [Answer] # [Haskell](https://haskell.org), ~~76~~ ~~73~~ 71 bytes ``` s!x|(t,y:_)<-span(<x)s,u<-last$0:t=fromIntegral(length$t)-1+(x-u)/(y-u) ``` [Try it online](https://tio.run/##hY7NCsIwEITvPsUKHhLcappGrFIfwGcQkSDxB2OUJJUWfPeaKOihYA47MDMfy5ykuyitu84Nmyfx2C53tMrcXRpSNdRhXWVaOj9iS7862Nt1bbw6WqmJVuboTyNPs3xMmqymU9IG7a7ybGAF3sqHsk4Buduz8TCB2uxra1sgQ0oHABsgG8G3CIJHi8FyEV2IuOhFPypHKBBmCHOEEiFn4SKRp4B58kN/SVH0I5b6k5y6@AIsRDyKiFIy9p5R/u15ohefftu9AA) (I hate explicit conversion (in golfing)) [Answer] # APL+WIN, 42 bytes Prompts for vector followed by integer. 1 indexed. ``` (m/⍳↑⍴m)+(i-m/v)÷(m←<\(i←⎕)≤v)/v-¯1↓0,v←,⎕ ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv0au/qPezY/aJj7q3ZKrqa2RqZurX6Z5eLtGLlCNTYxGJpACatF81LmkTFO/TPfQesNHbZMNdMqA4jpAif9AU7j@p3GZGIFQGpeRiQKQNjKBM8GihgrGCqYK5goWCoYGCoZGClyGWAQVuIwxRbkMEaYaGyOYBliUYrGJyxIkZmCgYATEJkBsYWAANNICi6gRVlETIwsA "APL (Dyalog Classic) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) + `-M5.10.0 -a`, 57 bytes ``` $_>"@F"&&$p<="@F"?say$.-3+("@F"-$p)/($_-$p):0,$p=$_ for<> ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3k7JwU1JTU2lwMYWxLIvTqxU0dM11tYA8XRVCjT1NVTiQbSVgY5Kga1KvEJafpGN3f//JkYWXIYGBlxGQGwCxBYGBv/yC0oy8/OK/@sm/tf1NdUzNNAzAAA "Perl 5 – Try It Online") ## Explanation Naiive approach, but using some Perl var tricks. `-a` stores the first input value (the target) in `@F` which, since we know will only be one value, we can access via `"@F"`. With this we can loop through all other lines of input (`for<>`) checking if we're greater than the current value and if the `$p`revious was less than of equal to the target and the current (`$_`) is greater than the target then we output (`say`) the current index (`$.` holds the current, 1-indexed, line of input being processed) plus the ratio of the differences between the current and previous, and previous and target. [Answer] # [Pip](https://github.com/dloscutoff/pip) `-x`, 36 bytes ``` Yb>=_FIa#y-:$/(-[bMXy]+MN:b<=_FIa)|1 ``` Takes the array and the number as command-line arguments. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSboVS7IKlpSVpuhY3VSKT7Gzj3TwTlSt1rVT0NXSjk3wjKmO1ff2skmzAEpo1hhC1UC07opWiDa2NrU2tza0trA0NrA2NYpV0FMxhRgIA) ### Explanation ``` Yb>=_FIa#y-:$/(-[bMXy]+MN:b<=_FIa)|1 a Input array FI Filter for elements where b>=_ Input number is greater or equal Y Yank that list into y FIa Filter input array for elements where b<=_ Input number is less or equal MN: Minimum such element + Plus -[ ] Negative of each of these: b Input number MXy Max of y (elements <= b) We now have a list containing two distances: from the first element larger than b to b, and to the last element smaller than b $/( ) Divide the first by the second |1 If the result was 0 or division by 0, substitute 1 instead -: Subtract that result from #y Length of y (elements <= b) ``` ]
[Question] [ # Fermat's Last Theorem, mod n It is a well known fact that for all integers \$p>2\$, there exist no integers \$x, y, z>0\$ such that \$x^p+y^p=z^p\$. However, this statement is not true in general if we consider the integers modulo \$n\$. You will be given \$n\$ and \$p\$, which are two positive integers with \$n>1\$. Your task will be to write a function or program to compute all positive integers \$x, y, z<n\$ such that \$(x^p+y^p)\$ and \$z^p\$ give the same remainder when divided by \$n\$. # Input Any reasonable method of input is allowed. E.g. two separate user inputs, ordered pair, two function parameters, etc. # Output Any reasonable method of output is valid, it may be produced by a function or output to the screen. The order the triples are listed does not matter. Triples such as `(1, 2, 3)` and `(2, 1, 3)` are considered distinct, and all distinct triples should be listed exactly once. No invalid/trivial triples such as `(0, 0, 0)` should be output. The numbers \$x, y, z\$ may have any ordering within each of the triples, but that order should be consistent. For example if \$2^p+2^p\$ and \$3^p\$ have the same remainder when divided by \$n\$, you may list this triple as `(2, 2, 3)` or `(3, 2, 2)`. # Examples ``` n p -> Possible Output ---------------------------------------------------------------- 2 3 -> [] 3 3 -> [(1,1,2),(2,2,1)] 3 4 -> [] 4 3 -> [(1,2,1),(1,3,2),(2,1,1),(2,2,2),(2,3,3),(3,1,2),(3,2,3)] ``` # Scoring Shortest code in bytes with no standard loopholes wins. [Answer] # [Julia 1.0](http://julialang.org/), 61 bytes ``` f(n,p,q=1:n-1)=[(x,y,z) for x=q,y=q,z=q if(x^p+y^p)%n==z^p%n] ``` -1 thanks to Glen O [Try it online!](https://tio.run/##yyrNyUw0rPj/P00jT6dAp9DW0CpP11DTNlqjQqdSp0pTIS2/SKHCtlCnEoirbAsVMtM0KuIKtCvjCjRV82xtq@IKVPNi/zsUZ@SXK6RpGOkYa3LBOMaoHBMExwQo8x8A "Julia 1.0 – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 19 bytes ``` {⍸0=⍵|-/¨⍺*⍨⍳3⍴⍵-1} ``` The triples are returned in the format `x z y`. [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR7w4D20e9W2t09Q@teNS7S@tRL5DabPyodwtQVNew9n/ao7YJhJVxPeqbqgBUqWCkkKZgDOcZo/BMMORM/gMA "APL (Dyalog Unicode) – Try It Online") ### Explanation ``` {⍸0=⍵|-/¨⍺*⍨⍳3⍴⍵-1} ⍝ n is our right argument, ⍵, and p is our left, ⍺. 3⍴⍵-1 ⍝ First, we get a triple of (n-1, n-1, n-1). ⍳ ⍝ Then we get the Cartesian product of three range[1, n-1). ⍝ As you will see, this gives a list of (x z y) triples. ⍺*⍨ ⍝ We take each element of each triple to the power of p. -/¨ ⍝ Here we subtract over each triple, using (element - rest) ⍝ This gives us (x^p - (z^p - y^p)) = x^p + y^p - z^p. 0= ⍝ Then we check which (x^p + y^p - z^p) equals 0. ⍸ ⍝ And use these results, a Boolean array, ⍝ to find get the indices of the correct triples, ⍝ which are our (x z y)s. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 10 bytes -2 bytes by Kevin Cruijssen -3 bytes by Grimmy ``` <L3ãʒImÆ¹Ö ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fxsf48OJTkzxzD7cd2nl42v//JlzGAA "05AB1E – Try It Online") Returns a triples in the format `[z,y,x]`. **Explanation**: ``` <L | Push the interval [1,n) 3ã | Push the triple cartesian product [1,n) x [1,n) x [1,n) | E.g. with n = 3, the list begins as follows: | [[1, 1, 2], [1, 2, 1], [2, 1, 3], ...] ʒ | Filter the list: Im | Take the p-th power of each input | E.g. [1, 1, 2] --> [1^p, 1^p, 2^p] Æ | Reduce by subtraction | E.g. [1^p, 1^p, 2^p] --> 1^p - 1^p - 2^p ¹Ö | Check if 1^p - 1^p - 2^p = 0 (mod n), and filter out if not. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` *ŒH§%³E Ṗṗ3çƇ ``` A full program accepting command line arguments `n p` which prints a list representation of the results (Do note that the empty list is represented as no output). **[Try it online!](https://tio.run/##ASMA3P9qZWxsef//KsWSSMKnJcKzRQrhuZbhuZczw6fGh////zT/Mw "Jelly – Try It Online")** ### How? ``` *ŒH§%³E - Link 1: evaluate a triple: [x, y, z], p * - exponentiate [x^p, y^p, z^p] ŒH - split into halves [[x^p, y^p], [z^p]] § - sums [x^p+y^p, z^p] ³ - program's 1st argument n % - modulo [(x^p+y^p)%n, (z^p)%n] E - all equal? (x^p+y^p)%n == (z^p)%n Ṗṗ3çƇ - Main Link: n, p Ṗ - pop (implicit range of n) [1,2,3,...,n-1] 3 - literal three 3 ṗ - Cartesian power [[1,1,1],[1,1,2],...,[n-1,n-1,n-1]] Ƈ - filter keep those for which: ç - last Link (1) as a dyad Link 1([[1,1,1],[1,1,2],...,[n-1,n-1,n-1]], p) - implicit print ``` [Answer] ## [GAP](http://gap-system.org), 63 bytes ``` Filtered(Tuples([1..n-1],3),i->(i[1]^p+i[2]^p-i[3]^p) mod n=0); ``` For example: ``` gap> n:=4; p:=3; 4 3 gap> Filtered(Tuples([1..n-1],3),i->(i[1]^p+i[2]^p-i[3]^p) mod n=0); [ [ 1, 2, 1 ], [ 1, 3, 2 ], [ 2, 1, 1 ], [ 2, 2, 2 ], [ 2, 3, 3 ], [ 3, 1, 2 ], [ 3, 2, 3 ] ] ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~74~~ 72 bytes *2 bytes saved thanks to [@79037662](https://codegolf.stackexchange.com/users/89930/79037662)* ``` @(n,p){[c,b,a]=ndgrid(1:n-1) [a(k=~mod(a.^p+b.^p-c.^p,n)) b(k) c(k)]}{2} ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI0@nQLM6OlknSScx1jYvJb0oM0XD0CpP11BTITpRI9u2Ljc/RSNRL65AOwlI6CYDCZ08TU2FJI1sTYVkIBFbW21U@z9Nw0jHWJMrTcMYRpmAKBMg7z8A) [Answer] # JavaScript (ES7), 104 bytes Takes input as `(n)(p)`. ``` n=>p=>[...Array(n**3)].map((_,i)=>[i/n/n|0,i/n%n|0,i%n]).filter(([x,y,z])=>x*y*z&&(x**p+y**p)%n==z**p%n) ``` [Try it online!](https://tio.run/##dYpBCoMwFET3vUfk/zSNpbqN4DlESrBaUuxPiFIS6d3T4K6UbuYNb@ahX3oZvHHriextTJNKpBqnmk5K2XqvIxDnFfbyqR3AVRjMmymppPdZZLKdjHqUk5nX0QN0QUSx9fkYeORbUUDg3B1jDmSk1JYLI0yDpcXOo5ztHSa4IFSIh29Z/ZH1j6z3Z/oA "JavaScript (Node.js) – Try It Online") [Answer] # [R](https://www.r-project.org/), 67 bytes ``` function(n,p,m=t(expand.grid(a<-2:n-1,a,a)))m[,!c(1,1,-1)%*%m^p%%n] ``` [Try it online!](https://tio.run/##NcexCoAgEADQvb9oEO7iDEynqC@JAqkMBy8Rg/7eamh6vFTcWNzFa/YnA1OkMGbY72h5a4/kN7CD7HqWiixZRAwT1SsoUiQVikaEJQrBc3HQkcbKgf4xH@ZdeQA "R – Try It Online") `expand.grid` creates all possible triplets of numbers. Annoyingly, the output of `expand.grid` is a data frame and not a matrix, so I transpose it to coerce to a matrix `m`. Take the matrix product of `[1,1,-1]` with `m^p` to get \$x^p+y^p-z^p\$, then keep only the rows for which we get \$ 0 \mod n\$. [Answer] # [R](https://www.r-project.org/), 65 bytes 3 btye's saved from my original idea by @robin-ryder by using subtraction, applying modulo the result. ``` function(n,p,q=(2:n-1)^p)which(!outer(outer(q,q,'+'),q,'-')%%n,T) ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jT6dAp9BWw8gqT9dQM65AszwjMzlDQzG/tCS1SANCFuoU6qhrq2uCKF11TVXVPJ0Qzf9pGkY6xppcaRrGMMoERJmAeP8B "R – Try It Online") Makes use of `outer` to build a 3d array of the addition, then the subtraction. If the remainder of n is 0 output the array indices using `which`. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 54 bytes ``` n_~f~p_:=Select[Range[n-1]~Tuples~3,n|{1,1,-1}.#^p&] ``` Named function taking the two inputs, like `f[4,3]`. The `|` symbol typed above needs to be replaced by the 3-byte character representing the "divides" relation; `\[Divides]` works as well, and is used in the TIO example. Works by testing every possible triple `{x,y,z}`. The only detail of note is that the dot product `{1,1,-1}.#^p&`, when applied to `{x,y,z}`, calculates `x^p+y^p-z^p`. [Try it online!](https://tio.run/##y00syUjNTSzJTE78/z8vvi6triDeyjY4NSc1uSQ6KDEvPTU6T9cwti6ktCAntbjOWCcvJtolsywzJbU4ttpQx1BH17BWTzmuQC32f0BRZl5JtFJatJGOcayCrYKSDoQZywWXMUbIGKPLmCBkTJBlTBB6QMzY/wA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~67~~ 66 bytes ``` ->n,p{w=*1...n;w.product(w,w).select{|a,b,c|(a**p+b**p-c**p)%n<1}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5Pp6C63FbLUE9PL8@6XK@gKD@lNLlEo1ynXFOvODUnNbmkuiZRJ0knuUYjUUurQDsJSOgmAwlN1Twbw9ra/wUKadFGOsaxXCCGMYJhAmGYAEX@AwA "Ruby – Try It Online") Thanks Chas Brown for -1 byte. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` *+_ƭ/³ḍ Ṗṗ3çƇ ``` [Try it online!](https://tio.run/##ASQA2/9qZWxsef//Kitfxq0vwrPhuI0K4bmW4bmXM8Onxof///80/zM "Jelly – Try It Online") -2 bytes thanks to caird coinheringaahing -1 byte borrowing a clever trick from Jonathan Allan # Explanation ``` *+_ƭ/³ḍ Helper Link - given (x, y, z), determine if x^p + y^p = z^p (mod n) * (x^p, y^p, z^p) / Reduce over +_ƭ Tied operator: cycle between + and - (x^p + y^p - z^p) ³ḍ Divisibility check by n (if x^p + y^p - z^p is divisible by n then x^p + y^p is congruent to z^p mod n) Ṗṗ3çƇ Main Link Ṗ Pop (remove last element) - on an integer, implicit range (1 to n-1) ṗ3 Cartesian power ^ 3 çƇ Filter: keep triples that are valid by the helper link ``` [Answer] # [Python 2](https://docs.python.org/2/), 94 bytes ``` n,p=input() R=range(1,n) print[(x,y,z)for x in R for y in R for z in R if(x**p+y**p-z**p)%n<1] ``` [Try it online!](https://tio.run/##RY49D4IwFEVn3q/oYihYBz4mIyOuJsTNOCAWaTSvzUuJLX@@Fh0c7slJ7nCv8XbSWIZB32WTpmlAYRqFZrY8g66hHh@SFwIzMKTQXrgTXizZqIk5ppB1bFX/1@WnauQuz83WR@yWiGyDh@Ia4gS8J/WS7Eyz3ENiyUcm0smBrScg6iCNZe3p2BJpWtsbyf4JoRQVVN/UUIvqAw "Python 2 – Try It Online") Pretty basic. [Answer] # [Icon](https://github.com/gtownsend/icon), 95 bytes ``` procedure f(n,p) x:=1to(t:=n-1)&y:=1to t&z:=1to t&(x^p+y^p-z^p)%n=0&write(x," ",y," ",z)&\q end ``` [Try it online!](https://tio.run/##y0zOz/v/v6AoPzk1pbQoVSFNI0@nQJOrwsrWsCRfo8TKNk/XUFOtEsxVKFGrgjE0KuIKtCvjCnSr4go0VfNsDdTKizJLUjUqdJQUlHQqwWSVplpMIVdqXgqS@bmJmXkamlwKQADRkKZhpGOsiSyipKurq4SqxJgYJSaElJiATQG5BwA "Icon – Try It Online") [Answer] # APL(NARS), chars 129, bytes 258 ``` r←f w;n;p;a;v;i;j;b (n p)←w⋄a←n∣p*⍨v←⍳n-1⋄r←⍬ :for i :in v⋄:for j :in v :if a∊⍨b←n∣a[i]+a[j]⋄r←r,⊂i,j,a⍳b⋄:endif :endfor⋄:endfor ``` test: ``` ⎕fmt f 2 3 ┌0─┐ │ 0│ └~─┘ ⎕fmt f 3 3 ┌2────────────────┐ │┌3─────┐ ┌3─────┐│ ││ 1 1 2│ │ 2 2 1││ │└~─────┘ └~─────┘2 └∊────────────────┘ ⎕fmt f 3 4 ┌0─┐ │ 0│ └~─┘ ⎕fmt f 4 3 ┌7─────────────────────────────────────────────────────────────┐ │┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐│ ││ 1 2 1│ │ 1 3 2│ │ 2 1 1│ │ 2 2 2│ │ 2 3 3│ │ 3 1 2│ │ 3 2 3││ │└~─────┘ └~─────┘ └~─────┘ └~─────┘ └~─────┘ └~─────┘ └~─────┘2 └∊─────────────────────────────────────────────────────────────┘ ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~30~~ 23 bytes -7 bytes thanks to ngn! ``` {(~x!-/*/y#)#+1+!3#x-1} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qWqOuQlFXX0u/UllTWdtQW9FYuULXsPZ/WrSJtXHsfwA "K (oK) – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), 90 bytes ``` l=({1..$[$1-1]}\ ) for x y z (${=${:-$^l$^l$^l}})(((x**$2+y**$2-z**$2)%$1))||<<<"$x $y $z" ``` [Try it online!](https://tio.run/##LczLCoMwFIThfZ5isKd4jiVC1FXRJ@kFijRYEATbhYn67GlCO/x8y/HvIVgWDmPHqylLupDR5rZfIcpOMxY4eDCtHa1nTffx174LMy9FQdXJJbVPypGMyLa1bZvRAnIgn4VnP0zIu7gcwAHptx8f8@vjlChlUaGO1n@baIMmfAE "Zsh – Try It Online") Creates the list `l=('1 ' '2 ' '3 ' ... '(n-1) ' )`, then `${=${:-$^l$^l$^l}` gets the Cartesian product and splits on spaces. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 17 bytes ``` AQf!%-F^RHTG^StG3 ``` [Try it online!](https://tio.run/##K6gsyfj/3zEwTVFV1y0uyCPEPS64xN34/38THWMA "Pyth – Try It Online") Displays a list of triplets, each as \$(z, x, y)\$. ``` AQ # Q = eval(input()), G = Q[0] (=n), H = Q[1] (=p) ^StG3 # Get the following: range(1, n) ^ 3 -> List of (z,x,y) tuples f # filter that on the following condition: lambda T: ^RHT # map(lambda x: x^H, T) --> (z^p, x^p, y^p) -F # reduce by subtraction -> z^p - x^p - y^p = z^p - (x^p + y^p) % G # modulo n --> (z^p - (x^p + y^p)) mod n ! # not (check if == 0) --> z^p == x^p + y^p mod n ``` ]
[Question] [ Similar to other quine puzzles (more specifically, [this one](https://codegolf.stackexchange.com/q/2582/3862)), write a program that produces the source for itself. **Here's the new twist:** The code produced should *NOT* be identical to the source. Rather, it should output a different program that will create the first. The challenge linked to above achieved that by jumping between two languages. I'm thinking this one would be done in **just one language**, but the two (or more) versions of the source should be significantly different (see rules below). With this constraint, [single character answers](https://codegolf.stackexchange.com/a/2593/3862) would be disallowed, thus requiring a little more thought be put into a final submission. --- **RULES** 1. Your code must be produced in just one language. (Multiple submissions, one for each language is perfectly acceptable.) 2. Your different code versions must be syntactically distinct. In other words, if you were to draw out an [abstract syntax tree](http://en.wikipedia.org/wiki/Abstract_syntax_tree) for your code, there should be at least one node different. * Supplying an **AST** will not be necessary, but if you feel inclined to provide one for each of your programs, it *would* help in judging. 3. You may produce as many iterations as you wish, as long as they all remain syntactically distinct. (More will help your score, see below.) --- **SCORING** Your final score will be the mean length of all your programs, divided by the number of programs. Example 1: > > A (source for B) = 50 characters > > B (source for A) = 75 characters > > Final Score = **31.25** > > > Example 2: > > A (source for B) = 50 characters > > B (source for C) = 75 characters > > C (source for A) = 100 characters > > Final Score = **25** > > > [Answer] ## Python, 0 (limit of (68+3 *n* )/(16*n*)) If two abstract syntax trees are different if they have different constants, ``` r='r=%r;n=(0x%XL+1)%%0x10...0L;print r%%(r,n)';n=(0xF...FL+1)%0x10...0L;print r%(r,n) ``` there are 16*n* programs of length at most 68+3n, giving asymptotic score of 0. If you want programs with variable structure, we can implement a binary adder on *n* bits. Here, there are 2*n* programs of length *O*( *n*2). Goes in a cycle due to dropped carry bit. ``` s=""" print 's='+'"'+'"'+'"'+s+'"'+'"'+'"' n=lambda m:reduce(lambda (s,c),y:(s+(c^y,),c&y),m,((),1))[0] print s[:112] t=n(t) print "t=(%s,)+(0,)*%s"%(t[0],len(t)-1) for i in range(len(t)-1): print i*' '+'for i in range(2):' print ' '+i*' '+['pass','t=n(t)'][t[i+1]] print s[113:-1] """ print 's='+'"'+'"'+'"'+s+'"'+'"'+'"' n=lambda m:reduce(lambda (s,c),y:(s+(c^y,),c&y),m,((),1))[0] print s[:112] t=(0,)+(0,)*10 for i in range(2): t=n(t) for i in range(2): t=n(t) for i in range(2): t=n(t) for i in range(2): t=n(t) for i in range(2): pass for i in range(2): t=n(t) for i in range(2): pass for i in range(2): pass for i in range(2): pass for i in range(2): t=n(t) t=n(t) print "t=(%s,)+(0,)*%s"%(t[0],len(t)-1) for i in range(len(t)-1): print i*' '+'for i in range(2):' print ' '+i*' '+['pass','t=n(t)'][t[i+1]] print s[113:-1] ``` [Answer] ## C++, score of 0.734194 The following source code prints a meta quine of order 999 to the console (explanation below): ``` #define X 1*(1+1) #include<iostream> #include<vector> #define Q(S)auto q=#S;S Q( \ main() \ { \ using namespace std; \ cout<<"#define X 1"; \ int x=X==2?1000:X-1; \ vector<int> factors; \ for ( int p = 2; p <= x; ++p) \ { \ while ( x % p == 0 ) \ { \ factors.push_back( p ); \ x /= p; \ } \ } \ for ( int factor : factors ) \ { \ cout<<"*(1"; \ for ( int i=1;i<factor;++i) \ cout<<"+1"; \ cout<<")"; \ } \ cout<<"\n#include<iostream>\n#include<vector>\n#define Q(S)auto q=#S;S\nQ("<<q<<")"; \ }) ``` The only line that changes is the first line. The value of `X` will be 1000, 999, 998, ..., 3, 2 and then it will start again. However, in order to get different syntax trees every time, `X` is represented in terms of its prime factorization, where every prime is written as a sum of `1`s. The ASTs are different, because the prime factorization of integers is different for every value. The program will print itself, except that the first line is changed and the backslashes, line breaks and indentations that are within `Q(...)` will be removed. The following program calculates the score of my answer: ``` #include <iostream> const int n = 1000; int getProgramLength( int n ) { int sum = 442; for ( int p = 2; p*p <= n; ++p ) { while ( n % p == 0 ) { sum += 2 * ( 1 + p ); n /= p; } } if ( n > 1 ) sum += 2 * ( 1 + n ); return sum; } int main() { int sum = 0; for ( int i = 2; i <= n; ++i ) sum += getProgramLength( i ); std::cout << (double)sum/(n-1)/(n-1) << '\n'; } ``` It printed 0.734194 to the console. Obviously, 1000 can be replaced by larger integers and the score will approach 0 as its limit. The mathematical proof involves Riemann's Zeta function is somewhat convoluted. I leave it as an exercise to the reader. ;) [Answer] # Perl, score of 110.25 I have to admit, I'm not very good with quines. I'm 100% certain that there is room for improvement. The solution is based off of the same principle of the Element solution below. The first program is 264 characters. ``` $s='$a=chr(39);print"\$s=$a$s$a;";$s=reverse$s;for(1..87){chop$s}$s=reverse$s;print$s;$f++;if($f==0){$a=chr(39);print"\$s=$a$s$a;$s"}';$a=chr(39);print"\$s=$a$s$a;";$s=reverse$s;for(1..87){chop$s}$s=reverse$s;print$s;$f++;if($f==0){$a=chr(39);print"\$s=$a$s$a;$s"} ``` The second program is 177 characters. ``` $s='$a=chr(39);print"\$s=$a$s$a;";$s=reverse$s;for(1..87){chop$s}$s=reverse$s;print$s;$f++;if($f==0){$a=chr(39);print"\$s=$a$s$a;$s"}';if($f==0){$a=chr(39);print"\$s=$a$s$a;$s"} ``` I'm working on the AST for this entry (and the Element entry). --- # [Element](https://codegolf.stackexchange.com/a/5268/2867), score of 47.25 The first program is 105 characters. ``` \ \3\:\$\'\[\\\\\`\(\`\]\#\2\1\'\[\(\#\]\`\ \3\:\$\'\[\\\\\`\(\`\]\#\` 3:$'[\\`(`]#21'[(#]` 3:$'[\\`(`]#` ``` The second program is 84 characters. ``` \ \3\:\$\'\[\\\\\`\(\`\]\#\2\1\'\[\(\#\]\`\ \3\:\$\'\[\\\\\`\(\`\]\#\` 3:$'[\\`(`]#` ``` I'm sure that there is a lot of room for improvement. In the first program there is one string (in which every character is escaped, despite a lot of redundancy) followed by executable parts A and B. Part A does several things: prints the string and escapes out of every character, prints the last half of the string (which is the source for part B), and then prevents the part B that follows it from doing anything. The second program is the same string followed by part B. Part B is based off of a simple quine; it prints a string preceded by an escaped version of it. This means it prints the string, and both parts A and B. [Answer] ## VBA: (251+216)/2/2 = 116.75 **251** ``` Sub a() r=vbCrLf:c="If b.Lines(4, 4) = c Then"&r &"b.InsertLines 8, d"&r &"b.DeleteLines 4, 4"&r &"End If":d="b.InsertLines 6, c"&r &"b.DeleteLines 4, 2" Set b=Modules("Q") If b.Lines(4, 4) = c Then b.InsertLines 8, d b.DeleteLines 4, 4 End If End Sub ``` **216** ``` Sub a() r=vbCrLf:c="If b.Lines(4, 4) = c Then"&r &"b.InsertLines 8, d"&r &"b.DeleteLines 4, 4"&r &"End If":d="b.InsertLines 6, c"&r &"b.DeleteLines 4, 2" Set b=Modules("Q") b.InsertLines 6,c b.DeleteLines 4,2 End Sub ``` This is run in **MSAccess** to make use of the `Module` object. The module is named `"Q"` for golfing. The difference in syntax comes from the `If ... Then` missing from the shorter version. [Answer] ## JavaScript, ~~84.5~~ ~~64~~ 61 Two programs, both length ~~169~~ ~~128~~ 122. ``` (function c(){alert(/* 2/*/1/**/);return ('('+c+')()').replace(/\/([/\*])/,function(m,a){return a=='*'?'/\/':'/\*'}); })() ``` Before I golfed it, for your viewing pleasure: ``` (function c() { var r = /\/([/\*])/; var f = function(m, a) { return a === '*' ? '/\/' : '/\*' }; var p = '(' + c + ')();'; p = p.replace(r, f); /* This is just a comment! console.log('Quine, part two!'); /*/ console.log('Quine, part one!'); /**/ return p; })(); ``` Returns the new program and outputs the current part! ~~I could probably make it shorter without the function regex, but... I don't want to.~~ [Answer] # J - (24+30)/2 / 2 = 13.5 pts Note that strings in J are not the backslash-escaped, but quote-escaped à la Pascal: `'I can''t breathe!'`. ``` 30$(,5#{.)'''30$(,5#{.)' NB. program 1, 24 char '30$(,5#{.)''''''30$(,5#{.)''' NB. program 2, 30 char ``` Program 1 has AST `noun verb hook noun` and program 2 has AST `noun`. Program 2 is a quoted version of program 1, which will just return program 1 when run, so this method can't be extended to three copies that easily :P Program 1 operates by taking a copy of the code portion of the source, with a quote appended at the front, and adding five of those quotes to the end (`(,5#{.)`). Then, it cyclically takes 30 characters from this 16-character string, which gives exactly Program 2 as a result. ]
[Question] [ Your job is to take a string input and a number and align the string to the right, making the width of the text the number. When a line is too long, break it and put the rest on the next line, repeating until it's not necessary. If a line is shorter than the width, then pad it with spaces. Multiple newlines can occur, and should be treated like any other single character. For example, the string ``` Programming Puzzles & Code Golf ``` and the number `5` would produce: ``` Progr ammin g Puzzl es & Code Golf ``` Whereas the same string and the number `10` would produce: ``` Programmin g Puzzles & Code Golf ``` The string ``` a b ``` and the number 5 would produce: ``` a <-- note the 5 spaces b ``` Shortest code wins! [Answer] ## Python 2, 84 ``` s,n=input() for w in s.split('\n'): w=w or' ' while w:print w[:n].rjust(n);w=w[n:] ``` Takes as input a string with newlines and a number, and prints the result. For each line in the input, takes and prints `n` chars at a time, using the built-in `rjust` to pad the left with spaces before printing. I fixed the empty line case with the hack `w=w or' '`. There's probably a better method but I'm not going to think much about it. [Answer] # Pyth, 14 bytes ``` jm.[\ QdscRQ.z ``` [Demonstration](https://pyth.herokuapp.com/?code=jm.%5B%5C+QdscRQ.z&input=5%0AProgramming%0APuzzles%0A%26%0ACode%0AGolf&debug=0) Uses Pyth's pad operator. [Answer] # CJam, 21 bytes ``` li_qN/Sfe|f/ff{\Se[N} ``` *Thanks to @Sp3000 for golfing off 1 byte and paving the way for 3 more.* Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=li_qN%2FSfe%7Cf%2Fff%7B%5CSe%5BN%7D&input=5%0AProgramming%0APuzzles%0A%0A%26%0A%0ACode%0AGolf). ### How it works ``` li Read an integer L from the first line of input. _ Push a copy. qN/ Split the remaining input at linefeeds. Sfe| Map `OR " "'; the replaces empty lines with a space. f/ Split each line into chunks of length L. ff{ } For each chunk, push L and the chunk; then: \ Swap L with the chunk. Se[ Left-pad the chunk to length L by prepending " ". N Push a linefeed. ``` [Answer] # Pyth, 16 ``` jm>Q+*\ QdscRQ.z ``` [Try it online here](https://pyth.herokuapp.com/?code=jm%3EQ%2B%2a%5C+QdscRQ.z&input=5%0AProgramming%0APuzzles%0A%26%0ACode%0AGolf&debug=0) ### Explanation ``` jm>Q+*\ QdscRQ.z : Q is the number on the first line, .z takes the rest cRQ.z : chop each line of .z into chunks of Q characters m s : remove nested lists and map over the result +*\ Qd : add Q spaces to each line d >Q : take the last Q characters of that result j : join results on newlines ``` [Answer] # Perl, 39 bytes ``` perl -ni5 -e 's!^$|.{1,$^I}!printf"%${^I}s ",$&!ge' ``` 36 bytes + 3 bytes for `-ni`. The wrap width is passed as the argument to `-i`. Handles blank lines properly by padding them with spaces: ``` $ echo -e "Programming\nPuzzles\n\n&\n\nCode\nGolf" | perl -ni5 -e 's!^$|.{1,$^I}!printf"%${^I}s ",$&!ge' Progr ammin g Puzzl es & Code Golf ``` ## How it works This solution uses the substitution operator to loop through the input, saving a byte over the equivalent `for` loop. The real trick, though, is in the regex on the LHS of the substitution: ``` ^$|.{1,$^I} ``` With the global modifier, this will match `$^I` characters at a time; when there are less than `$^I` characters remaining in the string, it will match everything to the end. The alternation with `^$` is required to handle blank lines. For example: ``` $ echo -e "foo\n\nbar" | perl -ni2 -E 'say "<$_>" for /^$|.{1,$^I}/g' <fo> <o> <> <ba> <r> ``` The RHS of the substitution simply uses `printf` to left-pad the matched chunk with spaces. [Answer] # Javascript (ES6), 107 I wish JS had a built in pad function. Oh well. ``` (a,b)=>a.replace(eval(`/(.{${b}})(?!\\n)/g`),`$1 `).split` `.map(c=>(Array(b).join` `+c).slice(-b)).join` ` ``` Explanation: ``` (a, b)=> // searches for sequences of characters longer than b without a newline after them and // adds a newline after every b characters of the sequence a.replace(eval(`/(.{${b}})(?!\\n)/g`), '$1\n') .split('\n') .map(c=> // prepends b spaces to each string then slices it from the right down to length b ( Array(b).join(' ') + c ).slice(-b) ).join('\n') ``` [Answer] # Julia, 126 bytes ``` f(s,n)=for i=split(s,"\n") while length(i)>0 println(lpad(i[1:min(n,end)],n));length(i)<n?break:(i=i[min(n+1,end):end])end;end ``` Ungolfed: ``` function f(s::String, n::Int) for i in split(s, "\n") while length(i) > 0 println(lpad(i[1:min(n,end)], n)) length(i) < n ? break : (i = i[min(n+1,end):end]) end end end ``` [Answer] ## Bash, 62, 61+feature, 59 Shorter if `N` can be set by the caller, instead of having to read it as the first line of input. ``` # width as a function arg: 59 chars f()while read -rn$1 r;do [[ $r ]]&&printf %$1s\\n "$r";done # width on stdin: 64 chars (not updated with later suggestions&ideas) read N;while read -rn$N r;do [[ $r ]]&&printf %$N's\n' "$r";done ``` This fails to handle empty lines in the input. Otherwise, this doesn't subject the input data to word-splitting, pathname expansion, or otherwise treat it as more than just raw data. `read -n$N` saves one character, but lets `read` munge `\`. The `[[ $r ]]&&` is needed because `read -n4` can't lookahead to see that the next char is a newline. So it sets `r` to a 4-char string, and the next read produces a zero-char empty string. Filtering these false newlines without filtering real newlines would require tracking state: whether the previous line was max-length or not. Either more code or a totally different approach would be needed. `[[ $r ]]` is shorter than `[ -n "$r" ]` which is needed to avoid errors if the line starts with `-z foo`, or is `*` or something, if you used `[ $r ]`. Justication happens with the standard printf "%4s" format string. Test with ``` f()(while read -rn$1 r;do [[ $r ]]&&printf %$1s\\n "$r";done); (echo 4; echo -e "*\n\\"; cat /tmp/lines) | f 4 ``` [Answer] # Haskell, 108 bytes ``` import Data.List.Split k[]=[""] k x=x f n=unlines.(map(\l->([1..n-length l]>>" ")++l).k.chunksOf n=<<).lines ``` Usage example: ``` *Main> putStr $ f 5 "a\n\nb\ncd\nMatamorphosis" a b cd Matam orpho sis ``` How it works ``` .lines -- split input string at newlines =<< -- for every line chunksOf n -- split into chunks of length n k -- fix empty lines map -- for every chunk \l->([1..n-length l]>>" " -- make a string of missing spaces ++l -- and append the chunk unlines -- join padded chunks with newlines in-between ``` [Answer] ## GNU awk + bash, 70 ``` f()(awk -vFPAT=.\{,$1} '{for(i=0;i++<NF;){printf "%'$1's\n",$i}}/^$/') ``` Using bash to slot the count into the awk program is prob. smaller than reading it with a `NR==1{N=$0}` block. Read a line at a time. Split into at-most-4 character chunks, using FPAT. (matches the fields, rather than the separators. GNU extension.) printf each field separately. (Default ORS = \n). The `/^$/` rule is there to print empty lines, which have NF=0 and thus don't print at all in the other block. So unlike my pure-bash solution, this actually works in the general case. Semi-unrelated, but my idea so far for perl is 112 chars for just the perl code: ``` (echo 4; echo -e 'foo\nbar'; echo -e "*\n\\"; echo '~$(true)'; cat /tmp/lines) | # test input perl -e '$N=<>;$/=\1;print "$N\n"; while(<>){if(/\n/ or length($l)>=$N){printf("%$4s\n",$l);$l=/\n/?"":$_;}else{$l.=$_;}}' ``` This eats one of the newlines, and is way too long. `$/=\1` reads a byte at a time. We append to $l. Probably a line-at-a-time with fixed-width split approach would be shorter. [Answer] # Bash + GNU utils, 41 ``` fold -$1|sed ":;s/^.\{,$[$1-1]\}\$/ &/;t" ``` String is input via STDIN, width is input by command-line arg: ``` ubuntu@ubuntu:~$ echo 'Programming Puzzles & Code Golf'|./ralign.sh 10 Programmin g Puzzles & Code Golf ubuntu@ubuntu:~$ ``` [Answer] # Python 2, 151 bytes ``` s,n=input();N='\n' for w in[i.lstrip()if i.replace(' ','').isalpha()else i for i in s.replace(N,'\n ').split(N)]: while w:print w[:n].rjust(n);w=w[n:] ``` This is a adaptation of @xnor's answer above, as his does not properly handle newlines. --- The `for` loop was changed from: ``` for w in s.split('\n'): ``` to: ``` for w in[i.lstrip()if i.replace(' ','').isalpha()else i for i in s.replace(N,'\n ').split(N)]: ``` --- # Example ``` $ python main.py "Programming\n\n\nPuzzles\n\n&\n\nCode\nGolf", 5 Progr ammin g Puzzl es & Code Golf ``` [Answer] # C#, 143 bytes ``` (s,n)=>Join("\n",s.Split('\n').SelectMany(l=>(l.Any()?l:" ").Select((c,i)=>new{c,i}).GroupBy(o=>o.i/n,o=>o.c).Select(g=>Concat(g).PadLeft(n)))) ``` Linq lets you make pretty gnarly expressions. `GroupBy` is useful here, but it's a shame they couldn't create function overloads taking the index. Assign the lambda to a `Func<string, int, string>` to run it Less golfed: ``` Func<string, int, string> Align = (s, n) => Join("\n", s.Split('\n') .SelectMany(l => (l.Any() ? l : " ") .Select((c, i) => new { c, i }) .GroupBy(o => o.i / n, o => o.c) .Select(g => Concat(g).PadLeft(n)))); ``` [Answer] # Groovy, 63 bytes Returns the correctly alligned string. Didn't know there was a padLeft (and padRight, padCenter) function until now. ``` f={s,n->s.split("(?<=\\G.{$n})|\n")*.padLeft(n," ").join("\n")} ``` [Answer] # JavaScript ~~174~~ 136 ``` function R(s,x){return s.replace(new RegExp(".{"+x+"}","g"),"$&\n").replace(/[^\n]*/g,function(m){ while(m.length<x)m=" "+m;return m;})} ``` [Answer] # Ceylon, 107 ``` String w(String s,Integer n)=>"\n".join{for(l in s.lines)for(p in l.partition(n))String(p).padLeading(n)}; ``` [Answer] # Matlab, 99 bytes Thanks to @beaker for removing 6 bytes! Using and anonymous function: ``` @(s,k)fliplr(char(cellfun(@fliplr,strsplit(regexprep(s,sprintf('\\S{%i}',k),'$0\n'),'\n'),'un',0))) ``` Define the function and use `ans` to call it: ``` >> @(s,k)fliplr(char(cellfun(@fliplr,strsplit(regexprep(s,sprintf('\\S{%i}',k),'$0\n'),'\n'),'un',0))) ans = @(s,k)fliplr(char(cellfun(@fliplr,strsplit(regexprep(s,sprintf('\\S{%i}',k),'$0\n'),'\n'),'un',0))) >> ans(['Programming' 10 'Puzzles' 10 '&' 10 'Code' 10 'Golf'], 5) %% 10 is line feed ans = Progr ammin g Puzzl es & Code Golf ``` [Answer] ## Burlesque, 28 Bytes Same as the version below, but treats line 1 as the number and the other lines as the string. ``` lng_riPpun{pPco{pP' lp}mu}Wl ``` Usage as in: ``` $ cat input.txt | blsq --stdin "lng_riPpun{pPco{pP' lp}mu}Wl" Progr ammin g Puzzl es & Code Golf ``` Old Version (16 bytes): ``` {5co{5' lp}mu}Wl ``` Example: ``` blsq ) "Programming\nPuzzles\n&\nCode\nGolf"{5co{5' lp}mu}Wl Progr ammin g Puzzl es & Code Golf ``` ]
[Question] [ The following is inspired by [a question that came up on Stack Overflow today](https://stackoverflow.com/questions/31251377). Given a number of microseconds, `0 <= n <= 86400000000` (e.g. `12345678900`), output a formatted string `hh:mm:ss:000:000`, e.g. `03:25:45:678:900`. ``` 0 -> '00:00:00:000:000' 12345678900 -> '03:25:45:678:900' 86400000000 -> '24:00:00:000:000' ``` I have a solution in Python in 209 bytes, but can it go lower? [Answer] # Python 2, ~~82~~ 79 bytes ``` n=input() o="" for k in[1000]*2+[60]*3:o=":%0*d"%(k%7/2,n%k)+o;n/=k print o[1:] ``` Builds the string, iterating through a series of divmods. The only fancy bit is the `%7/2`, which maps `1000 -> 3` and `60 -> 2`. [Answer] # Pyth, 31 bytes ``` j\:_m>l`td+"00"%~/QddCM"ϨϨ<<< ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=j%5C%3A_m%3El%60td%2B%2200%22%25~%2FQddCM%22%CF%A8%CF%A8%3C%3C%3C&input=12345678900&debug=0) ### Explanation: ``` implicit: Q = input number "ϨϨ<<< string "ϨϨ<<<" (5 chars but 7 bytes) CM convert each to number => [1000, 1000, 60, 60, 60] m map each number d to: /Qd divide Q by d ~ and update Q with the new value %~ Q d but use the old value to calculate Q mod d +"00" add the result to the string "00" > but only take the last l`td len(str(d-1)) chars _ revert order j\: join the strings with ":"s ``` [Answer] # Bash + coreutils, 61 Shortest "mainstream" language so far... ``` a=%02d: printf $a$a$a%03d:%03d `dc -e$1\ A00~rA00~r60~r60~rf` ``` ### Test output: ``` $ for t in 0 12345678900 86400000000; do ./usec.sh $t; echo; done 00:00:00:000:000 03:25:45:678:900 24:00:00:000:000 $ ``` [Answer] # CJam, ~~37 35~~ 34 bytes This is prettty long .. Golfing now.. ``` ri[1e3_60__]{:ImdsIBb,0e[':@}%W%2> ``` *UPDATE: 1 byte saved thanks to @Sp3000* [Try it online here](http://cjam.aditsu.net/#code=ri%5B1e3_60__%5D%7B%3AImdsIBb%2C0e%5B%27%3A%40%7D%25W%252%3E&input=12345678900) [Answer] # C, 97 bytes ``` q=1000,s=60; #define f(n)printf("%02d:%02d:%02d:%03d:%03d",n/s/s/q/q,n/s/q/q%s,n/q/q%s,n/q%q,n%q) ``` Test Code: ``` int main(int intc, char **argv) { long long n = atoll(argv[1]); f(n); } ``` [Answer] # q (34) I'm sure it can be shorter ``` ":"sv 0 8 11__[;8]15$2_($)16h$1e3* ``` e.g. ``` q)f:":"sv 0 8 11__[;8]15$2_($)16h$1e3* q)f 12345678900 "03:25:45:678:900" ``` [Answer] # Julia, ~~110~~ ~~96~~ 95 bytes ``` t->(o="";for i=int([36e8,6e7,1e6,1e3,1]) x,t=t÷i,t%i;o*=lpad(x,i>1e3?2:3,0)*":"end;o[1:end-1]) ``` This creates an unnamed function that accepts an integer as input and returns a string. To call it, give it a name, e.g. `f=t->...`. Ungolfed + explanation: ``` function f(t) # Initialize an output string o = "" # Loop over an array consisting of the number of microseconds in # an hour, minute, second, millisecond, and microsecond for i = int([36e8, 6e7, 1e6, 1e3, 1]) # Get the quotient and remainder for microseconds into t, # setting t to be the remainder x, t = t ÷ i, t % i # Left-pad x with zeroes and append it to the output o *= lpad(x, i > 1e3 ? 2 : 3, 0) * ":" end # o has a trailing :, so return everything but the last character o[1:end-1] end ``` Examples: ``` julia> f(12345678900) "03:25:45:678:900" julia> f(0) "00:00:00:000:000" julia> f(86400000000) "24:00:00:000:000" ``` [Answer] # C#, ~~179~~ 175 Bytes When you have builtins at your disposal, why not use 'em? ``` static void Main(string[]a){var t=TimeSpan.FromTicks(long.Parse(Console.ReadLine())*10);Console.Write(t.ToString((t.Days<1?"hh":@"\2\4")+@"\:mm\:ss\:ffffff").Insert(12,":"));} ``` With better formatting: ``` static void Main(string[]a){ var t = TimeSpan.FromTicks(long.Parse(Console.ReadLine())*10); Console.Write(t.ToString((t.Days<1?"hh":@"\2\4")+@"\:mm\:ss\:ffffff").Insert(12,":")); Console.Read(); } ``` [Answer] ## Excel, 65 63 characters Assuming your microseconds is in **A1**: ``` =TEXT(A1/50/1200^3,"[HH]:mm:ss:")&RIGHT(TEXT(A1,"000\:000"),7) ``` Output: ``` A B 1 0 00:00:00:000:000 2 12345678900 03:25:46:678:900 3 86400000000 24:00:00:000:000 ``` [Answer] # Perl, ~~141~~ 78 bytes ``` printf"%02d"x3.%03d:%03d",$_/36e8,$_/6e7%60,$_/1e6%60,$_/1e3%1e3,$_‌​%1e3 ``` 77 bytes of code, +1 for the `-n` flag. Run with: ``` echo 12345678900 | perl -ne'printf"%02d"x3.%03d:%03d",$_/36e8,$_/6e7%60,$_/1e6%60,$_/1e3%1e3,$_‌​%1e3' ``` Thanks to Thomas Kwa and chilemagic for cutting my code size nearly in half. [Answer] ## CoffeeScript, 127 bytes Took the approach in [ASCIIThenANSI's answer](https://codegolf.stackexchange.com/a/52686/22867). It's too bad that the JavaScript [Console API](https://developer.chrome.com/devtools/docs/console-api) doesn't have format placeholders for padding numbers. ``` p=(a,b)->('00'+~~a).slice -b||-2 f=(t)->console.log '%s:%s:%s:%s:%s',p(t/36e8),p(t/6e7%60),p(t/1e6%60),p(t/1e3%1e3,3),p t%1e3,3 ``` [Answer] ## Matlab - 88 ~~89~~ bytes Gained one byte with a solution without using the built in function: ``` n=[36e8,6e7,1e6,1e3];f=@(t)sprintf('%02d:%02d:%02d:%03d:%03d',fix([t mod(t,n)]./[n 1])) ``` Create an inline function which takes a numeric input argument `t` and return a string. it uses a vectorized combination of `fix` and `mod` to separate the time elements, then display. it's a bit frustrating that the formatting of the output string takes so much, more than the calculations themselves ... Test: ``` for t=[0 12345678900 86400000000] f(t) end ans = 00:00:00:000:000 ans = 03:25:45:678:900 ans = 24:00:00:000:000 ``` --- 89 bytes version: ``` f=@(t)sprintf('%s:%03d:%03d',datestr(fix(t/1e6)/86400,13),fix(mod(t,1e6)/1e3),mod(t,1e3)) ``` It splits the number, uses a built-in function for the hh:mm:ss part, which cannot deal with microseconds so the string is completed with combination of `fix` and `mod` operations [Answer] ## Powershell,153 ``` $t=[timespan]::FromTicks(($a=$args[0]));"{0:D2}:{1:D2}:{2:D2}:{3:D3}:{4:000}"-f [int]($t.TotalHours),$t.Minutes,$t.Seconds,$t.Milliseconds,(($a%1e4)/10) ``` ## Usage ``` powershell -nologo .\modprintsec.ps1 123456789000 03:25:45:678:900 powershell -nologo .\modprintsec.ps1 864000000000 24:00:00:000:000 powershell -nologo .\modprintsec.ps1 0 00:00:00:000:000 ``` [Answer] ## JavaScript (ES6), ~~128~~ ~~118~~ ~~116~~ 111 bytes There is probably some golfing potential in this. ``` f=t=>(t<864e8?new Date(t/1e3).toJSON().slice(11,-1):`24:00:00:000`).replace(`.`,`:`)+':'+('00'+t%1e3).slice(-3) ``` ### Demo It is ES6 so Firefox only, for now anyways: ``` f=t=>(t<864e8?new Date(t/1e3).toJSON().slice(11,-1):`24:00:00:000`).replace(`.`,`:`)+':'+('00'+t%1e3).slice(-3) // DEMO document.body.innerHTML += '<br>' + f(0); document.body.innerHTML += '<br>' + f(12345678020); document.body.innerHTML += '<br>' + f(86400000000); ``` [Answer] ## F#, 111 92 102 bytes First iteration: Base idea. Second iteration: Smaller constants Third iteration: Correct formatting for single digit portions. Note this function must be given an int64 to work. ``` let s,t=60L,1000L let f n=sprintf"%02d:%02d:%02d:%03d:%03d"(n/s/s/t/t)(n/s/t/t%s)(n/t/t%s)(n/t%t)(n%t) ``` Example outputs: ``` f 0L -> "00:00:00:000:000" f 12345678900L -> "03:25:45:678:900" f 86400000000L -> "24:00:00:000:000" ``` [Answer] # C, ~~113~~ ~~103~~ 105 bytes *EDIT: shoved off some more bytes* *FIX: removed long type, thanks to some user* Not the shortest C answer, but I had some fun with carriage returns so I felt like someone might like this. ``` i,k,p=16; #define f(n)for(;i<5;p-=i++<2?4:3)k=i<2?1000:60,printf("%0*d%c\r",p,n%k,i?58:13),n/=k;puts(""); ``` Call it like: ``` int main() { long long n = 12345678900; f(n); return 0; } ``` [Answer] # PHP - 115 102 bytes A solution in 155 bytes (wrapped here on 3 lines for readability): ``` $a=$argv[1]; $h=($a-($m=($a=($a-($s=($a=($a-($t=($a=($a-($u=$a%1000))/1000)%1000))/1000)%60))/60)%60))/60; printf("%02d:%02d:%02d:%03d:%03d",$h,$m,$s,$t,$u); ``` The second line computes (from inside to outside) the exact values of the components starting with the microseconds. ## The shorter version (115 bytes, wrapped on two lines for readability): ``` $u=$argv[1];$h=($m=($s=($t=$u/1000)/1000)/60)/60; printf("%02d:%02d:%02d:%03d:%03d",$h,$m%60,$s%60,$t%1000,$u%1000); ``` It also uses embedded assignments to compute the convert the input number of microseconds in milliseconds, seconds, minutes and hours using floating point numbers. The modulus operator (`%`) and the decimal number format (`%d`) of `printf()` is then used to force them to integer numbers (the fractional part is ignored). ## Another solution that uses the date functions (102 bytes) ``` $u=$argv[1]; echo gmdate("H:i:s",strtotime("@".substr($u,0,-6))),":",substr($u,-6,3),":",substr($u,-3); ``` The hours:minutes:seconds part is handled by the PHP date functions `gmdate()` and `strtotime()`, the milli- and micro-seconds are extracted as strings from the input value. ### Usage: ``` $ php -r '$u=$argv[1];echo gmdate("H:i:s",strtotime("@".substr($u,0,-6))),":",substr($u,-6,3),":",substr($u,-3);' 7198898787; echo 01:59:58:898:787 ``` [Answer] ## Java, 215 bytes ``` String f(long n){return p(n/3600000000l,2)+":"+p(n/60000000%60,2)+":"+p(n/1000000%60,2)+":"+p(n/1000%1000,3)+":"+p(n%1000,3);}String p(long n,int i){String s=String.valueOf(n);while(s.length()<i){s="0"+s;}return s;} ``` Method `f` does some calculations on `n` to work out the hours, minutes etc. and delegates to method `p` to format each value correctly. **Formatted:** ``` String f(long n) { return p(n / 3600000000l, 2) + ":" + p(n / 60000000 % 60, 2) + ":" + p(n / 1000000 % 60, 2) + ":" + p(n / 1000 % 1000, 3) + ":" + p(n % 1000, 3); } String p(long n, int i) { String s = String.valueOf(n); while (s.length() < i) { s = "0" + s; } return s; } ``` **Usage:** ``` public void demo() { long n = 12345678900l; System.out.println(f(n)); } ``` [Answer] # Ruby - 82 Bytes ``` puts (t=Time.at(0,gets.to_i)).strftime("%2H:%2M:%2S:%3L:#{(t.usec%1000).to_s.rjust(3,?0)}") ``` ]
[Question] [ # Objective Given an ASCII character, toggle its "shift-ness" on the standard US keyboard (ANSI-INCITS 154-1988 (R1999)), then output it. # Mapping ``` ) ↔️ 0 ! ↔️ 1 @ ↔️ 2 # ↔️ 3 $ ↔️ 4 % ↔️ 5 ^ ↔️ 6 & ↔️ 7 * ↔️ 8 ( ↔️ 9 " ↔️ ' + ↔️ = , ↔️ < - ↔️ _ . ↔️ > / ↔️ ? : ↔️ ; (Capital Latin letters) ↔️ (Small Latin letters) [ ↔️ { \ ↔️ | ] ↔️ } ` ↔️ ~ (ASCII whitespaces and control characters are left intact) ``` # Rule * Non-ASCII characters fall into *don't care* situation. # Examples Given a character `0`, output `)`. Given a character `C`, output `c`. Given a character (space), output . Given a character `\t` (horizontal tab), output `\t`. Given a character `\a` (bell), output `\a`. [Answer] # x86-16, Genuine IBM PC, ~~32~~ ~~31~~ 29 bytes ``` 00000000: b4f0 8ec0 bfe5 e8b3 3ab1 74a0 8200 f2ae ........:.t..... 00000010: 3acb 7f02 f7db 268a 41ff cd29 c3 :.....&.A..). ``` Build with `xxd -r`. **Unassembled listing:** ``` B4 F0 MOV AH, 0F0H ; BIOS segment address (F000H) 8E C0 MOV ES, AX ; set ES to BIOS segment for SCASB BF E8E5 MOV DI, E8E5H ; set to LABEL K10 B3 3A MOV BL, 58 ; size of table B1 74 MOV CL, 58*2 ; size of both tables A0 0082 MOV AL, BYTE PTR DS:[82H] ; get input char from command line F2/ AE REPNZ SCASB ; search BIOS table for char 3A CB CMP CL, BL ; found in the lowercase table? 7F 02 JG UPPER ; if so, convert with uppercase table by adding F7 DB NEG BX ; otherwise subtract the offset UPPER: 26:8A 41 FF MOV AL, ES:[BX+DI-1] ; get char from table CD 29 INT 29H ; DOS fast write to console C3 RET ; return to DOS ``` **Input/Output:** [![enter image description here](https://i.stack.imgur.com/VGUoi.png)](https://i.stack.imgur.com/VGUoi.png) **How does it work?** Well, the PC BIOS already contains all of the code and tables necessary for this since it actually handles the conversion of scan codes received from the keyboard to ASCII chars (in real/DOS mode at least). There's no way (that I know of) to actually hook this on just *any* "PC-compatible" BIOS, however if you know the location of the table in ROM (on the IBM PC it starts at `F000:E8E5`), you can use that. On Page A-25 of Appendix A the [IBM PC Technical Reference](https://ibm.retropc.se/manuals/IBM_5150_Technical_Reference_6025005_AUG81.pdf) (listing of the entire source code of the PC BIOS) is the disassembly of this table: [![enter image description here](https://i.stack.imgur.com/yenCh.png)](https://i.stack.imgur.com/yenCh.png) Unfortunately, this address will be different on any given PC-clone BIOS and of course, there's no guarantee that it would even be implemented in the same way by anyone else. Thus, this submission is guaranteed to run only on a *Genuine IBM PC*. Go Big Blue! [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~110 ... 97~~ 96 bytes ``` c=>(s=")0@2^6&7*8(9\"'+=-_:;`~")[s.indexOf(c)^1]||(B=Buffer)([([n]=B(c),n%127>32)<<4+n/64^n])+'' ``` [Try it online!](https://tio.run/##XY5BT8JAFITv/IqXJtr3XKm0EEDbJabcPMiBY2m1KV2swbdmFw0E9OgP8Cf6R@rCkctkkm8yM6/lZ2kr07xvuqyXdatkW8kJWulR7z4qhpejqzHeLjxfyO7TXfz87VFmg4aX9XamsKIizA8HTGX6oVRtCDPMOJepI9d8EUajST@iJBkIvhkOCs5J@H6rtEEGCb0YGBIIo7EzQhDsOwCVA/ONaXgVKKPfpi@lmbpjyBQfqWar13Ww1it8mM8eA3uKNmrnFkGAD38/v04FnNHjV3IVX@0/ "JavaScript (Node.js) – Try It Online") ### How? We use a lookup table for these pairs: ``` ) ↔️ 0 @ ↔️ 2 ^ ↔️ 6 & ↔️ 7 * ↔️ 8 ( ↔️ 9 " ↔️ ' + ↔️ = - ↔️ _ : ↔️ ; ` ↔️ ~ ``` For all other characters, we use the following code: ``` (B = Buffer)([ // generate a buffer from a singleton array: ( // [n] = B(c), // n = ASCII code of the input character n % 127 > 32 // 1 if 32 < n < 127, or 0 otherwise ) // << 4 + n / 64 // left-shifted by 4 if n < 64, or by 5 otherwise ^ n // XOR'ed with n ]) + '' // end of Buffer(); coerce it to a string ``` which supports these 3 cases: * If \$32<n<64\$, we XOR the ASCII code with \$16\$, which is what we need for: ``` ! ↔️ 1 # ↔️ 3 $ ↔️ 4 % ↔️ 5 , ↔️ < . ↔️ > / ↔️ ? ``` * If \$64\le n<127\$, we XOR the ASCII code with \$32\$, which toggles the case of letters and also works for these pairs: ``` [ ↔️ { \ ↔️ | ] ↔️ } ``` * If \$n\le32\$ or \$n=127\$, the character is left unchanged (ASCII code XOR'ed with \$0\$). [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 34 bytes ``` T`-~A-]d';-?/.+,:"(*&^%$#@!)}-_`Ro ``` [Try it online!](https://tio.run/##Xc89TgJRFAXg/qzi8v8GGMB/BRUIFQmV2CkwL8MzTDLOkDcvsUAobW1cjOtxAy5hHItjYfflnuTcHGtclOg8vw/8w9hfrBsDf9jttNr9smrWl7VqZVTy9v4quEvz3JOvt4/vz3fpoUQeYUQeo0KeoEqeokaeYUmeo05eoEleQpFXKJMNtMgbtMlr@OQKHfIWXXKIPjmAmuht5HQsM13sldg4Z2z2N0jNn3X8P8QD4x0eyVcsyD0C8gA1nk@mU3nZRM5kWx2aTHSyljBNnE1jCTfa6vC3VrQ1xYsnJ1HiipP3Aw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: The `T` command is Retina's transliteration operation. Among its special characters are: * ```: Delimit the parts of the command * `-`: Introduce a range (this suppresses the following special characters so `d-o` just means `defghijklmno`) * `_`: Delete the matching character * `d`: `0-9` * `R`: Reverse the next range * `o`: Take the source string as the range The trick is therefore to create as many ranges as possible to reduce the length, plus avoiding having the `-` and `_` characters where they would be interpreted as a special character and avoiding the ``` at all by including it inside a range. Additionally arranging for the range to transliterate to its reversal allows that to be expressed very cheaply. [Answer] # [Bash](https://www.gnu.org/software/bash/) + core utilities, ~~58~~ \$\cdots\$ ~~51~~ 49 bytes Added ~~47~~ 50 bytes to fix a bug kindly pointed out by [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe). Saved 8 bytes thanks to [Value Ink](https://codegolf.stackexchange.com/users/52194/value-ink)!!! Saved 2 bytes thanks to [Mitchell Spector](https://codegolf.stackexchange.com/users/59825/mitchell-spector)!!! ``` a='"A-]`=<_>?)!@#$%^&*(;' b=\'a-~+-: tr $a$b $b$a ``` [Try it online!](https://tio.run/##PYvLDoIwFET3/YoRq4AG4lZLQf/jKhaB8EiKAVby@PWKMbqZTM6ZSVRXmN5xB6OkbV28610GcRi5q/Oab27bnSNslkiylTfvvRPrW3DFE/CEKzOxvGlRotQYDr5/nEA2SIICUAwKQRFIYFC@/1rcABpBS5kF0oZVkjvZo2jAS4zoXVH/QfUFz7bUfQ5r08EL8UvS1ueyjHgtWNrozLwB "Bash – Try It Online") [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 86 [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") This solution [has been out-golfed](https://codegolf.stackexchange.com/a/199947/43319) but is preserved due to being interesting for its sourcing of the data. Anonymous prefix lambda. Requires 0-based indexing (`⎕IO←0`). ``` {⍵∊a←↑'[!-~]{2}'⎕S'&'↓⍉↑'\w\w...'⎕R(5⍴'')↓11 71↑30↓⎕FMT⌂notes.keyboards:a⌷⍨~@1⊃⍸⍵=a⋄⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/6sf9W591NGVCOQ8apuoHq2oWxdbbVSrDlQRrK6m/qht8qPeTpBMTHlMuZ6eHkgiSMP0Ue8WdXVNoKyhoYK5IVDe2ACktG@qm2/Io56mvPyS1GK97NTKpPzEopRiq8RHPdsf9a6oczB81NX8qHcH0FLbxEfdLUC69n8ayO7ePrDMGqDBh9YbAw0EOSDIGUiGeHgG/09TUDdQ5wKSzmBSAUxygkl2dQA "APL (Dyalog Extended) – Try It Online") This works by extracting the character pairs from [a built-in note about keyboards](https://dfns.dyalog.com/n_keyboards.htm). `{`…`}` "dfn"; argument character is `⍵`:  `⌂notes.keyboards` the built-in string  `⎕FMT` ForMaT as a character matrix  `30↓` drop the first 30 lines  `11 71↑` take the first 11 lines' first 71 columns  `↓` split into list of strings  `'\w\w...'⎕R(`…`)` PCRE **R**eplace word-character,word-character,any-symbol,any-symbol with:   `''` the empty string   `5⍴` reshaped to length 5, padding with spaces; i.e. 5 spaces  `↑` mix list of strings into character matrix  `⍉` transpose  `↓` split matrix into list of strings  `'[!-~]{2}'⎕R'&'` PCRE **S**earch and return any pair of printable ASCII characters  `↑` mix list of character pairs into two-column matrix  `a←` store in `a` (for ***a***ll)  `⍵∊`…`:` if the argument character is a member of that matrix:   `⍵=` Boolean matrix mask where they are equal   `⍸` get indices where true   `⊃` pick the first (row,column) pair   `~@1` negate the number at position 1 (the column; i.e. 1→0 and 0→1)   `a⌷⍨` use that to index into the matrix of **a**ll pairs  `⋄` else:   `⍵` the argument character [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~38~~ 37 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “Æz⁶ɦG!€u<ʂCP]ƭƝ’œ?ØṖḟØB¤ḊØD;ṙ21,ƊyŒs ``` A monadic Link accepting a list of characters which yields a list of characters. **[Try it online!](https://tio.run/##AYQAe/9qZWxsef//4oCcw4Z64oG2yaZHIeKCrHU8yoJDUF3Grcad4oCZxZM/w5jhuZbhuJ/DmELCpOG4isOYRDvhuZkyMSzGinnFknP///8HQmVsbAlUYWIgU3BhY2UpIUAjJCVeJiooIissLS4vOltcXWAwMTIzNDU2Nzg5Jz08Xz4/O3t8fX4 "Jelly – Try It Online")** ### How? Forms a mapping for non alphabetic characters, applies the translate atom, `y`, and then swaps case. ``` “Æz⁶ɦG!€u<ʂCP]ƭƝ’œ?ØṖḟØB¤ḊØD;ṙ21,ƊyŒs - Link: list of characters, S “Æz⁶ɦG!€u<ʂCP]ƭƝ’ - base 250 number =53994992086540427749431907521542401 ¤ - nilad followed by link(s) as a nilad: ØṖ - printable characters = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ØB - base-62 characters =0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ḟ - filter discard = !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ œ? - lexicographical permutation = '=<_>?;{|}~)!@#$%^&*("+,-./:[\]` Ḋ - dequeue ='=<_>?;{|}~)!@#$%^&*("+,-./:[\]` ØD - digit characters =0123456789 ; - concatenate =0123456789'=<_>?;{|}~)!@#$%^&*("+,-./:[\]` Ɗ - last three links as a monad: 21 - twenty-one ṙ - rotate left =)!@#$%^&*("+,-./:[\]`0123456789'=<_>?;{|}~ , - pair =)!@#$%^&*("+,-./:[\]`0123456789'=<_>?;{|}~ and 0123456789'=<_>?;{|}~)!@#$%^&*("+,-./:[\]` y - translate (S) Œs - swap case ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~99~~ 95 bytes Same strategy as @Arnauld's answer. *-4 bytes thanks to @mypetlion* ``` lambda c,s=")0!1@2#3$4%5^6&7*8(9\"'+=,<-_.>/?:;[{\\|]}`~":[c.swapcase(),s[s.find(c)^1]][c in s] ``` [Try it online!](https://tio.run/##Fc1JDoIwGEDhvaf4xalVRAEHRFHv0RathUoTLaQlMcbh6oi7t/nyqmddlDpsJCRAmxu/XzIOwrWJg@dd/xj0wv5isExXw/U4QhvqjCaJu5uevP3sEG/Ji9I3@5y/TkyEZx@8EtzmCLuWWE8qnSGBU58xIkBpsKyRpQH1b8P1NUd@EOG4A6J9i8IghTtQGaVrJFuImx8 "Python 3 – Try It Online") ## Explanation * `s=")0!1@2#3$4%5^6&7*8(9\"'+=,<-_.>/?:;[{\\|]}`~"` contains all pairs of special toggles. * `s[s.index(c)^1]` gets the index of the other character from the same pair * If the character is a Latin or control character (`c in s` is `False`), `c.swapcase()` is returned. `c.swapcase()` toggles the case of a Latin character, but doesn't affect control character. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~53~~ ~~36~~ 35 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .šžQžiмDœ•1ĀêŽƵÆ{çIΣeÿí‚Ð"pkālrÙ•è‡ ``` -1 byte implicitly thanks to *@Grimmy* due to his comment. [Try it online](https://tio.run/##AUcAuP9vc2FiaWX//y7FocW@UcW@adC8U0TigKIxxIDDqsW9xrXDhnvDp0nOo2XDv8Ot4oCaw5AicGvEgWxyw5nigKIuSeKAof//Xg) or [verify all printable ASCII characters](https://tio.run/##AVYAqf9vc2FiaWX/xb5Rdnk/IiDihpIgIj95/y7FocW@UcW@adC8U0TigKIxxIDDqsW9xrXDhnvDp0nOo2XDv8Ot4oCaw5AicGvEgWxyw5nigKIuSeKAof8s/w). NOTE: The TIO versions use the `S•...•.I` (builtin for the n'th permutation of a list) instead of `œ•...•è` (push all permutations of the string (extremely slow bottleneck for a string this large), and index into it). **Explanation:** ``` .š # Switch-case of the (implicit) input-character (if it's a letter) žQ # Push all printable ASCII characters: # !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ žiм # Remove all letters [A-Za-z]: # !"#$%&'()*+,-./0123456789:;<=>?@[\]^_`{|}~ D # Duplicate it œ # Push a list of all permutations of this string •1ĀêŽƵÆ{çIΣeÿí‚Ð"pkālrÙ• "# Push compressed integer 540470878544692028277787799913384202055137480696656 è # Index it into the string-list of permutations: # 1'3457"908=<_>?)!@#$%^&*(;:,+./2{|}6-~[\]` ‡ # Transliterate the characters at the same indices # (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 `•1ĀêŽƵÆ{çIΣeÿí‚Ð"pkālrÙ•` is `540470878544692028277787799913384202055137480696656`. This number(+1) is generated by [the Jelly builtin `Œ¿`](https://tio.run/##y0rNyan8///opEP7////r2Cobmxiaq5kaWBhaxNvZ6@p6KCsohqnpqVhbaWjradvVF1Ta6ZbFx0Tm/BfQVEJKKemrqGppa2jq6dvYGgE1GtmbmFpZW1ja2fvAFQVF58A1FEHAA), which gets the 1-based index of the permutation. [Answer] # [Perl 5](https://www.perl.org/) `-p`, ~~92~~ 91 bytes *-1 byte thanks to @ValueInk* ``` s/[]a-z{}|\\[]/$&^$"/gei;y/0-9)!@#$%^&*(`~\-=_+';":,.\/<>?/)!@#$%^&*(0-9~`_+\-=":';<>?,.\// ``` [Try it online!](https://tio.run/##K0gtyjH9/79YPzo2UbequrYmJiY6Vl9FLU5FST89NdO6Ut9A11JT0UFZRTVOTUsjoS5G1zZeW91ayUpHL0bfxs5eHyEJVFmXEK8NVKFkpW4NlAMp0f//PzEpOSIyytDI2MTUzNzC0gChIzo2pqa2@l9@QUlmfl7xf11fUz0DQ4P/ugUA "Perl 5 – Try It Online") [Answer] # Pure [Bash](https://www.gnu.org/software/bash/), ~~170~~ 165 bytes ``` a=`echo {A..Z}`')!@#$%^&*("+,-./:[\]`' b=`echo {a..z}`0123456789"'=<_>?;{|}~" c=$a$b d=$b$a for((;n<164;n++)){ [ "$1" = "${c:n:1}" ]&&echo ${d:n:1}&&exit;} echo "$1" ``` [Try it online!](https://tio.run/##NYzdDsEwAEbv@xRVtR@jlBnWFXsNM9puZG62BBei6tVrlrj6ck5OPiXvlbWSi3NRNVCnhOyNcP3ero8HR2fooWA0JpM4O@TCBeqfSUJeRkzpbB4uouVqjVyenDZbpt/mg0DBscQKlBwrLMGluXkeqxMahawOAt/XMIMIUwR5O7qI65gaBHPH6b6xLjvT4vP6YAZ09tdba9Mv "Bash – Try It Online") I decided to implement a solution inspired by @Noodle9's very nice answer, but using pure bash without any utilities (like tr). Note that you need to run this in an empty directory; this can be fixed at the cost of 2 bytes by using quotes for `"{d:n:1}"`. (This issue only arises with a non-empty current directory when the input is `8`, so the output is supposed to be `*`.) On the other hand, you can gain 2 bytes if you don't require output for the input `\n`: just eliminate the quotes in the final `echo`. [Answer] # [Julia](http://julialang.org/), 87 bytes ``` x->Char[0:32;b"1'3457\"908=<_>?)!@#$%^&*(;:,+./2";97:125;b"6-~";65:93;96;127][Int(x)+1] ``` [Try it online!](https://tio.run/##HY7LboJAAEX39yuu44PB94CAMII2XfUXimhpKimNoQamqenDX6fWszirk5v79nEsc3Vui7g9T5L717xO55Hr6GehLHfhBVsRzpfxap@s7c6m2@vvBkOpo/FoOnOEDoNIOd619ScXoX0vCl0d@lo5QZY@VEae7ZHKWnNoTMOYdf4phIDNOTpU2NBBly56XKBPDzv6GDDAkEtIhhC0MGKMMVeYcI8pE8y4RkSNlN/Y8gcZf/HEC3Le4YuP//Mo3msalhXToqwbM5XN6VgaeXth25oWrau21c3KysArp7qszLGShnHCQhrbxqF6QfsH "Julia 1.0 – Try It Online") [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 60 [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. ``` -(,⊃⍨⍳-¯1*⍳)⍨('"''+=,<-_.>/?:;[{\|]}`~',∊')!@#$%^&*(',¨⎕D),- ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X1dD51FX86PeFY96N@seWm@oBaQ1gVwNdSV1dW1bHRvdeD07fXsr6@jqmJrY2oQ6dZ1HHV3qmooOyiqqcWpaGuo6h1Y86pvqoqmj@z/tUduER719YAPXPOrdcmi98aO2iUDZ4CBnIBni4Rn8P01B3UCdC0g6g0kFMMkJJtnVAQ "APL (Dyalog Extended) – Try It Online") `-` swap case `(`…`),` prepend the following:  `⎕D` the digits  `')!@#$%^&*(',¨` prepend each of these characters to the corresponding digit  `∊` **ϵ**nlist (flatten)  `'"''+=,<-_.>/?:;[{\|]}`~',` prepend these characters (`''` is an escaped single quote) `-(`…`)⍨` apply the following function with that as *left* argument and the case-swapped original argument as *right* argument:  `⍳` **ɩ**ndex of the case-swapped argument in the substitution string  `¯1*` negative one raised to that power  `⍳-` subtract that from the **ɩ**ndex of the case-swapped argument in the substitution string  `,⊃⍨` use that to pick an element from the case-swapped argument appended to the substitution string [Answer] # Pure [Bash](https://www.gnu.org/software/bash/), 217 bytes ``` P=printf\ a=`$P%x "'$1"` case $a in 3[ab])x=1;;2[27])x=5;;2[68]|3[79])x=17;;2a|38)x=18;;2b|3d)x=22;;29|30)x=25;;36|5e)x=104;;2d|32|40|5f)x=114;;20|7f)x=0;;60|7e)x=30;;[23]?)x=16;;[4-7]?)x=32 esac $P\\`$P%o $[0x$a^x]` ``` [Try it online!](https://tio.run/##Hc7PCoMwDAbwu09RRsfYYVAbtUqRsTfwXjus/5gXN@YOHvLuXeLtly9fIH3YXjE29ee7rL@5FUmoO9mcd3G6yPTUJUPYJiGDWFYBLvT@uteptdppw8yZRekRnKmOnaEkIJTsktwjjGStyRWCYtMVFJhP3FEZLUYEjZnCfOYo5Uih4UFZWxC5CmSnwd@5U5CzmzkG0Mm0hSGRTdvy728hndpleO6@izE@/g "Bash – Try It Online") Just bash -- no Unix utilities. Input character is passed as an argument, and the output is on stdout. **\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_** **Test runs:** ``` $ cat shifttoggle P=printf\ a=`$P%x "'$1"` case $a in 3[ab])x=1;;2[27])x=5;;2[68]|3[79])x=17;;2a|38)x=18;;2b|3d)x=22;;29|30)x=25;;36|5e)x=104;;2d|32|40|5f)x=114;;20|7f)x=0;;60|7e)x=30;;[23]?)x=16;;[4-7]?)x=32 esac $P\\`$P%o $[0x$a^x]` $cat shifttoggleTest #!/bin/bash count=1 for s in ')!@#$%^&*("+,-./:' "0123456789'=<_>?;" ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz '[\]`' '{|}~' $' \a\n\r\t\x7F\x80\x88\x8F' do echo "TEST #$count" for ((n=0;n<${#s};n++)) do c="${s:$n:1}" d=`./shifttoggle "$c"` # Backticks remove any trailing newline, so restore that here for the case where c is \n (you can check that shifttoggle really prints \n in that case). if test -z "$d" then d=$'\n' fi if test "$count" -eq 7 then printf " ASCII %d => ASCII %d\n" "'$c" "'$d" else echo " $c => $d" fi done (( count++ )) echo '' done $ ./shifttoggleTest TEST #1 ) => 0 ! => 1 @ => 2 # => 3 $ => 4 % => 5 ^ => 6 & => 7 * => 8 ( => 9 " => ' + => = , => < - => _ . => > / => ? : => ; TEST #2 0 => ) 1 => ! 2 => @ 3 => # 4 => $ 5 => % 6 => ^ 7 => & 8 => * 9 => ( ' => " = => + < => , _ => - > => . ? => / ; => : TEST #3 A => a B => b C => c D => d E => e F => f G => g H => h I => i J => j K => k L => l M => m N => n O => o P => p Q => q R => r S => s T => t U => u V => v W => w X => x Y => y Z => z TEST #4 a => A b => B c => C d => D e => E f => F g => G h => H i => I j => J k => K l => L m => M n => N o => O p => P q => Q r => R s => S t => T u => U v => V w => W x => X y => Y z => Z TEST #5 [ => { \ => | ] => } ` => ~ TEST #6 { => [ | => \ } => ] ~ => ` TEST #7 ASCII 32 => ASCII 32 ASCII 7 => ASCII 7 ASCII 10 => ASCII 10 ASCII 13 => ASCII 13 ASCII 9 => ASCII 9 ASCII 127 => ASCII 127 ASCII 128 => ASCII 128 ASCII 136 => ASCII 136 ASCII 143 => ASCII 143 ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 100 bytes ``` char*strchrnul(),*s=")0@2^6&7*8(9\"'+=-_:;`~\0";f(c){c=s[strchrnul(s,c)-s^1]?:(c%127>32)<<4+c/64^c;} ``` Similar to the Javascript strategy. I'd like to get rid of the extra parentheses but this is pretty good. [Try it online!](https://tio.run/##lY/NDoIwEITvPEXTRG35iYAEkIL6HiJKVhESLaYFLwRfHQvReHZOk9l8u7NgXQGGAcpc6LIRUAre3gg1dZlgau/czJ8HekjWKV4YiXWM2OmV2pgVBGgHidz/GGkCtWTmHLYRgZnjBpuVS@PYM2Dpexmwfqh4g@55xcmzrs5U6zSkNIbAtMkXtSCAEmQzBChGjhsqYxh0Go56tM3YVB3/ECqQBKcc039XjB98IXFpWsEVo/XDGw "C (gcc) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/) `-p`, 66 bytes Builds the "lowercase" and "uppercase" strings so that everything lines up, and connects them together to be passed into the `tr` function so it can do the proper conversions. ``` l="\\-a-z0-9=[-];',./`" u='_A-Z)!@#$%^&*(+{|}:"<>?~' $_.tr!u+l,l+u ``` [Try it online!](https://tio.run/##KypNqvz/P8dWKSZGN1G3ykDX0jZaN9ZaXUdPP0GJq9RWPd5RN0pT0UFZRTVOTUtDu7qm1krJxs6@Tp1LJV6vpEixVDtHJ0e79P//BEMjYxNTM3MLSwNdW67C8tSiksrSzPyC6NgYrsTilLT0jKzsHGt1rqqK5LKkvFygBVxcdXCDNeO1uQLDXYNCIkM9/QOqa2u4HINd3Nw9vLx9rJS4oiKcw5z8fIH2cnF5pObk5OsolOcX5aQo/ssvKMnMzyv@r1sAAA "Ruby – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 189 bytes ``` param($x)if(($s=")0@2^6&7*8(9""'+=-_:;``~").contains($x)){$s[$s.indexof($x)-bxor1]}else{ $n=[byte][char]$x;if($n-in32..64){[char]($n-bxor16)}elseif($n-in65..127){[char]($n-bxor32)}else{$x}} ``` [Try it online!](https://tio.run/##XY3RCoIwAEXf@4wxaiscqTUrEfqJnsRy2sSBbbIJLcR@faXSS6/nnsNt1ZNrU/Omca5lmj0QtFhUCEGTALw9B1e6jNYHdARgtUm82ynO8zfApFSyY0KaUcc9NCk0RMg7t6oakVdYpf1s4I3h/QLKJC1eHc/SsmY6gzb@PkDpCRkGhNAd7udhZFNI8VT@LLonxA@ify0MZq2Hdhicc5cP "PowerShell – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 111 bytes ``` $k=')!@#$%^&*("+,-./:[\]`'+'A'..'Z'+"0123456789'=<_>?;{|}~"+'a'..'z' "$k$k$args"[($p=$k|% i*f @args)+72*!!++$p] ``` [Try it online!](https://tio.run/##RZDbUsIwEIbv8xRLCGxLCiIe8FSswwPIDHeWCjWmUkFa0zI6Qn31mrSMbGaSf3f//TJJmnxJlS3lel2yCFzYlWzlot3wmqz13O5YlDvd3smNPwsWyPEBez18Qk77p4Oz84vL4dU1unfz0f3tbl/8Uo6hMfwgoWylV6jeMupbLHXZat@CuBOBZ2o2Hw46jQbnLA3KghDPIsSxsI8O2mgbaWvZr@UYHUBRazAaKk0XOXXMZhJfLEMVDJ3DaQM0Ic4hzkAkSkmRA85ChChRMPl/cAVRBqJoTdyYZKMTYsMeWrAjoIMZqANMfqeaJF/1L7F53VEy265zXWjrz6t8Vd2fTMfbLE8@Hl/e9Ujg1SAT060QMssM4zDcFfLzCD8al3F0uKw2Vp2CFOUf "PowerShell – Try It Online") `i*f` is shortcut for `indexOf`. Explain: * The shift series contains 72 chars `)!@#..A B C.. Y Z`. * The shift-ness series contains 72 chars also * `$k` contains concatenated shift and shift-ness series * if `$args` does not found in `$k`, then `indexOf` returns `-1` and script returns the last char from string `$k+$k+$args`. It is `$args`. * if `$args` found in `$k`, then the script return shifted char. ]
[Question] [ The year 2013 had an interesting property: the digits are consecutive when sorted (0123). Let's call this type of number a *sortable number:* a non-negative integer whose base-10 digits are consecutive after sorting. Unfortunately, this won't happen again until 2031, and after that, not until 2103. Your challenge is to write a program or function that, when given a non-negative integer through any standard method, outputs or returns the next sortable number. ## Rules * Input and output must be in base 10. * Output may be in any reasonable format (number literal, string literal, single-item array, ...). * Your code must produce the proper output within 1 minute for all inputs up to 98764. ## Test cases ``` 0 -> 1 1 -> 2 9 -> 10 10 -> 12 11 -> 12 99 -> 102 233 -> 234 234 -> 243 243 -> 312 2016 -> 2031 2031 -> 2103 2103 -> 2130 2130 -> 2134 2134 -> 2143 9876 -> 10234 98764 -> 98765 ``` The sortable numbers form [A215014](http://oeis.org/A215014). A list of all entries up to 98765 can be found [here](https://gist.github.com/ETHproductions/4937931975a5397b9035227af57fe2f1). ## 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/), 61 bytes ``` f=lambda n:-~n*(`sorted(`n+1`)`[2::5]in'0123456789')or f(n+1) ``` [Try it online!](https://tio.run/nexus/python2#Jc3bCsIwDIDha32K3Iy2WqHHHQo@iQidzEFhZjLnra8@E735@EkC2cbz1D9uQw@YTh88yPyal/U@yIxHm1W@uJTitaAw1vkQ66bthJoXGCXt1TZSIhQEaTRYDR3JxUntvGcCEbiMrVlPa2cNT6w3P@mka5v6b1Bpv3suBVcQVXwnIARUIFHzY6W2Lw "Python 2 – TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ ~~10~~ 9 bytes ``` ⁵ḶwṢ ‘Ç1# ``` Returns a singleton array. [Try it online!](https://tio.run/nexus/jelly#@/@ocevDHdvKH@5cxPWoYcbhdkPl/9ZKh9sfNa1x///fQEfBUEfBEkiCWCAmkG1kbAwiTICECYhlYGgGIo2B0kaGBiARQ2MDMAlUYmlhbgYhTQA "Jelly – TIO Nexus") ### How it works ``` ‘Ç1# Main link. Argument: n ‘ Increment; yield n+1. Ç1# Apply the helper link to k = n+1, n+2, n+3, ... until one of them maps to a truthy value. Yield a singleton array containing that value of k. ⁵ḶwṢ Helper link. Argument: k ⁵ Set the return value to 10. Ḷ Unlength; yield [0, ..., 9]. Ṣ Sort; yield the sorted array of k's decimal digits. w Window-index; yield the 1-based index(truthy) of the digit array in [0, ..., 9], 0 (falsy) if not found. ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 8 bytes ``` `QtVSdqa ``` [Try it online!](https://tio.run/nexus/matl#@58QWBIWnFKY@P@/kYGhGQA) Or [verify all test cases](https://tio.run/nexus/matl#S/ifEFgSFpxSmPg/1iXkvwGXoQKXJZchkDbksrTkMjI2BmITLiMTIG1gaAYkjA25jAwNgFxDYwMQYcJlaWFuBiZMAA). ### Explanation ``` ` % Do...while Q % Add 1. Takes input (implicit) in the first iteration t % Duplicate V % Convert to string. This gives an array of chars (same as a string) % representing the digits S % Sort d % Consecutive differences between the chars (automatically converted % to ASCII codes) q % Subtract 1. This gives an array where consecutive differences equal % to 1 are converted to 0, and the rest give a nonzero result a % True if any value is nonzero. This is the loop condition: if true % (which means at least one consecutive difference was not 1), go on % with the next iteration. Else exit loop % End do...while (implicit) % Display (implicit) ``` [Answer] ## JavaScript (ES6), ~~64~~ 54 bytes *Saved a massive 10 bytes, thanks to Neil* ``` f=n=>[...++n+''].sort().some((v,i,a)=>v-i-a[0])?f(n):n ``` ### Test cases ``` f=n=>[...++n+''].sort().some((v,i,a)=>v-i-a[0])?f(n):n console.log(f(0)); // -> 1 console.log(f(1)); // -> 2 console.log(f(9)); // -> 10 console.log(f(10)); // -> 12 console.log(f(11)); // -> 12 console.log(f(99)); // -> 102 console.log(f(233)); // -> 234 console.log(f(234)); // -> 243 console.log(f(243)); // -> 312 console.log(f(2016)); // -> 2031 console.log(f(2031)); // -> 2103 console.log(f(2103)); // -> 2130 console.log(f(2130)); // -> 2134 console.log(f(2134)); // -> 2143 console.log(f(9876)); // -> 10234 console.log(f(98764)); // -> 98765 ``` [Answer] # Pyth - ~~11~~ 10 bytes ``` f}S`TjkU;h ``` [Test Suite](http://pyth.herokuapp.com/?code=f%7DS%60TjkU%3Bh&test_suite=1&test_suite_input=2012%0A2013%0A2016%0A9876%0A98764&debug=0) [Answer] ## PowerShell v2+, ~~71~~ ~~68~~ 67 bytes ``` param($n)do{$n++}until(-join(0..9)-match-join([char[]]"$n"|sort))$n ``` [Try it online!](https://tio.run/nexus/powershell#@1@QWJSYq6GSp5mSX62Sp61dW5pXkpmjoZuVn5mnYaCnZ6mpm5tYkpwBEYhOzkgsio6NVVLJU6opzi8q0dRUyfv//7@hpYUhAA "PowerShell – TIO Nexus") An iterative solution that runs pretty much instantaneously on my machine. ``` PS C:\Tools\Scripts\golfing> measure-command {.\find-the-sortable-years.ps1 98764} | fl totalseconds TotalSeconds : 0.0487127 ``` Yes, that's a `do`/`until` loop in a code-golf. Sorry, not sorry. Basically we loop upwards from our input `$n` until `$n|sort`ed regex `-match`es against `0123456789`. Then we place `$n` on the pipeline, and output is implicit. Saved a byte by realizing that `-join(0..9)` is one byte shorter than the literal string `0123456789`. [Answer] ## Mathematica, 63 bytes ``` #+1//.x_/;!Differences@Sort@IntegerDigits@x~MatchQ~{1...}:>x+1& ``` Replaces `#+1` with the next value as long as `Differences@Sort@IntegerDigits@x~MatchQ~{1...}` is false, which is the condition that the current value is sortable. Here's another fun idea, that unfortunately ended up being way too long: ``` FirstCase[FromDigits/@Union@@Permutations/@Join@@Array[Range,{9,10},0],x_/;x>#]& ``` In this one, I'm generating all the sortable years first and then I select the first one that is greater than the input. Some more ideas that didn't turn out to be shorter than the first attempt: ``` #+1//.x_/;Array[Range,{9,10},0]~FreeQ~Sort@IntegerDigits@x:>x+1& #+1//.x_/;Subsequences@Range[0,9]~FreeQ~Sort@IntegerDigits@x:>x+1& #+1//.x_/;0~Range~9~FreeQ~{___,##&@@Sort@IntegerDigits@x,___}:>x+1& ``` [Answer] # PHP, ~~105~~ ~~103~~ 89 bytes New 89 bytes version thanks to Titus: ``` for(;!$p;){$t=str_split($n=++$argv[1]);sort($t);$p=strstr('0123456789',join($t));}echo$n; ``` Usage: ``` php -r "for(;!$p;){$t=str_split($n=++$argv[1]);sort($t);$p=strstr('0123456789',join($t));}echo$n;" 9000 ``` Previous 103 bytes version thanks to Xanderhall: ``` <?for($p=0;!$p;){$t=str_split($n=++$_GET[n]);sort($t);$p=strstr('0123456789',implode($t));}echo "$n\n"; ``` Previous 105 bytes version: ``` <?for($n=$_GET[n]+1;;$n++){$t=str_split($n);sort($t);if(strstr('0123456789',implode($t))){echo$n;exit;}} ``` Usage: `sortable-years.php?n=9000` outputs `9678`. Ungolfed version with test cases: ``` $test = array(0,1,9,10,11,99,233,234,243,2016,2031,2103,2130,2134,9876,98764); foreach ($test as $argv[1]) { for(;!$p;){ $t=str_split($n=++$argv[1]); sort($t); $p=strstr('0123456789',join($t)); } echo "$n\n"; // add newline for testing $p=false; // reset $p for testing } Output: 1 2 10 12 12 102 234 243 312 2031 2103 2130 2134 2143 10234 98765 ``` [Test online! (New 89 bytes version)](http://sandbox.onlinephpfunctions.com/code/923855caa7033f41df3b2ee35cf84a80df48263b) [Test online! (Previous 103 bytes version)](http://sandbox.onlinephpfunctions.com/code/f1fff3e3d40de0a1e22bc99100c34e67fe4eded2) [Test online! (Previous 105 bytes version)](http://sandbox.onlinephpfunctions.com/code/83a6784c6c461ba68f931688e9d6d39f19000147) Execution time maybe <= 1 second for all the test cases. [Answer] # [Perl 6](https://perl6.org), 49 bytes ``` {first {$/eqv($/=.comb.sort).minmax.list},$_^..*} ``` ## Explanation ``` { first { $/ # sorted list from later eqv # is it equivalent ( $/ # store in match variable ( doesn't need to be declared ) = .comb.sort # sorted list of digits from currently tested value ).minmax # the Range of digits .list # flattened to a list }, $_ ^.. * # Range starting just after input } ``` ## Test: ``` # give it a lexical name for clarity my &code = {first {$/eqv($/=.comb.sort).minmax.list},$_^..*} my @all = +«'sortable.txt'.IO.lines; my @gen = code(-1), &code ... ( * >= 98765 ); say @all eqv @gen; # True say now - INIT now; # 16.3602371 ``` [Answer] # C#, ~~153~~ ~~130~~ 101 bytes (~~122~~ ~~99~~ 83 excluding namespace declarations) ``` using System.Linq;n=>{while(!"0123456789".Contains(string.Concat((++n+"").OrderBy(x=>x))));return n;} ``` **-23 bytes thanks to pinkfloydx33** **another -29 thanks to Link Ng (I really should have known I don't need to convert it into an array)** Damn conversions. (Added bonus this is surprisingly fast) [Answer] # [Befunge](http://github.com/catseye/Befunge-93), 117 bytes ``` &>1+0v 9`#v_>:9+0\4p1+: 1:$<v 0g1+>00p:55+%9+1\4p55+/:!#v_0 v+*g09:<".........." 9p09 < >:00g-v^< -9:p09_v| $v@._<$<> ``` [Try it online!](http://befunge.tryitonline.net/#code=Jj4xKzB2CjlgI3ZfPjo5KzBcNHAxKzoKMTokPHYKMGcxKz4wMHA6NTUrJTkrMVw0cDU1Ky86ISN2XzAKdisqZzA5OjwiLi4uLi4uLi4uLiIgOXAwOSA8Cj46MDBnLXZePAotOTpwMDlfdnwKJHZALl88JDw-&input=MjAxMw) The way we test if a year is sorted is by creating an "array" (written into the string literal on line five) and for every digit in the year, we set that index into the array to 1. Once all the digits have been processed, we count how many 1s there are in sequence, and if that count equals the year length we can assume the year is sorted. **Detailed Explanation** ``` &>1+ Read the year and increment it. 0v The "array" is initialized with zeros prior 9`#v_>:9+0\4p1+: to processing each year. 1:$<v For every digit, set the corresponding array index 0g1+>00p:55+%9+1\4p55+/:!#v_0 to one, and increment the year length counter. p09 < Initialise the sequence counter to zero. 9 Push a marker onto the stack. ".........." Push the values from the array onto the stack. v+*g09:< Increment the sequence counter for every 1 in the >:00g-v^< array and reset it on every 0. Break if it equals -9:p09_v| the year length or we encounter the end marker. @._<$< If we have a match, clear the stack and output the year. $v > If we've reached the marker, drop it try the next year. ``` [Answer] # Ruby, 51 bytes ``` ->n{n+=1 until'0123456789'[n.to_s.chars.sort*''];n} ``` [Answer] # Python 2, 68 bytes ``` n=input()+1 while''.join(sorted(`n`))not in'0123456789':n+=1 print n ``` Well beaten by @Dennis but just posted as an alternative method anyway. [Answer] ## C#, 127 bytes ``` using System.Linq;n=>{char[]s;while((s=(++n+"").OrderBy(x=>x).ToArray()).Select((x,i)=>i>0&&x-s[i-1]!=1).Any(x=>x));return n;}; ``` ~~Beat the current C# submission by 3 bytes :p~~ Beaten back already I know this answer will be beaten back easily... [repl.it demo](https://repl.it/EqwA/1) Ungolfed ``` n=> { char[] s; while(( // Store char array in variable to be referenced in Select() // Increment n and cast to string s=(++n+"") // Sort ascending, to array .OrderBy(x=>x) .ToArray()) // Convert char to true if it's not at position 0, // and it is not 1 greater than the previous char .Select((x,i)=>i>0&&x-s[i-1]!=1) // All false: n is sortable // Any true: n is not sortable .Any(x=>x)) // while loop body is empty ; return n; }; ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~10~~ 9 bytes -1 thanks to Emigna. ``` [>D{žhså# ``` [Try it online!](http://05ab1e.tryitonline.net/#code=Wz5Ee8W-aHPDpSM&input=Mg) New description coming when I have time. [Answer] # Python 2, ~~118 117 114~~ 108 Bytes ``` x,s=input()+1,sorted while[j for i,j in enumerate(s(str(x))[1:])if int(s(str(x))[i])+1!=int(j)]:x+=1 print x ``` EDIT: -1 Byte thanks to @Gábor Fekete -6 Bytes thanks to @Zachary T [Answer] # PHP, ~~90~~ ~~89~~ 88 bytes a completely different approach: ``` while(array_unique($a=str_split($n=++$argv[1]))!=$a|max($a)-min($a)-count($a)+1);echo$n; ``` Run with `-r`. **breakdown** ``` while( array_unique( // 3. unique values $a=str_split( // 2. split to digits $n=++$argv[1] // 1. increase number ) ) !=$a // 4. repeat while unique digits differ from original digits | // or max($a)-min($a) // digit range -count($a)+1 // differs from count-1 ); echo$n; // print result ``` [Answer] **Clojure, ~~104~~ ~~96~~ 91 bytes** Long method names don't make this that short... At least `map-indexed` and `-` get main calculations done in a neat way. *Edit 1*: Neat, I forgot also `=` can take multiple arguments so I don't need to check if count of distinct values is 1. *Edit 2*: No need to run `(sort(seq(str %)))`, `(sort(str %))` works equally well. ``` (fn[i](first(filter #(apply =(map-indexed -(map int(sort(str %)))))(rest(iterate inc i))))) ``` Ungolfed: ``` (defn f [i] (let [is-sorted? #(= 1 (->> % str sort (map int) (map-indexed -) set count))] (->> i (iterate inc) rest (filter is-sorted?) first))) ``` [Answer] ## R, 87 bytes ``` f=function(x)`if`(all(diff(sort(as.double(el(strsplit(c(x+1,""),"")))))==1),x+1,f(x+1)) ``` As usual when it comes to splitting numbers into digits, R does not have a native way of doing this. Consequently we have to coerce the input into a character, split into a character vector and subsequently convert back to any numeric type. [Try it online](http://www.r-fiddle.org/#/fiddle?id=HkO8NoHd&version=1) ]
[Question] [ I have a serious problem. I have some text files where I keep my very important numbers -- all of the important ones! And twos, and threes.. These numbers were so important that I couldn't entrust them to those newfangled decimal or binary number systems. I kept each number encoded in unary, as so: ``` +--+ | | +---+ +----+ | | | | | +---+ +-------+ ~/two.txt ``` Simple and reliable: two ASCII loops for the number 2. Unfortunately, these things tend to get tangled up over time and now I have a hard time figuring out how many loops are in each file. Here are some examples that I worked out by hand: One: ``` +---+ | | +--+ | | | +--+ | | | | | | | +--+ +--+ | | +---------+ ``` Three: ``` +---------+ | +-----+ | | | +-+ | | | | | | | | | | +-+ | | | +-----+ | +---------+ ``` Four: ``` +--------------+ | +--+ +--+ | | | | | | | +-|-----|-----|----+ | | | | | | | | | +--+ +--+ +--+ | +------------------+ +------------+ | | +-----+ +-----+ | | | | | +-----|-----------+ | | | | +--+ | | | | +-+ +--|--|--+ +---------+ | | +-+ | | | +------+ | | | | +-------+ | | || | | |+-----+ | | +---+ ``` Five: ``` +--------+ +--------+ +--------+ | | | | | | | +--|-----+ +--|-----+ | | | | | | | | | | | +-----|--+ +-----|--+ +--------+ | | | | +--------+ +--------+ ``` Can you help me count my loops? Here are the rules: * Since I store everything in ASCII-encoded unary, space efficiency is very important to me. Therefore, this is code golf. The smallest program in bytes wins. * Loops are drawn with the characters +, -, |. Every corner in the loop is drawn unambiguously: exactly one of the characters above and below the + will be |, and exactly one to the right or left will be -. Two + marks are never adjacent. * Strands may pass over and under each other. When strands cross, you'll be able to see the "under" strand immediately on both sides of the "over" strand. * Your program should take a string representation of the loop (either from stdin or as a function parameter) and produce a number (either to stdout or as a return value). * Line lengths may not be uniform in the loop drawing and there may be trailing spaces on each line. * You may assume that there is at least one loop in the input. I'm counting on you! [Answer] # SnakeEx - 98 bytes with Javascript, 44 without This looked like a good problem to try my language from the [Fortnightly Challenge](https://codegolf.stackexchange.com/questions/47311/language-design-2-d-pattern-matching/47555#47555) on: ``` m:({e<>PE}\-[|\-]*<T>\+|[|\-]*<T>)+`\+ e:\+ ``` The best place to try this out is my [online interpreter](http://www.brianmacintosh.com/snakeex/). SnakeEx matches patterns in text by using "snakes" that move around the text matching regexes. The code reads kind of like a regex, except: * The `<T>` instruction. That is a direction command that branches the snake left and right from its current direction. * `{e<>PE}` is like a subroutine call. It that spawns a snake with definition `e` moving forward (`<>`) and with parameters `P` (piggyback - the spawning snake follows the new snake) and `E` (exclusive - don't match anything that's already been matched). This exclusive check is the only thing that stops the snake from looping infinitely. * The prefix ``` at the end indicates that what follows should be matched only if it has already been matched, which we can use to force the loop to close. Because SnakeEx is like regex and doesn't technically output the results as desired by itself, I guess we need to wrap it in some Javascript calling the interpreter: ``` function e(s){return snakeEx.run('m:({e<>PE}\\-[|\\-]*<T>\\+|[|\\-]*<T>)+`\\+\ne:\\+',s,1).length} ``` *Edit*: fixed it up to work with blutorange's additional test cases [Answer] # C# - 338 ~~388~~ ~~433~~ bytes Saved a bunch of bytes by changing to a 1-dimensional array. ``` using C=System.Console;using System.Linq;class P{static void Main(){var D=C.In.ReadToEnd().Split('\n');int z,w=D.Max(m=>m.Length)+1,d,c=0;var E=D.SelectMany(l=>l.PadRight(w)).ToList();for(z=E.Count;z-->1;)if(E[z-1]==43)for(d=1,c++;E[z+=d%2<1?w*d-w:d-2]>32;)if(E[z]<44){E[z]=' ';d=d%2>0?z<w||E[z-w]<99?2:0:E[z+1]!=45?1:3;}C.WriteLine(c);}} ``` First it reads in the input, and makes it nice and rectangular, with a " " border so we don't have to do any bounds checking on the horizontal (cheaper to do the checking on the vertical than to put in the extra line). Then it looks back through the rectangle, so it always hits a right-bottom corner. When it hits one of these, it directs itself up, following any +s it meets, and clearing them as it goes (with a space). It stops following when it meets a space. Tested on the five given examples. ``` using C=System.Console; using System.Linq; class P { static void Main() { // read in var D=C.In.ReadToEnd().Split('\n'); int z, // z is position in E w=D.Max(m=>m.Length)+1, // w is width d, // d is direction of travel (1 == horizontal?, 2 == down/right?) c=0; // c is loop count // make all the lines the same length var E=D.SelectMany(l=>l.PadRight(w)).ToList(); // say no to horizontal bounds checking // consume +s for(z=E.Count;z-->1;) if(E[z-1]==43) // right-most lower-most + for(d=1,c++; // go left, increment counter E[z+=d%2<1?w*d-w:d-2]>32 // move z, then check we havn't hit a space (when we do, z is basiclly z - 1) ;) if(E[z]<44) // + { E[z]=' '; // toodles d= d%2>0? // currently horizontal, must go vertical z<w||E[z-w]<99?2 // can't go up, must go down :0 // can go up, go up : // currently vertical, must go horizontal E[z+1]!=45?1 // can't go right, must go left :3 // can go right, go right ; } // output result C.WriteLine(c); } } ``` [Answer] # [Slip](https://github.com/Sp3000/Slip/wiki), ~~51~~ 41 + 2 = 43 bytes ``` $a(`+`-[^ +]*`+(<|>)`|[^ +]*`+#(<|>))+?$A ``` *(Now updated to work with @blutorange's test case at a major cost)* Since @BMac used SnakeEx for this challenge, I thought I'd try and use my [2D pattern-matching language](https://codegolf.stackexchange.com/a/47532/21487) submission, Slip. But because Slip didn't have the features necessary to solve this problem, I've been adding them in over the past few days. In other words, this submission is **not eligible to win**. Run with the `n` flag for number of matches, e.g. ``` py -3 slip.py regex.txt input.txt n ``` [Try it online](https://slip-online.herokuapp.com/?code=%24a%28%60%2B%60-%5B%5E%20%2B%5D%2a%60%2B%28%3C%7C%3E%29%60%7C%5B%5E%20%2B%5D%2a%60%2B%23%28%3C%7C%3E%29%29%2B%3F%24A&input=%20%20%2B--------------%2B%0A%20%20%7C%20%20%2B--%2B%20%20%2B--%2B%20%20%7C%0A%20%20%7C%20%20%7C%20%20%7C%20%20%7C%20%20%7C%20%20%7C%0A%2B-%7C-----%7C-----%7C----%2B%0A%7C%20%7C%20%20%7C%20%20%7C%20%20%7C%20%20%7C%20%20%7C%20%7C%0A%7C%20%2B--%2B%20%20%2B--%2B%20%20%2B--%2B%20%7C%0A%2B------------------%2B%0A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%2B------------%2B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%20%20%7C%0A%20%20%20%20%20%20%20%20%2B-----%2B%20%20%2B-----%2B%20%20%20%7C%0A%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%7C%20%20%20%7C%0A%20%20%2B-----%7C-----------%2B%20%20%7C%20%20%20%7C%0A%20%20%7C%20%20%20%20%20%7C%20%20%2B--%2B%20%20%7C%20%20%7C%20%20%7C%20%20%20%7C%0A%20%20%2B-%2B%20%20%20%2B--%7C--%7C--%2B%20%20%2B---------%2B%0A%20%20%20%20%7C%20%20%20%20%20%20%7C%20%20%2B-%2B%20%20%20%20%20%20%7C%20%20%20%7C%20%20%7C%0A%20%20%20%20%2B------%2B%20%20%20%20%7C%20%20%20%20%20%20%7C%20%20%20%7C%20%20%7C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%2B-------%2B%20%20%7C%20%20%7C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%7C%20%20%7C%20%20%7C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%2B-----%2B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%7C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%2B---%2B&config=n). --- ## Explanation Due to the plethora of new features in this submission, this is a good opportunity to showcase them. ``` $a Set custom anchor at current position ( `+`- Match '+-' [^ +]* Match any number of '|' or '-' `+ Match a '+' (<|>) Either turn left or turn right `| Match a '|' [^ +]* Match any number of '|' or '-' `+ Match a '+' # Prevent next match from moving the match pointer (doubling up on '+') (<|>) Either turn left or turn right ) +? Do the above at least once, matching lazily $A Make sure we're back where we started ``` Slip tries to match starting from every position, and only returns unique matches. Note that we use `[^ +]` — while using `[-|]` would theoretically save two bytes, unescaped `-` at the beginning/end of character classes is not yet implemented in Slip. [Answer] # Ruby 295 ``` F=->i{l=i.lines g={} l.size.times{|y|i.size.times{|x|l[y][x]==?+&&g[[y,x]]=[[y,x]]}} c=->a,b{w=g[b]+g[a];w.map{|x|g[x]=w}} k=g.keys k.product(k).map{|n,o| r,p=n s,q=o ((r==s&&p<q&&l[r][p...q]=~/^\+-[|-]*$/)||(p==q&&r<s&&l[r...s].map{|l|l[p]||c}.join=~/^\+\|[|-]*$/))&&c[n,o]} g.values.uniq.size} ``` Try it online: <http://ideone.com/kIKELi> (*I added a `#to_a` call on the first line, because ideone.com uses Ruby 1.9.3, which does not support `#size` for `Enumerable`s. In Ruby 2.1.5+ the code runs OK.*) The approach is the following: * make a list of all the `+` signs in the input and consider each of them a distinct shape * find horizontal and vertical lines that link two `+` signs and combine their shapes into one * in the end, the number of distinct shapes matches the result Here's a more readable version: ``` def ascii_topology_count(input) lines = input.lines max_length = lines.map(&:size).max # hash in which the keys are corners ("+"s), represented by their [y, x] coords # and the values are arrays of corners, representing all corners in that group corner_groups = {} lines.size.times { |y| max_length.times { |x| if lines[y][x] == ?+ corner_groups[[y, x]] = [[y, x]] end } } # function that combines the groups of two different corners # into only one group combine_groups =-> c1, c2 { g1 = corner_groups[c1] g2 = corner_groups[c2] g2 += g1 corner_groups[c1] = g2 g2.map{|x| corner_groups[x] = g2} } corner_groups.keys.product(corner_groups.keys).map{|c1, c2| y1,x1=c1 y2,x2=c2 if y1 == y2 && x1 < x2 # test horizontal edge t = lines[y1][x1...x2] if t =~ /^\+-[|-]*$/ # p "#{c1}, #{c2}, [H] #{t}" combine_groups[c1, c2] end end if x1 == x2 && y1 < y2 # test vertical edge t=lines[y1...y2].map{|l|l[x1]||' '}.join if t =~ /^\+\|[|-]*$/ # p "#{c1}, #{c2}, [V] #{t}" combine_groups[c1, c2] end end } corner_groups.values.uniq.count end ``` [Answer] # JavaScript (ES6) 190 ~~197 202 215 235 289 570~~ **Edit** Single dimension array instead of 2 dimension, max row size 999 chars (but can be more at no cost, e.g. 1e5 instead of 999) **Edit** Added animated code snippet, see below ``` F=s=>[...s.replace(/.+/g,r=>r+Array(e-r.length),e=999)] .map((c,x,z,d=1,f='-',g='|')=>{ if(c=='+') for(++n;z[x+=d]!='+'||([f,g,e,d]=[g,f,d,z[x-e]==g?-e:z[x+e]==g&&e],d);) z[x]=z[x]==g&&g },n=0)|n ``` **Ungolfed** first try ``` f=s=> { cnt=0 s = (1+s+1).split(/[1\n]/) for(;x=-1, y=s.findIndex(r=>~(x=r.indexOf('+-'))), x>=0;++cnt) { //console.log(y+' '+x+' '+s.join('\n')) dx = 1 for(;dx;) { a=s[y-1],b=s[y+1], r=[...s[y]] for(r[x]=' ';(c=r[x+=dx])!='+';) { if (c=='-') if((a[x]||b[x])=='|')r[x]='|'; else r[x]=' '; } if(a[x]=='|')dy=-1; else if(b[x]=='|')dy=1; else dy=0 r[x]=' ' s[y]=r.join('') if (dy) { for(;y+=dy,r=[...s[y]],(c=r[x])!='+'&c!=' ';) { if (c=='|') if((r[x-1]||r[x+1])=='-')r[x]='-'; else r[x]=' '; s[y]=r.join('') } if(r[x-1]=='-')dx=-1; else if(r[x+1]=='-')dx=1; else dx=0; } } } return cnt } ``` **Animated snippet** ``` F=s=>[...s.replace(/.+/g,r=>r+Array(e-r.length),e=999)].map((c,x,z,d=1,f='-',g='|')=>{if(c=='+')for(++n;z[x+=d]!='+'||([f,g,e,d]=[g,f,d,z[x-e]==g?-e:z[x+e]==g&&e],d);)z[x]=z[x]==g&&g,steps.push(z.map(c=>c?c!=','?c:'':0).join(''))},n=0)|n function go(){var g=grid.value;steps=[];Num.value=F(g);a=_=>{g=steps.shift();if(g){grid.value=g;setTimeout(a, 100)}};a()} ``` ``` textarea { width: 500px; height: 500px; } input {width: 80px} ``` ``` Better viewed full page<br>Input (paste input text - enlarge if needed)<button onclick="go()">Process</button>Loop count:<input readonly id=Num /><br><textarea id=grid></textarea><br> ``` **Test** In Firefox/FireBug console ``` F('\ +--------------+\n\ | +--+ +--+ |\n\ | | | | | |\n\ +-|-----|-----|----+\n\ | | | | | | | |\n\ | +--+ +--+ +--+ |\n\ +------------------+\n\ \n\ +------------+\n\ | |\n\ +-----+ +-----+ |\n\ | | | |\n\ +-----|-----------+ | |\n\ | | +--+ | | | |\n\ +-+ +--|--|--+ +---------+\n\ | | +-+ | | |\n\ +------+ | | | |\n\ +-------+ | |\n\ || | |\n\ |+-----+\n\ | |\n\ +---+') ``` > > 4 > > > ``` F('\ +--------+ +--------+ +--------+\n\ | | | | | |\n\ | +--|-----+ +--|-----+ |\n\ | | | | | | | | | |\n\ +-----|--+ +-----|--+ +--------+\n\ | | | |\n\ +--------+ +--------+') ``` > > 5 > > > [Answer] # Ruby, 178 187 199 212 Better ruby version, creates a function F. Now with more delicious interpreter warnings constantly. ``` b=->n{Q[I]=?~ d=Q[I+n]==(n>1??|:?-)?1:-1 loop{I+=d*n b[n>1?1:N]if Q[I]==?+ Q[I]<?~?4:break}} F=->s{N=s.size;Q=s+?\n Q.gsub!(/^.*$/){$&.ljust N-1} (0..N).find{!(I=Q=~/\+/)||b[1]}} ``` Test it online: [ideone](https://ideone.com/dH76NL) Basically, function `b` starts at any `+`, recursively goes through the loop, setting all `+` to `u`. Thus one loop gets removed each time `b` is called. Function `F` just tries how often we need to call `b` until there aren't any loops remaining. [Answer] # Python 2 - 390 Takes a string with newlines from stdin. It's a pretty simple method golfed a fair bit, but I'm sure not as much as it could be considering how long it is. ``` s=raw_input().split('\n');L=len def R(x,y): b=p,q=x,y;u=v=f=0 while b!=(p,q)or not f: p+=u;q+=v;f=u+v;c=s[q][p] if'+'==c:u,v=[(i,j)for i,j in{(-1,0),(1,0),(0,-1),(0,1)}-{(-u,-v)}if 0<=q+j<L(s)and 0<=p+i<L(s[q+j])and s[q+j][p+i]in['-+','|+'][j]][0];s[q]=s[q][:p]+' '+s[q][p+1:] if c+s[q+v][p+u]in'-|-':p+=u;q+=v print L([R(x,y)for y in range(L(s))for x in range(L(s[y]))if'+'==s[y][x]]) ``` [Answer] # Python 2 - 346 bytes Implemented as a function `c` that takes the file data as input and returns the number of loops. First, the function decomposes the data to a mapping of loop element locations to the element type at that location (e.g. `{(0,0): '+'}`). Then, it uses two mutually-recursive internal functions. The first removes a loop segment from the mapping and decides which locations to check for the subsequent segment. The second checks what kind of loop element is in the selected locations and, if it is compatible with what is expected, calls the first to remove the newly found section. ``` e=enumerate def c(d): D={(i,j):k for i,l in e(d.split('\n'))for j,k in e(l)if k in'+-|'} def f(r,c,R,C,t): if D.get((r,c),t)!=t:g(r,c) elif D.get((R,C),t)!=t:g(R,C) def g(r,c): t=D.pop((r,c)) if t!='|':f(r,c-1,r,c-2,'|');f(r,c+1,r,c+2,'|') if t!='-':f(r-1,c,r-2,c,'-');f(r+1,c,r+2,c,'-') n=0 while D:g(*D.keys()[0]);n+=1 return n ``` ]
[Question] [ What general tips do you have for golfing in Lua? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Lua (e.g. "remove comments" is not an answer). Please post one tip per answer. [Answer] In addition to the ones already posted, here are some tricks I've gathered over time, in no specific order... * For the function calls that only have one parameter delimited by a symbol (`"` for strings, `{` for tables), the parameter doesn't need to be wrapped around parentheses. For example, instead of doing `print("hello")`, you can simply do : `print"hello"` * Remove as much whitespace as possible - this is especially easy to do after a symbol that closes strings (or before one opening), function calls, tables... Instead of `print(42) a=1` you can do `print(42)a=1`. Other example: `print(a and-1 or-2)`. * Use the ternary operator when you can! Instead of `if a>0 then print("hello") else print("goodbye") end`, prefer `print(a>0 and "hello" or "goodbye")`. More info [here](http://lua-users.org/wiki/TernaryOperator). *(This can actually get even better : `print(a>0 and"hello"or"goodbye")`)* * Use the colon-call syntactic sugar when you can : instead of `string.rep(str,12)`, do `str:rep(12)`. That also works on non-variables this way (and only this way) : `("a"):rep(5)` * Instead of doing `tonumber(str)` just do `str+0` * For functions with no parameters, instead of defining them the usual way (`function tick() blabla() end`), you can do : `ticks=loadstring"blabla()"`, which saves 1 or more bytes, depending on the content. Also, if you define multiple functions, localize `loadstring` to a 1-char variable before and you'll save a lot of bytes ;). *Credits to Jim Bauwens for this trick.* * Lua considers empty string (and `0` too unlike other languages) as *true* in conditional tests, so, for example, instead of doing `while 1 do ... end`, save 1 byte by writing `while''do ... end` * `({""})[i]or"s"` is 1 char shorter than `i==1 and""or"s"` and can be written without a whitespace at the beggining, which may save one more byte. [Answer] **Shorten your infinite loop** When you have to use an infinite loop, you may think of using a `while`, but using a label instead is shorter by 2 byte: ``` while''do end ::a::goto a ``` **Use the less space as possible** There's a simple thing you could (ab)use to remove even more spaces from your code. Lua's specs are clear about the name you give to variables: They have to start with a letter. It imply that, sometimes, you can skip on spaces between numbers and functions/variables ``` x=0>1 and 0or 1print(x) ``` The possibility of removing the space depends on the letter following the number, here's the letter that won't allow you to do this: ``` a,b,c,d,e,f -- They would be interpreted as hexadecimal x -- only fail when after a 0, other number are fine -- (0x indicates the following is an hexadecimal number) ``` By using this, and paying attention to how you call your variables, you can make most of your source codes space-free. Picking up an example already here, and using this advice, here's one more byte you could shaved off :). ``` print(a and-1 or-2) print(a and-1or-2) ``` **Use the right input method** If we look at the boilerplate and cost for each *major* type of input, here's what we have: ``` function f(x)x end io.read() arg[1] ``` Each one of this method allow us to take 1 input, with the function being the one with the heaviest cost (but allows us to take a table as input) We can now see that using command-line argument is the way-to-go if you want to golf, but be aware: it can be even shorter ``` arg[1] ... ``` The `...` are a bit special in lua, it's a variable containing the unpacked content of `arg`, or the unpacked parameters in case of a variadic function. When you will have to get more than one input, and use each of them, it can be good to do save them in a variable. Here's some ways to save 2 inputs in variables ``` a=arg[1]b=arg[2] -- highly un-efficient, costs 8 bytes by variable a,b=unpack(arg) -- costs 15, but at least doesn't depends on the number of argument a,b=... -- only costs 7 ``` and here are the shortest call you could have done without the variables: ``` ... -- using a allow a gain of 1-2 bytes at each use arg[2] -- using b allow a gain of 4-5 bytes at each use ``` From the point where you have 3 argument, or when you use 2 arguments, with one used twice, you're already gaining bytes due to `a,b=...`! :) **Almost never use if!** There's near no cases where using a if/elseif/if statement will cost less than a ternary. the boilerplate for such a statement is really heavy: ``` -- exemple with dumb values if 1>0then v=1 else v=0 end v=1>0 and 1or 0 ``` With a simple example, you already save 12 bytes, when you have to do some elseifs, it become more and more important, so be aware of that! Also, ternaries in lua are *special*, there's some condition in how they work, for those interested, I'll explain it below: Ternaries in lua are of the form `<condition> and <case true: have to be a true value> or <case false: can be anything>` First of all, let's see the truth table of the `or`. A `or` can be considered as a function: it always return a value, here's the value it returns: ``` x | y ||x or y ------||------- 0 | 0 || y 0 | 1 || y 1 | 0 || x 1 | 1 || x ``` That's what allow us to construct our ternary. The `and` is what allow us to evaluate the condition, it will always return `y` if `x and y` evaluates to true. The problem with it is that it will fail if we want a `nil` or `false` to be return when the condition is `false`. For instance, the following will always return 5, despite the condition being true. ``` v = true and false or 5 ``` Here's a step by step evaluation of a ternary to explain how it works (it will be useful for when you have to nest them :)) ``` -- let's use our dumb ternary = true and false or 5 -- and statement will be evaluated first, leading to = false or 5 -- and we saw how the or works = 5 ``` [Answer] I have already thought of one. I don't know if it works in some other languages, but Lua is the only one I know what allows you to store functions in variables. So if e.g. `string.sub`is used multiple times in your program, use e.g. `s=string.sub`. [Answer] It's a pretty verbose language for golfing... but some general tips that come to mind are: * Try to avoid conditionals, since `if`...`then`...`else`...`end` is a major waste. * Instead, try to focus on language constructs that are shorter, e.g. `for i=1,5 do`. * The `#` operator is pretty great for golfing (and in general). [Answer] ## Variadic Functions The main variadic function that will trouble you is `print()`. For instance, when you're using it along `String.gsub()` it will print the string you modified AND the number of times `gsub` triggered. To supress that second output, encapsulate your `gsub` in parens to force it to return only one value ``` print(("").gsub("aa",".","!")) -- outputs "!! 2\n" print((("").gsub("aa",".","!"))) -- outputs "!!\n" ``` [Answer] I have compiled several tips as well. I'm sure some of mine will overlap with ones already stated, but I'll include them anyhow in the vein of creating a more complete answer. --- **Assign repeated functions to variables** Lua allows you to assign functions to variables. Even one character variables. This means if you repeat the function `string.sub(x, y)` more than twice, you will get a benefit from assigning it to a variable. Without assigning to a variable (69 characters): ``` print(string.sub(x, y)) print(string.sub(x, y)) print(string.sub(x, y)) ``` Assigning to a variable (51 characters): ``` s=string.sub print(s(x,y)) print(s(x,y)) print(s(x,y)) ``` There's cases where you can take this yet a step further. Lua allows an OOP to string manipulation, like so: `str:sub(x, y)` or `str.sub(x, y)` This opens up new options for our code. You can assign a variable to the function by it's reference as shown (46 characters.) ``` s=z.sub print(s(x, y)) print(s(x, y)) print(s(x, y)) ``` --- **Use the most efficient way to parse strings** You may find yourself using a `for` loop and `string.sub` to iterate character by character in Lua. Sometimes this may work best, depending on your needs, but other times, string.gmatch will work in fewer characters. Here's an example of both: ``` s=io.read() for a = 1, s:len() do print(s:sub(a, a)) end for i in io.read():gmatch('.') do print(i) end ``` And when golfed, the difference is more notable: ``` s=io.read()for a=1,s:len()do print(s:sub(a, a))end for i in io.read():gmatch'.'do print(i)end ``` --- **Restructure Assignations To Optimize Whitespace** In Lua, you do not have to put a space character between a closed parentheses or a end quotation mark and the next character. So far, I've found two cases where restructuring with this in mind will cut characters. * Assigning variables: ``` x,y=io.read(),0 print(x) vs. y,x=0,io.read()print(x) ``` * If Statements: ``` if x:sub(1,1)==1 then vs if 1==x:sub(1,1)then ``` --- **Return the fewest characters possible** If you must return a true or false value, then it seems you must necessarily use at least 5 characters for the return value. In reality the following works just as well: ``` return true return false vs return 1>0 return 0>1 ``` [Answer] The expression `a==1 and 1or 0` can be shortened to `#{[a]=0}`. This works because the array length operator `#` is actually measuring the number of consecutive integer array indices starting at 1. (Arrays in Lua are 1-based, but they allow assignment at other indices, even those that are negative or floating point.) If there no element at index 1, it will always report a length of zero. And `{[a]=0}` is an anonymous array with an element of value `0` at index `a`. How many bytes this will save depends on the circumstance. For example, if you're already using `n%i<1` as a shorthand for `n%i==0` to test divisibility, then changing `n%i<1 and z or 0` to `z*#{[n%i+1]=0}` saves 2 or 3 bytes, depending on whether it's followed by a symbol or a keyword/identifier. [Answer] These are Lua only (I think) optimizations: Strings are automatically converted into numbers when doing arithmetic operations on them. Just watch out for conditional statements, they do not automatically convert. This is great for taking user input as numbers while saving space. Switching the contents of two variables does not require a temporary variable. `a,b=b,a` will swap the values of a and b. Also, to extend upon what was said above, any alphanumeric character can touch a non alphanumeric character. So `a,b=io.read():match"(.+)/(.+)"u,v=a,b` is a perfect, working script, even with the lack of whitespace. [Answer] ### Combine Local Variable Assignments Instead of: ``` local a=42 local b=17 local c=99 ``` Use parallel assignment: ``` local a,b,c=42,17,19 ``` 6 bytes saved for each variable! ### Declare Local Variables via Unused Function Parameters Instead of: ``` function foo(a,b) local c,d ... end function bar(a,b) local c,d=42,17 ... end ``` Use ``` function foo(a,b,c,d) ... end function bar(a,b,c,d) c,d=42,17 ... end ``` 6 bytes saved (minus 1-2 bytes for each variable that might be duplicated). [Answer] ## Know how to output There's two main method of outputting in lua ``` io.write() -- outputs without trailing newline print() -- outputs with trailing new line and shorter by 3 bytes ``` When you have to concatenate multiple times, you could shorten that by using `io.write()` assigned to a one letter variable instead of the standard concatenation operator `..` ``` i(a) -- i was defined as io.write s=s..a ``` You gain 2 bytes at each call while paying some upfront ``` i=io.write -- longer by 6 bytes s="" ``` You're even on the third concatenation, and start gaining byte on the fourth. [Answer] A bunch of tips in no particular order: * `string` is pretty long name. Efficiently, `('').char` is same as `string.char`. Even better results can be achieved if you use it together with a semicolon on variables: `a=...; print(a:sub(1, 5))`, but some `string` functions don't take strings as input. * Lua has automatic conversions between strings and numbers for most cases, so `tonumber` and `+0` often only waste bytes. * Always use `load'your function code here'` instead of `function()your function code here end`. Access function arguments using `...` inside. * Some string functions in Lua can be used in unintended ways! For example, `a:gsub('.',load'my function')` seems to be the shortest way to iterate over chars in a string * While the string engine is powerful, beware of its power when using user input as patterns! Because of that, you might have to use `a:find('.',1,1)` (to test for this issue, try including `%` at various places in your input and check out results). Countless ideas broke because of Lua trying to parse input as pattern. * `nil` is three bytes, `_` is one (it is just random name which most likely doesn't exist). Also, any digit will work as truthy value. * Know your logic behind `x and i or o`. It isn't just a ternary operator - it is a complete logical expression. In fact, it means the following: "if `x` is truthy, try `i`. If either x or i is falsy, return o". So if `i` is not truthy, result is `o`. Also, both `and` or `or` parts can be omitted (`x and i`, `x or o`). * Use integer division by one instead of `math.floor`: `5.3//1==5.0`. Please note that the resulting number always follows the type of input one (integer/float). ]
[Question] [ Your task is to write a short program that represents a large (infinite) ordinal, using a well-ordering of the set of positive integers. Your program will take two different positive integers and indicate which one is greater in your chosen well-ordering. The order type of the well-order is the represented ordinal. The challenge is to min-max your code size and the represented ordinal respectively. # Explanation Usually the positive integers are ordered like so: ``` 1, 2, 3, 4, 5, ... ``` In this ordering, the expressions: `2 < 5`, `1 < 2`, `3 < 19`, are true, as usual. The expressions `5 < 2`, `10 < 3`, and so on, are false. However, we can order the positive integers also in the following way: ``` 2, 4, 6, 8, 10, ..., 1, 3, 5, 7, ... ``` Here all the even numbers are followed by all the odd numbers. Now the expressions `2 < 1`, `6 < 8`, `1 < 5`, `100 < 51` are true, and the expressions `101 < 2` `5 < 3` and `120 < 110` are false. This is another well-ordering: ``` 2, 4, 6, 8, 10, ..., 3, 9, 15, 21, ..., 5, 25, 35, 55, ..., 7, 49, 77, ..., ..., 1 ``` First we have all the even numbers, then all the remaining numbers that are divisible by 3, then ones that are divisible by 5 and so on. Finally, at the very end is 1. Notice that we have a nested "...". This is allowed. What is not allowed is a "..." that starts from the left. ``` 1, 3, 5, 7, 9, ..., ..., 10, 8, 6, 4, 2 ``` This is not a well-order (just a total order). A more rigorous way of stating this rule is that every nonempty subset must have a smallest element. Here the subset of even numbers doesn't have a smallest element. Another way of looking at this, is to imagine starting from the right and walking to the left. You can jump over an arbitrary (possibly infinite) amount of numbers, but you have to always go left. If the numbers are well-ordered, your walk will always take a finite amount of steps. In this example however, you can just stay on the even side, by never jumping over the three dots, thus never reaching the beginning. Notice that if you lay the three well-orders on top of each other like so: ``` 1, 2, 3, 4, 5, ... 2, 4, 6, 8, 10, ..., 1, 3, 5, 7, ... 2, 4, 6, 8, 10, ..., 3, 9, 15, 21, ..., 5, 25, ..., ..., 1 ``` They have different "length". The bottom one is the longest, and the top one is the shortest. The "length" is called the "order type", and it can be measured with an ordinal. Our first well-order has order type \$\omega\$, the second one \$\omega\cdot2\$ and the third one is \$\omega^2+1\$ Your program will compare two positive integers, according to a well-ordering of your choice. That way your program will represent the order type of your well-order. For more info on ordinals, visit the Wikipedia page for [ordinals](https://en.wikipedia.org/wiki/Ordinal_number) and [ordinal arithmetic](https://en.wikipedia.org/wiki/Ordinal_arithmetic). For more ordinals, visit [Googology Wiki](https://googology.wikia.org/wiki/Ordinal). Also check out the [previous infinite ordinal question on Code Golf](https://codegolf.stackexchange.com/questions/48931/make-the-largest-infinity-that-you-can). ## More ordinal examples \$\omega\$ `1, 3, 2, 4, 5, 7, 6, 8, ...` \$\omega^2\$ `1, 2, 4, 8, 16, ..., 3, 5, 6, 9, 10, 12, 17, 18, ..., 7, 11, 13, 14, 19, 21, 22, ..., 15, 23, 27, ..., ...` (popcount then value) \$\omega^2+\omega\$ `2, 4, 8, 16, 32, ..., 3, 9, 27, 81, ..., 5, 25, 125, ..., ..., 1, 6, 10, 12, 14, ...` \$\omega^\omega\$ `1, 2, 4, 8, 16, ..., 3, 6, 12, 24, 48, ..., 9, 18, 36, 72, ..., ..., 5, 10, 20, 40, 80, ..., 15, 30, ..., 45, ..., ..., ..., etc.` (reverse lexiographic ordering of the [standard form](https://en.wikipedia.org/wiki/Fundamental_theorem_of_arithmetic)) # Rules You must pick a well-ordering on \$\mathbb{Z}^+\$. A well ordering is a binary relation \$<\$ such that for all distinct elements \$a\$, \$b\$, \$c\$, \$a<b\space\veebar\space b<a\$ and \$a<b\space\land\space b<c\implies a<c\$ and also for every nonempty subset \$S\$ of \$\mathbb{Z}^+\$, there is a minimal element \$m\$, so that for every other member \$n\$ in \$S\$, \$m<n\$. Your program will receive two distinct positive integers \$a\$ and \$b\$ in some reasonable format. The program will output TRUE if \$a<b\$ and FALSE otherwise. Instead of "TRUE" and "FALSE", you can choose any two distinct output strings, such as ("true", "false"), ("1", "0") and so on. Instead of reading from stdin/cmdline and writing to sdtout, you can make a function that takes two integers. The function should still have only two possible (distinct) return values, although they don't have to be strings. If your programming language has no built-in bignum support, you can assume that a native integer datatype has infinite range (doesn't overflow). # Scoring Your score is the tuple \$(Value, Bytes)\$ where \$Value\$ is the represented ordinal and \$Bytes\$ is the number of bytes in your program. For example, if you implement the ordinal \$\omega^3+\omega\$ in 6 bytes, your score is \$(\omega^3+\omega, 6)\$. To compare scores we define a partial order \$\ge\$ so that \$(v\_0, b\_0)\ge (v\_1, b\_1)\$ iff \$v\_0\ge v\_1\$ and \$b\_0\le b\_1\$. A score \$(v\_0, b\_0)\$ is better than a score \$(v\_1, b\_1)\$ iff \$(v\_0, b\_0)\ge (v\_1, b\_1)\$ and the scores are not equal. In other words, your submission is better than another submission, if you achieve more bang-for-buck. That is, you achieve a bigger ordinal with the same number of bytes, or achieve the same ordinal, with a smaller amount of bytes. And obviously if you achieve a bigger ordinal with fewer bytes, your submission is better. This does mean that some scores can't be compared. For example, \$(\omega\cdot 2, 2)\$ and \$(\omega^2, 4)\$ are incomparable. You are a winner if there is no submission that is better than yours. If there are two or more submissions with the exact same score, the one submitted first is the winner. Since some scores can't be compared with others, there can be multiple winners. You are free to make multiple submissions, and possibly have multiple winning ones. # List of winning submissions | Bytes | Value | Language and Author | | --- | --- | --- | | 1 | \$\omega\$ | [Polyglot - community wiki](https://codegolf.stackexchange.com/a/237343/84290) | | 6 | \$\omega^\omega\$ | [Pyth - Anders Kaseorg](https://codegolf.stackexchange.com/a/237303/84290) | | 12 | \$\omega^\omega+1\$ | [Husk - Dominic van Essen](https://codegolf.stackexchange.com/a/237301/84290) | | 17 | \$\varepsilon\_0\$ | [Pyth - Anders Kaseorg](https://codegolf.stackexchange.com/a/237303/84290) | | 208 | \$\phi\_{\Omega^\omega}(0)\cdot\omega\$ | [Haskell - Grain Ghost](https://codegolf.stackexchange.com/a/237294/) | | 218+2\$n\$ | \$\phi\_{\Omega^\omega}(0)^n\cdot\omega\$ | [Haskell - Grain Ghost](https://codegolf.stackexchange.com/a/237294/) | [Answer] # [Pyth](https://github.com/isaacg1/pyth), \$(ω^ω, 6)\$ ``` >_PE_P ``` [Try it online!](https://tio.run/##K6gsyfj/3y4@wDU@4P9/QyNjLhNTMwA "Pyth – Try It Online") Compares the reversed prime factorizations of the two inputs. # [Pyth](https://github.com/isaacg1/pyth), \$(ε\_0, 17)\$ ``` L_SmylP#U_dPb>yEy ``` [Try it online!](https://tio.run/##K6gsyfj/3yc@OLcyJ0A5ND4lIMmu0rXy/39DI2MuE1MzAA "Pyth – Try It Online") ``` L def y(b): Pb prime factors of b m map over d: _d -d U range [-d, …, -1] P# filter for (negated) primes l count y recursively call y S sort _ reverse >yEyQ y(second input) > y(first input) ``` The ordinal corresponding to each positive integer is given by $$α(p\_{i\_0}p\_{i\_1} \dotsc p\_{i\_{c-1}}) = \sum\_k ω^{α(i\_k)}$$ where \$p\_i\$ is the \$i\$th prime, and the sum on the right is taken in nonincreasing order of \$α(i\_k)\$ (since ordinal addition isn’t commutative). This allows us to build any ordinal with a finitely long [Cantor normal form](https://en.wikipedia.org/wiki/Ordinal_arithmetic#Cantor_normal_form). For example: ``` α(1) = 0, y(1) = [] α(2) = 1, y(2) = [[]] α(4) = 2, y(4) = [[], []] α(8) = 3, y(8) = [[], [], []] α(16) = 4, y(16) = [[], [], [], []] α(3) = ω, y(3) = [[[]]] α(6) = ω + 1, y(6) = [[[]], []] α(12) = ω + 2, y(12) = [[[]], [], []] α(9) = ω·2, y(9) = [[[]], [[]]] α(18) = ω·2 + 1, y(18) = [[[]], [[]], []] α(27) = ω·3, y(27) = [[[]], [[]], [[]]] α(7) = ω^2, y(7) = [[[], []]] α(14) = ω^2 + 1, y(14) = [[[], []], []] α(21) = ω^2 + ω, y(21) = [[[], []], [[]]] α(49) = ω^2·2, y(49) = [[[], []], [[], []]] α(19) = ω^3, y(19) = [[[], [], []]] α(5) = ω^ω, y(5) = [[[[]]]] α(10) = ω^ω + 1, y(10) = [[[[]]], []] α(15) = ω^ω + ω, y(15) = [[[[]]], [[]]] α(35) = ω^ω + ω^2, y(35) = [[[[]]], [[], []]] α(25) = ω^ω·2, y(25) = [[[[]]], [[[]]]] α(13) = ω^(ω + 1), y(13) = [[[[]], []]] α(23) = ω^(ω·2), y(23) = [[[[]], [[]]]] α(17) = ω^ω^2, y(17) = [[[[], []]]] α(11) = ω^ω^ω, y(11) = [[[[[]]]]] α(31) = ω^ω^ω^ω, y(31) = [[[[[[]]]]]] ``` # [Pyth](https://github.com/isaacg1/pyth), \$(ε\_0, 19)\$ ``` L_S.ey-bkx1_jb2>yEy ``` [Explanation](https://codegolf.stackexchange.com/revisions/237303/8) for this old answer, which is now obsolete, but may be of interest for porting to languages lacking prime-related builtins. [Answer] # [Haskell](https://www.haskell.org/), \$(\omega, 3)\$ This solution is dead simple, really can't be beat in Haskell. ``` (<) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P81Ww0bzf25iZp5tQVFmXolKmoKRgonpfwA "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), \$(\omega+n,19+2\left\lfloor\log\_{10}(n+1)\right\rfloor)\$ Here's a scheme to get \$\omega + n\$ for any \$n\in\mathbb{N}\$. Just replace the `9`s below with one more than \$n\$. This will make the first \$n\$ numbers bigger than all other numbers but otherwise compare normally. ``` x#y=(x<9,x)<(y<9,y) ``` [Try it online!](https://tio.run/##y0gszk7NyfmfmVuQX1Si4JJYkqjnk1lc8r9CudJWo8LGUqdC00ajEkhXav5Pzs8tUEhUSKpJtLVNsnUNrElUTrL1CeGCidu6h3DlJmbm2RYUZeaVqBQDTXSqVADLRhvq6RkaGMT@BwA "Haskell – Try It Online") Looks like the leader board should now have an infinite number of winners. However we can beat an infinite number of these pretty easily. Most of this can just be done by fiddling with things a little bit up until we hit 26 bytes. So I will present my scores for 21, 23 and 25 without individual commentary. They should be pretty clear modifications of the 19 byte case. ### 21 bytes, \$\omega+98\$ ``` x#y=(x<99,x)<(y<99,y) ``` ### 23 bytes, \$\omega+387420488\$ ``` x#y=(x<9^9,x)<(y<9^9,y) ``` ### 25 bytes, \$\omega+9^{99}-1\$ ``` (.q).(<).q q x=(x<9^99,x) ``` Luckily this wraps up by 26 we can get to a much larger ordinal: # [Haskell](https://www.haskell.org/), \$(\omega\cdot n,26+\left\lfloor\log\_{10}(n)\right\rfloor)\$ *Thanks to the OP for pointing out that I didn't need division for this.* Another scheme much like the last, replace `9` with the desired number. ``` (.q).(<).q q x=(mod x 9,x) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P81WQ69QU0/DRlOvkKtQocJWIzc/RaFCwVKnQvN/bmJmnm1BUWZeiUqagomCsel/AA "Haskell – Try It Online") Once again we can use kolmogorov complexity to improve some of these. Here's a few that are currently records for their respective program sizes. ### 28 bytes, \$\omega\cdot 9^9\$ ``` (.q).(<).q q x=(x`mod`9^9,x) ``` ### 29 bytes, \$\omega\cdot 9^{99}\$ ``` (.q).(<).q q x=(x`mod`9^99,x) ``` ### 30 bytes, \$\omega\cdot 9^{9^9}\$ ``` (.q).(<).q q x=(x`mod`9^9^9,x) ``` ### 31 bytes, \$\omega\cdot 9^{9^{99}}\$ ``` (.q).(<).q q x=(x`mod`9^9^99,x) ``` ### 32 bytes, \$\omega\cdot 9^{9^{9^9}}\$ ``` (.q).(<).q q x=(x`mod`9^9^9^9,x) ``` ### 33 bytes, \$\omega\cdot 9^{9^{9^{99}}}\$ ``` (.q).(<).q q x=(x`mod`9^9^9^9,x) ``` # [Haskell](https://www.haskell.org/), \$(\omega^\omega, 63)\$ Implements the order for \$\omega^\omega\$ in the question. ``` n#1=[] n#a|mod a n<1=n#div a n++[n]|m<-n+1=m#a y=(.(2#)) f=y.y(<) ``` [Try it online!](https://tio.run/##PY6xCoMwFEX3fEUgHRRpMJ19S2np4lJwE4dnVRqaPK2mhUD@PdVCu93DPXDvHZdHb0zUdhpnx58vNHrQfcdP6FCWenGRhIK6YSQw2LHjyKlQQKLT7y1nWU1NsMWeMgVWIPOQyOQg0pQN4KVPijTeRjutbhsQoIXzNQwbQVmxXwOXilnUBNOsye3@43JZXx09/3q1klLleRM/ "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), \$(\phi\_{\Omega^\omega}(0)\cdot\omega,208)\$ This implements the same ordinal as in [cardboard\_box's answer](https://codegolf.stackexchange.com/a/237306/56656). It's slightly bigger than the small Veblen ordinal \$\phi\_{\Omega^\omega}(0)\$. This could certain be golfed more. I'm not sure that either the type or the instance are really necessary, but for now it puts Haskell back on the leaderboard. ``` data T=T[T]deriving Eq instance Ord T where a<=b=a==b||a<b;T a<T b=any(T a<=)b||(all(<T b)a&&(l a,a)<(l b,b)) l=length c x|odd x,(y,t)<-c$div x 2=(T t:)<$>c y|1>0=(div x 2,[]) g f x|(y,t)<-c x=f(T t,y) g.g(<) ``` [Try it online!](https://tio.run/##hVLbitswEH3XVwxsWGxwir2l0Iu1T01LYWEp67cQythWZFFZztrKOqHpt6cj52bnQjHBztGZc86MpsDmt9B6@2d8B09o5BKlgBeLJkddGfFV1OpNGQl347/bHC1CwpNpMssP@OSVKdMQPxPwXOeQQFuIWgDGPOXIebrZYJx@SQhIgBCz9tw39@nAQ609B/t4f@9pwAD9mN5pkPo@01wLI23BMlhtqjyHVeCtA@vH42yUqzdYwQMnLfvZj0ePGaw30WPIvf1JMJ35TMKcSg9FsOJzxw/WPptz@U56sb899nFs4qWoWkgYG4/huRQSWQscqOXpLKDfrDv4YayQoobKESCNwoi1vxT/cKoCW4EtxI7B2oOGU7gl069wmmFEqk42@tSxJ4tG0ZWAwaUsLBNhP9elqBjQu5AUU4Qk@BB1zG9iLuoSDbW8FNaSdZ0rg5rJ8Czupfqt2p2Piy6d08f3jJWoDM8rBrColbEwggyoreH/c8DlHABOjhFyHLB4XaJu9gPuMatygbR/LT2cw@TnoEg1oEXT0KAp@uXYr@t0Qk9J73DuGtiF7qsPbpCsZC3Q0rBObtcM9km/J7eTDu/yakq3DldTitPghht0PeH/5kE@7SHvwOrM67Qg2dmGqKYz0FhL0fSbKXGlymUJ0zZo20CEgQxnzkmGF03J4Xrs7S9Ql6dDt/8A "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), \$(\phi\_{\Omega^\omega}(0)^n\cdot\omega,218+2n)\$ This example code at 222 bytes, iterates the previous algorithm twice. Giving \$\phi\_{\Omega^\omega}(0)^2\cdot\omega\$. ``` data T=T[T]deriving Eq instance Ord T where a<=b=a==b||a<b;T a<T b=any(T a<=)b||(all(<T b)a&&(l a,a)<(l b,b)) l=length c x|odd x,(y,t)<-c$div x 2=(T t:)<$>c y|1>0=(div x 2,[]) g f x|(y,t)<-c x=(T t,f y) r=g$g id f=(.r).(<).r ``` [Try it online!](https://tio.run/##hVPvi9pAEP2@f8XAyZG0URKPQq9171NtKRwc5fJNpKxmXJcmG2@zGqXe325nE3/GSAkSeTvz3pvZl7ko/mCa7v527@BZaLkUEuHVCp2INNf4DY1aKS3hrvu@S4QVEPN4FI@TAz58Y0oXVD9FeDEJxFDO0SCIAZ9wwflkuxWDydeYgBgI0RvP/ec@HXgiTT0H@@L@3ktBBMIf0HsSTHyfpTxFLe2cTWG9zZME1oG3Caw/6E47iVrBGvqcuOwXf9B5msJmGz2F3NufBKOxzyTMqPXQBOuqPJjBxmeGy44ElbAZ93rG73kDv2d2x6mOI73O8xJixrpdeMlQClYCB1rAaBzQb1wd/NQWJRrIXQFMojBi5W/FP526wOZg51hXsPLA4Rhu0Zx3OM4wIlZHGz1W1cNFoeiCQIulnFuG4bmva1K8KK9Mkk0MibAfVZXfcYYmE5pGXqK1JG0SpUXKZNiwe81@q7fWcdalU/r8UK9kf1gqCwUNCCnObL5CUzCDmQsRh@jxw0P/I60wE0rzJGcAC6O0hQ64awPaxBXUgrkBm5hswWrdM9Q0FEyT3jS5TZPYHFgJOwYB35YiLfZBONVO82wh6Ksp6eEchr8umlRBKyoKCgSt@Doe7TwV0XN8djhzM9VznLNfJI2kpEFh6VJPam0Ce6c/4ttOLzPX6tLFttVltdya@TLp7Q7/tw/SKQ9@L6QaWqcgTxtJVkUlkAojsTgfJhNrlS0zGJVBWQYYBjIcOyUZXg3VCMhe/gp1fip09w8 "Haskell – Try It Online") Every time we add a `g$` to the front of the definition of `r` we add 1 to the power at the cost of two bytes. --- ## Haskell Leaderboard ~~Since Haskell has been complete removed from the main leaderboard,~~ for now I am maintaining a short list of Haskell winners here | Bytes | Value | Author | | --- | --- | --- | | 3 | \$\omega\$ | Grain Ghost | | 19 | \$\omega+8\$ | Grain Ghost | | 21 | \$\omega+98\$ | Grain Ghost | | 22 | \$\omega\cdot 2\$ | [xnor](https://codegolf.stackexchange.com/a/237304/56656) | | 24 | \$\omega\cdot 4\$ | [xnor](https://codegolf.stackexchange.com/a/237304/56656) | | 25 | \$\omega\cdot 12\$ | [xnor](https://codegolf.stackexchange.com/a/237304/56656) | | 26 | \$\omega\cdot 32\$ | [xnor](https://codegolf.stackexchange.com/a/237304/56656) | | 27 | \$\omega\cdot 99\$ | Grain Ghost | | 28 | \$\omega\cdot 9^9\$ | Grain Ghost | | 29 | \$\omega\cdot 9^{99}\$ | Grain Ghost | | 30 | \$\omega\cdot 9^{9^9}\$ | Grain Ghost | | 31 | \$\omega\cdot 9^{9^{99}}\$ | Grain Ghost | | 32 | \$\omega\cdot 9^{9^{9^9}}\$ | Grain Ghost | | 33 | \$\omega\cdot 9^{9^{9^{99}}}\$ | Grain Ghost | | 34 | \$\omega^{10}\$ | [xnor](https://codegolf.stackexchange.com/a/237304/56656) | | 53 | \$\omega^\omega\$ | [AnttiP](https://codegolf.stackexchange.com/a/237342/84290) | | 208 | \$\phi\_{\Omega^\omega}(0)\cdot\omega\$ | Grain Ghost | | 218+2\$n\$ | \$\phi\_{\Omega^\omega}(0)^n\cdot\omega\$ | Grain Ghost | [Answer] # [Python 2](https://docs.python.org/2/), \$\psi\_0(\Omega^{\Omega^\omega})\cdot\omega\$ with respect to Buchholz's psi, 266 bytes ``` l=len T=lambda i,s='(',d=1:T(i/2,s+['),','('][i%2],d+i*2%4-1)if d else(eval(s)[0],i) L=lambda A,B:any(A==b or L(A,b)for b in B)or all(L(a,B)for a in A)and(l(A)-l(B),0)<(0,next((L(a,b)for a,b in zip(A,B)if a!=b),0)) def f(a,b):A,a=T(a);B,b=T(b);return(a,0)<(b,L(A,B)) ``` [Try it online!](https://tio.run/##hVTLbtswEDxbX7GBUZismVaSe0orFDZQ9OKj0R4MJ6AsOmEqUwKp1HF/Pl0@9HJSND5EmhkOl7vi1OfmoVLpy0uZlUJFm6zkx7zgIJnJZmTGiiy52RD5MWVmvp1RNmOI7rbyXbpjxVy@T999uk6oPEABojSCiN@8JIZu4x2TNFq3dku2uuHqTJZZlkOlYU2WLKcHfMpBKlhRfOJlSdaEs5XDucWXlKuClGRJr0uyoiymX0jMlHhuiJN6C/xvxX9kja4rWwy/ynKrplEhDnBwypsl49mGcPp5xXJ8yOlnLZonrZC1vjlbu@X0ZQobYRpoHngDG6h1VQtdnqHRXJmSN8KAejrmQhtoKkQFAnPQ4silKoSONnd7bhDLYBtNtnEeMyCUAXbEvSbhPQnvcZwggMhIMwAHwhYdq2NkHOHgS6JbY9nRHvb3psJzqNtFkW2wZPaUrDui7XY45U00wX7jF0LhKgMy1lFkJ5pLI@Db817UjawUmf3Ulbp3fbua0SgadnsNp0r/MsANiOda7BtRQKXAVEfhG/0hwvY3d77prsG2lZd/U4iR8E26IBJLtH0aEqkjAtNzU1h4K0LHZlM4AZFHfi@VcMXPsGwFWOk9p2ETu2awyi6Zhwo6tuU9mYbNwiQG5Z1aT0/1y9LO1JL@AD27OPWOuGHnidvdpgNLx3nWUReertYx3RfU86jo6JFDf9yBJB3WFmqwe1h@0c2JjBtxuj31kyKjTiDV9ddzZHzgV2vJ4EwjuiVJV9BA4O7fRVmiNrKsVNxtflFbyw8KvLCZwnd@PPJ4sMOIrXQhFS@hOuDnhp@c0IrrM/wQOQY3PEihud4/nIHXNddCNeX5q72//gLbG4vxdS8Iikl/h6i9olbx2CvkHPPgDdmE443rsa3cIZaPsUfccWITYY15yqmNelXhvfYJjNTrOFjxwt1t2FdHrFyaSrlcwGBYlqZy7oAhjlYuB0L2hiSQqglBMMEedcnDvGXoWTRxKRyigdl0CLkbgCQAFnLAyQJJHD6OJCxJvMQBQRF7j7RXeI80mCZJUCxaRRIUi1YRO5MpfLKK3b8HZo/6/3l1qn5cFrqYloMed35Wh9GsDv@ZFS59NapaI0pmNsgN1NwYUXywxMtf "Python 2 – Try It Online") At least I think that's how this ordinal is written. It's a little bigger than the [Small Veblen ordinal](https://en.wikipedia.org/wiki/Small_Veblen_ordinal). `T` is a bijective function that maps natural numbers `n` to tuples `(tree,remainder)` of ordered trees and natural numbers. It does so by treating the reversed binary representation of the input as a sequence of `(`s and `)`s, prepended by an extra `(`. Once the initial `(` is given a matching `)`, the unused bits form the remainder. For example, `37` is `100101` in binary, which gets reversed to `101001` which becomes `( ()()) 1`, giving `(()())` as the tree and `1` as the remainder. `L` is a well ordering of ordered trees, the ordinal of which is the small Veblen ordinal. It is taken from Jervell, Herman Ruge (2005), "Finite Trees as Ordinals" (which I found via the Wikipedia article linked above). I horizontally mirrored it because it made the code shorter. `f` accepts 2 natural numbers, converts them to `(tree,remainder)` tuples, and compares these by remainder first, then by tree. Numbers which map to tuples in the form `(tree, 0)` form the small Veblen ordinal. Tuples in the form `(tree, 1)` come next, then `(tree, 2)`, `(tree, 3)` etc. for a total of \$\omega\$ copies of the small Veblen ordinal, which I think is written \$\phi\_{\Omega^\omega}(0)\cdot\omega\$. Note: while I defined `f` in terms of non-negative integers, the ordinal doesn't change if you only use strictly positive integers. [Answer] # Polyglot, \$(\omega, 1)\$ Feel free to add languages to the list. ``` < ``` Try it in: * [Actually](https://tio.run/##S0wuKU3Myan8/9/m/39DUxNzE2NTQyNTAzMzQ0NLLgsjM0tLA2Mzc1NjQ0MLQyMA "Actually – Try It Online"). Outputs `0`/`1`. * APL family languages: [APL](https://tio.run/##SyzI0U2pTMzJT///P@1R2wSb//8NTU3MTYxNDY1MDczMDA0tFdIULIzMLC0NjM3MTY0NDS0MjQA), [J](https://tio.run/##BcHJEQAgCASwViiB5cbRdnzY/x@TN3PP2jNwS1OHOEcATZdKops10hUoyAc), [K](https://ngn.bitbucket.io/k/#eJwFwckRACAIBLA/1bDcqJ04fum/BJNZh2gu3NLUIc4RQO+S6GaNdAUK8j66FgjN), [BQN](https://mlochbaum.github.io/BQN/try.html#code=RuKGkDwKMTU0NzQzNTEyNTA2NjExOSBGIDgyNjk5MDM2NzUzMTE4MTI=). Outputs `1`/`0`. * [Jelly](https://tio.run/##BcHJDQAgDAOwlZrelViHD2IBpg/22fc@cpFEeLkFNCQTGLbmjFhWGNDQDw "Jelly – Try It Online"). Outputs `1`/`0`. * [Keg](https://tio.run/##y05N///f5v9/Q1MTcxNjU0MjUwMzM0NDSy4LIzNLSwNjM3NTY0NDC0MjAA "Keg – Try It Online"). Outputs `0`/`1`. * [MathGolf](https://tio.run/##y00syUjPz0n7/9/m/39DUxNzE2NTQyNTAzMzQ0NLBQsjM0tLA2Mzc1NjQ0MLQyMA "MathGolf – Try It Online"). Outputs `0`/`1`. * [MATL](https://tio.run/##BcGxEQAgCASw3ml4kAfuXMZeO/fH5O53ulc3fMY0h7qQQI1UVokx3ICEfg "MATL – Try It Online"). Outputs `1`/`0`. * [Pyt](https://tio.run##BcG5EQAgCATA3Go44HhmLMrAxOpx97w7s2dATzdCKRFAr9LoFoukAQX9 "Pyt – Try It Online"). Outputs `False`/`True`. * [Stax](https://tio.run/##Ky5JrPj/3@b/f0NTE3MTY1NDI1MDMzNDQ0sFCyMzS0sDYzNzU2NDQwtDIwA "Stax – Try It Online"). Outputs `1`/`0`. * [Vyxal](https://lyxal.pythonanywhere.com?flags=&code=%3C&inputs=1547435125066119%0A8269903675311812&header=&footer=). Outputs `0`/`1`. Also one byte in [05AB1E](https://tio.run/##yy9OTMpM/f//UcPO//8NTU3MTYxNDY1MDczMDA0tuSyMzCwtDYzNzE2NDQ0tDI0A "05AB1E – Try It Online"), but `‹` instead of `<`. Outputs `0`/`1`. [Answer] # [Python 3](https://docs.python.org/3/), \$(\omega^2,28)\$ ``` lambda a,b:(a&-a,a)<(b&-b,b) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFRJ8lKI1FNN1EnUdNGI0lNN0knSfN/QVFmXolGmoZBkqGhgYEOkDIA0pqaXCgShmAJsPh/AA "Python 3 – Try It Online") [Old version](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFRJ8lKIzEuUa1ON1EnUdNGIykuCchO0knS/F9QlJlXopGmYZBkaGhgoAOkDIC0piYXioQhWAIs/h8A "Python 3 – Try It Online") This orders by number of trailing zeros (of binary rep) first and then by the number itself. [Answer] ## [Haskell](https://www.haskell.org/), \$ \omega \cdot 2\$, 22 bytes ``` (.q).(<).q q=odd>>=(,) ``` [Try it online!](https://tio.run/##y0gszk7NyfmfmVuQX1Si4JJYkqjnk1lcwpVmG/NfQ69QU0/DRlOvkKvQNj8lxc7OVkNH839yfm6BQqJCUk2irW2SrWtgTRqIZ@sTwgWTsXUP4cpNzMyzLSjKzCtRKQYa7VSpAJaNNtTTs7S0jP3/LzktJzG9@L9uckEBAA "Haskell – Try It Online") Based off [Grain Ghost's Haskell answers](https://codegolf.stackexchange.com/a/237294/20260_). The function `q` is pointfree for `q x=(odd x,x)`. That is, we sort numbers by whether they're odd, then the number itself, which gives the evens followed by the odds. We can generalize this idea as: ### [Haskell](https://www.haskell.org/), \$ \omega \cdot 4\$, 24 bytes ``` (.q).(<).q q=gcd 6>>=(,) ``` [Try it online!](https://tio.run/##y0gszk7NyfmfmVuQX1Si4JJYkqjnk1lcwpVmG/NfQ69QU0/DRlOvkKvQNj05RcHMzs5WQ0fzf3J@boFCokJSTaKtbZKta2BNGohn6xPCBZOxdQ/hyk3MzLMtKMrMK1EpBhruVKkAlo021NOztLSM/f8vOS0nMb34v25yQQEA "Haskell – Try It Online") Partitions numbers by the greatest common divisors with 6, which is one of `[1,2,3,6]`. In general, we can replace 6 with any number \$c\$, and get order type \$ \omega \cdot \sigma(c)\$, where \$ \sigma(c)\$ counts the divisors of \$c\$. For instance: ### [Haskell](https://www.haskell.org/), \$ \omega \cdot 12\$, 25 bytes ``` (.q).(<).q q=gcd 60>>=(,) ``` [Try it online!](https://tio.run/##y0gszk7NyfmfmVuQX1Si4JJYkqjnk1lcwpVmG/NfQ69QU0/DRlOvkKvQNj05RcHMwM7OVkNH839yfm6BQqJCUk2irW2SrWtgTRqIZ@sTwgWTsXUP4cpNzMyzLSjKzCtRKQaa7lSpAJaNNtTTs7S0jP3/LzktJzG9@L9uckEBAA "Haskell – Try It Online") For 3 digits, 840 gives \$ \omega \cdot 32\$ for 26 bytes. The optimal values of \$c\$ to use are [Highly Composite Numbers](https://en.wikipedia.org/wiki/Highly_composite_number). --- ## [Haskell](https://www.haskell.org/), \$\omega^{10}\$, 34 bytes ``` (.q).(<).q q=scanl1 min.show>>=(,) ``` [Try it online!](https://tio.run/##Nc27CsIwFIDhPU@RwaEBPdAx4OkgiksXoZs6nAZjQ3NrExChz268gOPPN/wDpfFmbTEuhjnzPWWC1qTMNF5KBZOAaitgYhMmRd7W3BkPaQiPpsFqLYoKLnLi/UKIPR5Oi/4Wth37Cx475sh4jLPxeZU@m92T//RcA0gpr@WltKV7KhsV4xs "Haskell – Try It Online") The helper `scanl1 min.show` takes the decimal representation of a number and computes the running minimum, resulting in a non-increasing sequence. For example, `45271` becomes `44521`. We then compare these representations lexicographically, tiebroken by the number itself. Let's show that the non-decreasing finite lists of digits \$0,\dots,9\$ are in well-ordered, with order type \$\omega^{10}\$. The lexicographic comparison first checks which sequence has more 9's in the prefix, tiebroken by whichever is followed by more 8's, and so on down to which ends with more 0's. So, if we represent the list as \$a\_9\$ 9's followed by \$a\_8\$ 8's, and so on to \$a\_0\$ 0's, the comparison is equivalent to comparing \$a\_9, a\_8, \dots, a\_0\$ lexicographically. Each \$a\_i\$ is an arbitrary natural number, so this is exactly the order type \$\omega^{10}\$. The `scanl min` operation suffices to obtain almost every non-increasing sequence of digits 0 through 9, as is seen by it leaving the numbers represented by these digits unchanged -- the only exception is sequences made of only 0's, but their omission doesn't affect the order type. Moreover, each such sequence is produced by a finite number of values, a subset of the numbers with that many digits, and it doesn't matter what the tiebreak is among these values as long as there are no ties. So, the order type produced by the main function is also \$\omega^{10}\$. Sorting the digits in decreasing order would have also worked, but Haskell doesn't have a built-in sort. In other languages, sorting would likely be the way to go. If we could remove the cap of 9 from the values of the digits, we'd get order type \$\omega^{\omega}\$ [Answer] # [Husk](https://github.com/barbuz/Husk), \$\omega\$, 2 bytes ``` ¬< ``` [Try it online!](https://tio.run/##yygtzv6f6/aoqfH/oTU2////j4421DGO1Yk2ApPGYNIETJqCSTMwaQ4mLcCkJZg0NABSsQA "Husk – Try It Online") Boring single-omega solution: well-ordering is just normal integer order (example 1 in question). --- # [Husk](https://github.com/barbuz/Husk), \$\omega\$+1, 7 bytes ``` ¬F<σ7\0 ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8f@hNW4255vNYwz@//8fHW2oYxSrE22kYwgkDXXMgaQ5mG0BZVvExgIA "Husk – Try It Online") Omega+1: well-ordering is integers starting at 1 in normal order, but missing 7, and finally with 7 last, so: 1,2,3,4,5,6,8,9,10,...,7. Change the `7` in the code to select any other digit at the end. --- # [Husk](https://github.com/barbuz/Husk), \$\omega\$.2, 11 bytes ``` ¬F<m?o_\I%2 ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8f@hNW42ufb58TGeqkb///@PjjbWMYzVAZJGYNIETJoCSROwuAlY3AQqYhYbCwA "Husk – Try It Online") Odd numbers first, then even numbers, so: 1,3,5,7,...,2,4,6,8,... . --- # [Husk](https://github.com/barbuz/Husk), \$ω^ω\$, 6 bytes ``` ¬¤<(↔p ``` [Try it online!](https://tio.run/##yygtzv7//9CaQ0tsNB61TSn4//@/8X8zAA "Husk – Try It Online") Port of [Neil's omega^omega approach](https://codegolf.stackexchange.com/a/237296/95126): gets the reversed (`↔`) `p`rime factors of each `¤` argument, and compares them lexicographically (`<`), finally taking the logical NOT (`¬`) to ensure only two output values. --- # [Husk](https://github.com/barbuz/Husk), \$ω^ω\$+1, 12 bytes ``` ¬¤>?o↔pȯ;\←← ``` [Try it online!](https://tio.run/##yygtzv7//9CaQ0vs7PMftU0pOLHeOuZR2wQg@v//v5HJf0MjAA "Husk – Try It Online") Lexicographic ordering of reversed prime factors of inputs minus 1, but finally with `1` last: subtract 1 (`←`) from each (`¤`) input, then if the result is falsey (zero), convert it to a list containing infinity (`ȯ;\←`), otherwise make a list of its reversed (`↔`) `p`rime factors, before comparing them (`>`) and taking the logical NOT (`¬`). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), \$ω^2\$, 10 bytes ``` ‹⟦ΣθN⟧⟦ΣηN ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMntbhYIzq4NFejUFNHwTOvoLTErzQ3KbVIQzNWRwEskYEhoalp/f@/oYEll6Xlf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Orders by sum of digits, then regular ascending order, resulting in the following ordering: `1, 10, 100, ..., 2, 11, 20, 101, 200, ..., 3, 12, 21, 30, 102, 111, 120, 201, 210, 300, ..., 4, 13, 22, 31, 40, 103, 112, 121, 130, 202, 211, 220, 301, 400 ..., ...` # [Charcoal](https://github.com/somebody1234/Charcoal), \$ω^2\cdot 9\$, 14 bytes ``` ‹⟦⌈θΣθN⟧⟦⌈ηΣηN ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMntbhYI9o3sSIztzRXo1BTRyEYSnvmFZSW@JXmJqUWaWjG6ijAFWVAFWVgKNLUtP7/39DAksvS8r9uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Orders by greatest digit, then sum of digits, then regular ascending order, resulting in the following ordering: `1, 10, 100, ..., 11, 101, ..., 111, ..., ... 2, 20, 200, ..., 12, 21, 102, 120, 201, 210, ..., 22, 112, 121, 202, 211, 220, ..., ... 9, 90, 900, ..., 91, 109, 190, 901, 910, ..., 92, 119, 191, 209, 290, 902, 911, 920, ..., ...` # [Charcoal](https://github.com/somebody1234/Charcoal), \$ω^3\$, 16 bytes ``` ‹⟦ΣΣθΣθN⟧⟦ΣΣηΣηN ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMntbhYIzq4NFcDhAs1NXUUIAwdBc@8gtISv9LcpNQiDc1YHQW4qgyYqgwMVZqa1v//GxpYclla/tctywEA "Charcoal – Try It Online") Link is to verbose version of code. Orders by sum of digits of sum of digits, then sum of digits, then regular ascending order, resulting in the following ordering: `1, 10, ..., 19, 28, 37, 46, 55, 64, 73, 82, 91, ..., ... 2, 11, 20, ..., 29, 38, 47, 56, 65, 74, 83, 92, ..., ... 3, 12, 21, 30, ..., 39, 48, 57, 66, 75, 84, 93, ..., ... 4, 13, 22, 31, 40, ..., 49, 58, 67, 76, 85, 94, ..., ...` # [Charcoal](https://github.com/somebody1234/Charcoal), \$ω^ω\cdot 9\$, 29 bytes ``` F²⊞υ⟦N⟧W›⌈Eυ⌊κ⁹Fυ⊞κΣ⌊κ›⮌⊟υ⮌⊟υ ``` [Try it online!](https://tio.run/##XYy9CsIwFIX3PMUdcyEOuoU@gDhUQh3FIZZIQvNT0qT69jEpIuJ0OIfvfKOWcQzSlvIIEegBQeRF08zgevJzTufs7ipSvGFHntpYBfQYlUx16@XLuOxqzo3vjd/qhIgMOCJsxvwxTgwuDf6hOiKi8ekrHNSq4qKoCFXYJH9DfZSy55xwXnarfQM "Charcoal – Try It Online") Link is to verbose version of code. Repeatedly sums the digits of the inputs until they both reach their digital root, then compares the results in reverse order from the digital root working back to the original input. Since there are 9 digital roots and a potentially arbitrary number of summation steps I think I have the correct value for this. For small inputs the ordering is the same as the previous version; it first diverges for 199, which for instance compares less than 99 here but not in the previous ordering. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), \$ω^ω\$, 54 bytes ``` \d+ $* +`\b(11+)(\1)+\b $1 1$#2$* ^(.+)(,\1|\b.*,\1\B) ``` [Try it online!](https://tio.run/##HY0xDsIwEAR7vwKJIDlxFPnOTnQ1DZ@wEERQ0FAgSv5ubrcZr@zR@PP8vt73foqXW2@PFIYppFvbo0gaY5MxtT0McpDhqP50jYtfz01@bV8mP9t57F22WTQ4tYJi3BksZF2D6CwbCEfpKB2lo3C0wgGVNNAdZyHRMXaMPxprxo6xY@xkdjI7GQ62gehkOIVOoVPoFDrYGXSnrnBABd3BNu4MlvwH "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` \d+ $* ``` Convert to unary. ``` +`\b(11+)(\1)+\b $1 1$#2$* ``` Factorise with the smallest prime factors last. ``` ^(.+)(,\1|\b.*,\1\B) ``` Compare lexicographically. [Answer] # [Python 2](https://docs.python.org/2/), \$\omega^{10}\$, 48 bytes ``` lambda*l:cmp(*[(sorted(`n`)[::-1],n)for n in l]) ``` [Try it online!](https://tio.run/##Ncw9CoAgGADQvVM4@oWBNgpewrUE7ccK9FPMpdNbSwd4Lz/1TDg2r@YWXFw21we5xkz7id6p1H2jFi1MUg7CMASfCkFyIQkGmlbF4bFTwQTnHLpcLqw/0@xrlAdoLw "Python 2 – Try It Online") Outputs `-1` for `<` and `+1` for `>` Takes each number and sorts its digits in descending order, then compares lexicographically. This effectively compares the count of digit 9's, tiebroken by the number of count 8's, and so on down to 0's. This is all tiebroken by the value of the number itself. This having order type \$\omega^{10}\$ follows the same argument as my [Haskell \$\omega^{10}\$ answer](https://codegolf.stackexchange.com/a/237304/20260), with sorting replacing taking the running minimum. [Answer] # [Haskell](https://www.haskell.org/), \$\omega^\omega\$,62 53 bytes ``` i#0=[i] i#a=(i+1)#sum[1|'0'<-show a]++[a] a&b=1#a<1#b ``` [Try it online!](https://tio.run/##PY69CsIwFEb3PEUgYpViSPbeRRSXLkK3kOFGK720aWuTIkLfPf6Art85cL4GQ1t3XSI/DlPk9xk7ulF95QeMKEsKMZFQYMgyEggbyvVWhNkbvWQqK3ahGR4cbZ4btAzXDrTAQguXLoMfOXK3IICD43n5wLJivx1OFfNIPYwT9XH1z8nw/rF/8q9ntJRaKWXTCw) *-9 bytes thanks to xnor* Conceptually, this transforms an integer into an infinite list, that is made by iterating `sum[1|'0'<-show a]`, which just counts the zeroes, until zero is reached. Then it's just zeroes after that. Then those lists are then compared in reverse lexicographic order. To actually do that in practice, the lists are constructed in reverse, and the head of the list is it's own length. The "ideal" infinite lists have an infinite trail of zeroes, which are removed in the "practical" ones. These zeroes are accounted for with the length. For example, the number `100_000_000_001` has the "ideal" representation `[100_000_000_001,10,1,0,0,0,...]` and the "practical" representation `[4, 1, 10, 100_000_000_001]` ]
[Question] [ No, not [this](https://codegolf.stackexchange.com/q/115715/64159). And not [this](https://codegolf.stackexchange.com/q/116616/64159) either. This question is nothing like those Write the shortest code to print/return the following output: ``` /\ /\ /\ / \ / \ / \ / /\ \ / /\ \ / /\ \ / / \ \/ / \ \/ / \ \ \ \ / /\ \ / /\ \ / / \ \/ / \ \/ / \ \/ / \ / /\ \ / /\ \ / \/ / \ \/ / \ \/ /\ \ / /\ \ / /\ / \ \/ / \ \/ / \ / /\ \ / /\ \ / /\ \ / / \ \/ / \ \/ / \ \ \ \ / /\ \ / /\ \ / / \ \/ / \ \/ / \ \/ / \ / \ / \ / \/ \/ \/ ``` * Standard methods of input/output. * Standard loopholes apply. * Trailing/leading whitespace is okay, in any amount. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~28~~ ~~24~~ 23 bytes ``` ↗²↖↙⁴⟲P²⁴⁶↘↙↙²⟲P²⁴⁶C⁸¦⁰ ``` [Try it online!](https://tio.run/nexus/charcoal#@/@obfqhTY/apj1qm/moccuj@Zve79kAFAAyG7c9apsBEm6bCRRAkXi/Z/Gjxh2Hlj1q3PD/PwA "Charcoal – TIO Nexus") Explanation: ``` ↗²↖↙⁴ Draw the top left 4x4 corner / // ⟲P²⁴⁶ Rotate it three times to complete a diamond /\ //\\ \\// \/ ↘↙↙² Draw the top left line of the inner diamond /\ //\\ \\// \// ⟲P²⁴⁶ Rotate three times to complete five diamonds C⁸¦⁰ Copy everything 8 characters to the right to complete eight diamonds ``` Edit: My previous answer used `‖M‖M↓` to create a whole diamond by reflecting the top corner, but due to a bug in Charcoal this left the cursor out of position. Fortunately I discovered another way of achieving the same effect which doesn't move the cursor, which meant that I saved a byte drawing the inner diamond. (I also looked into overlapping operations, but I wasn't able to improve on the rotate/copy approach.) Edit: `↖²↗↘⁴‖M¬M¹¦³↘²‖M¬C⁸¦⁰` does the job in 21 bytes, but that relies on the new reflecting behaviour, so I don't know whether this was possible with the old code. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~62~~ ~~50~~ ~~48~~ ~~45~~ ~~42~~ 40 bytes *Thanks to @Okx for saving two bytes!* ``` ↙²→↘²↙↖⁴→↗⁴‖MF²C⁸¦⁰M⁸↓→↗²↓↘²M⁴→↑↗²↓↘²‖M↓ ``` [Try it online!](https://tio.run/nexus/charcoal#@/@obeahTY/aJj1qmwGiZz5qm/aocQtYYDqI0TDt/Z617/csO7Tp/Z7Fjxp3HFr2qHEDUAjIfNQ2GaIOpHEy2ACwBET3RBQJiDlA3v//AA) **Explanation:** ``` ↙²→↘² // Draw the left half of the inner part of the first diamond. ↖⁴→↗⁴ // Draw the left half of the outer part. ‖M // Mirror the half of the diamond to create the first full diamond. F²C⁸¦⁰ // Copy the picture eight characters to the left twice. // The first copy gives us two diamonds, and the second copy of the // two diamonds overlaps so that the result is three diamonds. M⁸↓→↗²↓↘² // Move down to draw the upper inner half of the first middle diamond. M⁴→↑↗²↓↘² // Move right to do the same for the second middle diamond. ‖M↓ // Mirror the whole thing vertically. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~45~~ ~~44~~ 43 bytes Code: ``` …/ \©•—‹íćCé']d₂2ó@¯çX‘¯¨•3вè8äJvy®‡«}»Â» ``` Pre-explanation: The [`•—‹íćCé'\]d₂2ó@¯çX‘¯¨•3в`](https://tio.run/nexus/05ab1e#AS8A0P//4oCi4oCU4oC5w63Eh0PDqSddZOKCgjLDs0DCr8OnWOKAmMKvwqjigKIz0LL//w) part is just a compressed version of the following array: ``` [1, 1, 1, 0, 2, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 2, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 2, 1, 2, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 2, 1, 2, 0, 1, 0, 1, 2, 1, 2, 1, 1, 0, 1, 0, 2, 1, 2, 1, 1, 2, 1, 2, 0, 1, 0, 1, 1, 2, 1, 2, 1, 1, 2, 1, 1, 0, 1, 0, 2, 1, 2, 1, 1, 1, 1, 2, 0, 1, 0, 1, 1, 2, 1, 2] ``` Which we index into the string `…/ \`. This maps `0 -> /`, `1 -> space`, `2 -> \`. After that, we process this string with the following program: ``` 8äJvy®‡«}»Â» 8ä # Split the array into 8 pieces J # Join each sub-array in the array vy } # For each string in the array  # Bifurcate (duplicate and reverse) ® # Push the string "/ \" (which was copied using ©)  # Bifurcate to get "\ /" ‡ # Transliterate / -> \ and \ -> / « # Append to the original string » # Join the entire stack on newlines  # Bifurcate » # Join the stack by newlines ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/nexus/05ab1e#AVEArv//4oCmLyBcwqnigKLigJTigLnDrcSHQ8OpJ11k4oKCMsOzQMKvw6dY4oCYwq/CqOKAojPQssOoOMOkSnZ5w4LCrsOC4oChwqt9wrvDgsK7//8 "05AB1E – TIO Nexus") [Answer] # PHP, 126 Bytes ``` <?=gzinflate(base64_decode("vY7BCQAwCAP/mSIbuJD7z1GJLbbiuz5yKCeEpDk1RUSQWm8iMiRnIyw178Qgi5hs3ceHOA86snN7ON2b/687X+7umuIC")); ``` [Try it online!](https://tio.run/nexus/php#@29jb5telZmXlpNYkqqRlFicamYSn5KanJ@SqqFUFmnu5BzoWO7sGKCfG@yZVOrlYl5l6O7lk5SUWVplWuntnOpa4JJtGBQaHBiea5HpmxmU51lZbmhuEZieaZpRbJyc6uHvaGFWnOdn7u9nlKRvZmEeoW1emlvq6aykqWn9/z8A "PHP – TIO Nexus") # PHP, 149 Bytes ``` $s=strtr("000 111 222 333 444 555 \ 22 / \\33/ ",[" /\ "," / \ "," / /\ \ ","/ / \ \\","\ \ / /"," \ \/ / "]);echo"$s ".strrev($s); ``` [Try it online!](https://tio.run/nexus/php#Jc4xCsMwDAXQXacQwkMCpbIte0pLD1J1KoFsDXbo9V0pnfT4/w@6PfZtH6Hf@9GONlGMEVJKkHMGEYFSCtRaAVExZ2REI6qKGJEuT7LDetrIvjvJnqqT/6mq2SOvfGH2il7zsr63D4UOdLU32vqdQp@XMX4 "PHP – TIO Nexus") [Answer] # Ruby, ~~99~~ 97 bytes ``` 400.times{|i|print (23<x=i%25)?$/:" / \\ "[(x^y=i/25)&4^x+y&1^(x-2&4&y-2>y/6%2*x/2%11*4?2:0)]} ``` **Explanation** Each 4x4 square contains only spaces and `/` or `\`. We plot these to give the overall diamond pattern. To avoid partial patterns at the borders, certain 2x2 squares must be left blank as below. ``` .. /\ .... /\ .... /\ .. ../ \..../ \..../ \.. / /\ \ / /\ \ / /\ \ / / \ \/ / \ \/ / \ \ \ \ / /\ \ / /\ \ / / \ \/ / \ \/ / \ \/ / ..\ / /\ \ / /\ \ /.. .. \/ / \ \/ / \ \/ .. .. /\ \ / /\ \ / /\ .. ../ \ \/ / \ \/ / \.. / /\ \ / /\ \ / /\ \ / / \ \/ / \ \/ / \ \ \ \ / /\ \ / /\ \ / / \ \/ / \ \/ / \ \/ / ..\ /....\ /....\ /.. .. \/ .... \/ .... \/ .. ``` **Ungolfed version** - modified to print the above to assist in explanation ``` 400.times{|i|print (23<x=i%25)?$/: #Calculate x. If last column, print a newline else " /..\\ .."[(x^y=i/25)&4^x+y&1^ #If (x^y)&4==4, use x+y&1 to select between space and /. If (x^y)&4==0 select between \ and space. (x-2&4&y-2>y/6%2*x/2%11*4?2:0)] #If x-2&4&y-2==4, and we are on the 2 character wide border (y/6%2*x/2%11==0), XOR with 2 to print . } ``` [Answer] # JavaScript, 232 bytes ``` _=>(a=`3868683 2/274/274/272 1/18172/18172/18171 /1/27191/27191/2717 7172/18172/18172/1/ 17191/27191/27191/1 272/18172/18172/2 391/27191/27193`.replace(/\d/g,n=>n>6?['\\','/\\','\\/'][n-7]:' '.repeat(n)))+` `+[...a].reverse().join`` ``` ### Try it online! ``` const f = _=>(a=`3868683 2/274/274/272 1/18172/18172/18171 /1/27191/27191/2717 7172/18172/18172/1/ 17191/27191/27191/1 272/18172/18172/2 391/27191/27193`.replace(/\d/g,n=>n>6?['\\','/\\','\\/'][n-7]:' '.repeat(n)))+` `+[...a].reverse().join`` console.log(` ${f()} `) ``` [Answer] # Pyth - ~~106~~ ~~98~~ ~~96~~ 92 bytes ``` V16V24J%t+NH8K%+_2-NH8=Y&&&>H1>N1<N14<H22p?|q2J&&Y!%J4?<1%H4J!J\/?|q2K&&Y!%K4?<1%H4!KK\\d)pb ``` [Try it](https://pyth.herokuapp.com/?code=V16V24J%25t%2BNH8K%25%2B_2-NH8%3DY%26%26%26%3EH1%3EN1%3CN14%3CH22p%3F%7Cq2J%26%26Y%21%25J4%3F%3C1%25H4J%21J%5C%2F%3F%7Cq2K%26%26Y%21%25K4%3F%3C1%25H4%21KK%5C%5Cd%29pb&debug=0) [Answer] # [Canvas](https://github.com/dzaima/Canvas), 18 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` 4/2/33╋╬2/77╋╬:91╋ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjE0JXVGRjBGJXVGRjEyJXVGRjBGJXVGRjEzJXVGRjEzJXUyNTRCJXUyNTZDJXVGRjEyJXVGRjBGJXVGRjE3JXVGRjE3JXUyNTRCJXUyNTZDJXVGRjFBJXVGRjE5JXVGRjExJXUyNTRC,v=0) Explanation: ``` 4/ push a diagonal of length 4 2/ push a diagonal of length 2 33╋ insert that at [3;3] in the 1st diagonal / / / / / / ╬ quad-palindromize with 0 overlap 2/77╋ insert a 2-long diagonal in the bottom-right corner /\ / \ / /\ \ / / \ \ \ \ / / \ \/ / \ / / \/ / ╬ quad-palindromize with 0 overlap, creating most of the output /\ /\ / \ / \ / /\ \ / /\ \ / / \ \/ / \ \ \ \ / /\ \ / / \ \/ / \ \/ / \ / /\ \ / \/ / \ \/ /\ \ / /\ / \ \/ / \ / /\ \ / /\ \ / / \ \/ / \ \ \ \ / /\ \ / / \ \/ / \ \/ / \ / \ / \/ \/ :91╋ overlap self on [9;1] ``` [Answer] # C#, 608 bytes ``` void q(){Action<string>a=Console.Write;Func<int,int,string>b=(c,d)=>new string(' ',c)+(d<1?"/\\":d<2?"/ \\":d<3?"/ /\\ \\":d<4?"/ / \\ \\":d<5?"\\ \\ / /":d<6?"\\ \\/ /":d<7?"\\ /":"\\/");Action e=()=>a(b(0,4)+b(0,4)+b(0,4)+"\n"+b(1,5)+b(2,5)+b(2,5)+"\n");Action f=()=>a(b(1,2)+b(2,2)+b(2,2)+"\n");Action g=()=>a(b(0,3)+b(0,3)+b(0,3)+"\n");a(b(3,0)+b(6,0)+b(6,0)+"\n"+b(2,1)+b(4,1)+b(4,1)+"\n");f();g();e();a(" \\ / /\\ \\ / /\\ \\ /\n"+" \\/ / \\ \\/ / \\ \\/\n"+" /\\ \\ / /\\ \\ / /\\\n"+" / \\ \\/ / \\ \\/ / \\\n");f();g();e();a(b(2,6)+b(4,6)+b(4,6)+"\n"+b(3,7)+b(6,7)+b(6,7)+"\n");} ``` [Answer] # C#, ~~382~~ 291 bytes ``` _=>string.Format(@"{5}{5}{5} {2}{2}{2} {0}{0}{0} {1}{1}{1} \ \ {0}{0} / / \ \{1}{1}/ / \ {0}{0} / \{1}{1}/ /\ \ {0} / /\ / \ \{1}/ / \ {0}{0}{0} {1}{1}{1} \ \ {0}{0} / / \ \{1}{1}/ / {4}{4}{4} {3}{3}{3}",@" / /\ \ ",@"/ / \ \",@" / \ ",@" \/ ",@" \ / ",@" /\ "); ``` [Answer] ## Javascript 126 bytes ``` for(c=r=a='';r<16;c++>22&&(r++,c=0,a+=` `))C=c%22>1&&r%14>1,q=[1,,C&&r&2,,,,C&&~r&2,,1],a+=q[c+5+r&7]?'/':q[r-c+20&7]?'\\':' ' ``` Since it's now pretty unreadable, a basic explanation: * we tile the space top left to bottom right * we draw it as basically 6 diagonal lines that repeat every 8 characters: 2 solid lines, and 4 that are "dashed" (two characters, then two spaces...) * the `C=...` stuff is to limit drawing of some of the lines to within a bounding box * to save a lot of characters, we deliberately add numbers to make the expressions for the upwards and downwards lines extremely similar * then, put the expressions themselves into a sparse array `[1,,C&&...]`, which we look up into. If there is a truthy value, we draw the appropriate character. - ``` for(c=r=a='';r<16;c++>22&&(r++,c=0,a+=` `)) // basic grid tiling C=c%22>1&&r%14>1, // are we not near the edges q=[1, // a solid line that always draws , // a line that never draws C&&r&2, // a line that draws if not near the edge, and if on the correct "dash" (r&2) ,,, C&&~r&2, // if not near the edge, and on the opposite "dash" (~r&2) ,1 // the opposite diagonal line that always draws ], a+=q[c+5+r&7]?'/' // compute which upward line we're on, check whether to draw it :q[r-c+20&7]?'\\' // do the same for the downward line :' ' // otherwise draw a space ``` Maybe this explanation didn't help. :) Try online: <https://codepen.io/stevebennett/pen/WjgMpY> Hopefully I got the output right: ``` /\ /\ /\ / \ / \ / \ / /\ \ / /\ \ / /\ \ / / \ \/ / \ \/ / \ \ \ \ / /\ \ / /\ \ / / \ \/ / \ \/ / \ \/ / \ / /\ \ / /\ \ / \/ / \ \/ / \ \/ /\ \ / /\ \ / /\ / \ \/ / \ \/ / \ / /\ \ / /\ \ / /\ \ / / \ \/ / \ \/ / \ \ \ \ / /\ \ / /\ \ / / \ \/ / \ \/ / \ \/ / \ / \ / \ / \/ \/ \/ ``` # History ## 130 ``` for(c=r=a='';r<16;c++>22&&(r++,c=0,a+=` `))C=c%22>1&&r%14>1,q=[1,,C&&r&2,,,,C&&~r&2,,1],a+=q[(c+5+r)%8]?'/':q[(r-c+20)%8]?'\\':' ' ``` ## 133 ``` for(c=r=a='';r<16;c++>22&&(r++,c=0,a+=` `))C=c%22>1,q=[1,,C&&r&2&&r<14,,,,C&&~r&2&&r>1,,1],a+=q[(c+5+r)%8]?'/':q[(r-c+20)%8]?'\\':' ' ``` ## 137 ``` for(c=r=a='';r<16;c++==23&&(r++,c=0,a+=` `))C=c<22&&c>1,q=[1,,C&&r&2&&r<14,,,,C&&~r&2&&r>1,,1],a+=q[(c+5+r)%8]?'/':q[(r-c+20)%8]?'\\':' ' ``` ## 155 ``` for(c=r=a='';r<16;c++==23&&(r++,c=0,a+=` `))Z=(C=c<22&&c>1)&&~r&2&&r>1,Y=C&&r&2&&r<14,B=(c-r+12)%8,A=(c+5+r)%8,q=[1,,Y,,,,Z,,1],a+=q[A]?'/':q[8-B]?'\\':' ' ``` ## History: 172 ``` for(c=r=a='';r<16;c++==23&&(r++,c=0,a+='\n'))a+=(Z=(C=c<22&&c>1)&&~r&2&&r>3,Y=C&&r&2&&r<12,B=(c-r+16)%8,A=(c+r)%8,A==3||A==5&&Y||A==1&&Z?'/':B==4||B==2&&Y||B==6&&Z?'\\':' ') ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~168~~ ~~125~~ ~~122~~ 121 bytes ``` $a=(,' '*24+' ')*16 0,8,8+(88,8)*2+8|%{$i=$o+=$_ '&$:&8%$%6%&%5%&%6%$%8&:$'|% t*y|%{$i+=$_-35;$a[$i]='\/'[$i%2]}} -join$a ``` [Try it online!](https://tio.run/##HYpBCsIwEADveUUPu9k2SVGjDUslL9EiORSMFCMqiNi@PUYPM8xhbuk13h/ncZpyhuBrQxUpu9MkqFEbJ9aGDeuaixtlNc/4geghaQ8nQRJ6yQjoUGJXcKVZ9kAzVk/1/s@/s912ewgHiIOn44pKoB2WRbSXFK8Qcv4C "PowerShell – Try It Online") The script creates the array of 400 chars and renders 8 diamonds started from positions with intervals `0,8,8,88,8,88,8,8`. * The string `'&$:&8%$%6%&%5%&%6%$%8&:$'` contains the intervals of offsets for the rendered symbols. * The expression `|% t*y` is shortcut for `|foreach-object toCharArray` First render steps: ``` ---/\------------------- --/--\------------------ -/-/\-\----------------- /-/--\-\---------------- \-\--/-/---------------- -\-\/-/----------------- --\--/------------------ ---\/------------------- ------------------------ ------------------------ ------------------------ ------------------------ ------------------------ ------------------------ ------------------------ ------------------------ ``` --- ``` ---/\------/\----------- --/--\----/--\---------- -/-/\-\--/-/\-\--------- /-/--\-\/-/--\-\-------- \-\--/-/\-\--/-/-------- -\-\/-/--\-\/-/--------- --\--/----\--/---------- ---\/------\/----------- ------------------------ ------------------------ ------------------------ ------------------------ ------------------------ ------------------------ ------------------------ ------------------------ ``` --- ``` ---/\------/\------/\--- --/--\----/--\----/--\-- -/-/\-\--/-/\-\--/-/\-\- /-/--\-\/-/--\-\/-/--\-\ \-\--/-/\-\--/-/\-\--/-/ -\-\/-/--\-\/-/--\-\/-/- --\--/----\--/----\--/-- ---\/------\/------\/--- ------------------------ ------------------------ ------------------------ ------------------------ ------------------------ ------------------------ ------------------------ ------------------------ ``` --- ``` ---/\------/\------/\--- --/--\----/--\----/--\-- -/-/\-\--/-/\-\--/-/\-\- /-/--\-\/-/--\-\/-/--\-\ \-\--/-/\-\--/-/\-\--/-/ -\-\/-/--\-\/-/--\-\/-/- --\--/-/\-\--/----\--/-- ---\/-/--\-\/------\/--- ----\-\--/-/------------ -----\-\/-/------------- ------\--/-------------- -------\/--------------- ------------------------ ------------------------ ------------------------ ------------------------ ``` and so on. [Answer] # [Retina](https://github.com/m-ender/retina), 214 bytes ``` F/\E/\E/\¶B/B\BB/B\FAD D¶F\/ C C¶FD D /\¶BC CAF\B/BB\B/¶F\/E\/E\/ F B E BBB D /\ \B/ C /B\ \/ B A / \¶ / /\ \ / /\ \ / /\ \¶/ / \ \/ / \ \/ / \ \¶\ \ / /\ \ / /\ \ / /¶ \ \/ / \ \/ / \ \/ /¶ \ / ``` [Try it online!](https://tio.run/##bYyxDQMxDAN7TsENNINlW1O4SZEiTYrgZ/MAXszh67vHA4QogSf@3sfn@9obYaOn1nTz4eeI0tjWjGGsrFp0MgmdJYYYkZZETyHgRIe7o8EGFaNCXVToIFFAI1UiOwHefE1LQA83X/MBT1fZA38FF7L3Hw "Retina – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 75 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Can't seem to golf at all today :\ This is hideous! ``` `­66e7s2gf8447sppcpÜ;7¶p1paff2kmbj1l3odfs4q1½0j¢·lqbs`q¤®©n28" /\\"÷ê û ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=YK02NmU3czJnZjg0NDdzcHBjcNw7N7ZwMXBhg2ZmMmttYmqDMWwzb2RmnHM0cTG9MGqit2xxYnNgcaSuqW4yOCIgL1xcIsO36iD7) [Answer] # Deadfish~, 2839 bytes ``` {iii}iiccc{i}iiiiic{iiii}iiiiic{dddddd}cccccc{i}iiiiic{iiii}iiiiic{dddddd}cccccc{i}iiiiic{iiii}iiiiic{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddcc{iiiiii}c{dddddd}cccc{i}iiiiic{d}dddddcc{iiiiii}c{dddddd}cccc{i}iiiiic{d}dddddcc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddc{i}iiiiic{iiii}iiiiic{dddddd}c{iiiiii}c{dddddd}cc{i}iiiiic{d}dddddc{i}iiiiic{iiii}iiiiic{dddddd}c{iiiiii}c{dddddd}cc{i}iiiiic{d}dddddc{i}iiiiic{iiii}iiiiic{dddddd}c{iiiiii}c{{d}ii}ddc{iiii}dddc{d}dddddc{i}iiiiic{d}dddddcc{iiiiii}c{dddddd}c{iiiiii}c{dddd}dddddc{d}dddddc{i}iiiiic{d}dddddcc{iiiiii}c{dddddd}c{iiiiii}c{dddd}dddddc{d}dddddc{i}iiiiic{d}dddddcc{iiiiii}c{dddddd}c{iiiiii}c{{d}ii}ddc{{i}dd}iic{dddddd}c{iiiiii}c{dddddd}cc{i}iiiiic{d}dddddc{i}iiiiic{iiii}iiiiic{dddddd}c{iiiiii}c{dddddd}cc{i}iiiiic{d}dddddc{i}iiiiic{iiii}iiiiic{dddddd}c{iiiiii}c{dddddd}cc{i}iiiiic{d}dddddc{i}iiiiic{dddd}iiic{ii}iic{iiiiii}c{dddddd}c{iiiiii}c{dddd}dddddc{d}dddddc{i}iiiiic{d}dddddcc{iiiiii}c{dddddd}c{iiiiii}c{dddd}dddddc{d}dddddc{i}iiiiic{d}dddddcc{iiiiii}c{dddddd}c{iiiiii}c{dddd}dddddc{d}dddddc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}cc{i}iiiiic{d}dddddc{i}iiiiic{iiii}iiiiic{dddddd}c{iiiiii}c{dddddd}cc{i}iiiiic{d}dddddc{i}iiiiic{iiii}iiiiic{dddddd}c{iiiiii}c{dddddd}cc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddd}dddddc{d}dddddc{i}iiiiic{d}dddddcc{iiiiii}c{dddddd}c{iiiiii}c{dddd}dddddc{d}dddddc{i}iiiiic{d}dddddcc{iiiiii}c{dddddd}c{iiiiii}c{dddd}dddddc{dddd}iiic{ii}iiccc{i}iiiiic{iiii}iiiiic{dddddd}c{iiiiii}c{dddddd}cc{i}iiiiic{d}dddddc{i}iiiiic{iiii}iiiiic{dddddd}c{iiiiii}c{dddddd}cc{i}iiiiic{d}dddddc{i}iiiiic{iiii}iiiiic{{d}ii}ddc{ii}iicc{i}iiiiic{d}dddddcc{iiiiii}c{dddddd}c{iiiiii}c{dddd}dddddc{d}dddddc{i}iiiiic{d}dddddcc{iiiiii}c{dddddd}c{iiiiii}c{dddd}dddddc{d}dddddc{i}iiiiic{d}dddddcc{iiiiii}c{{d}ii}ddc{ii}iic{i}iiiiic{d}dddddc{i}iiiiic{iiii}iiiiic{dddddd}c{iiiiii}c{dddddd}cc{i}iiiiic{d}dddddc{i}iiiiic{iiii}iiiiic{dddddd}c{iiiiii}c{dddddd}cc{i}iiiiic{d}dddddc{i}iiiiic{iiii}iiiiic{dddddd}c{iiiiii}c{{d}ii}ddc{iiii}dddc{d}dddddc{i}iiiiic{d}dddddcc{iiiiii}c{dddddd}c{iiiiii}c{dddd}dddddc{d}dddddc{i}iiiiic{d}dddddcc{iiiiii}c{dddddd}c{iiiiii}c{dddd}dddddc{d}dddddc{i}iiiiic{d}dddddcc{iiiiii}c{dddddd}c{iiiiii}c{{d}ii}ddc{{i}dd}iic{dddddd}c{iiiiii}c{dddddd}cc{i}iiiiic{d}dddddc{i}iiiiic{iiii}iiiiic{dddddd}c{iiiiii}c{dddddd}cc{i}iiiiic{d}dddddc{i}iiiiic{iiii}iiiiic{dddddd}c{iiiiii}c{dddddd}cc{i}iiiiic{d}dddddc{i}iiiiic{dddd}iiic{ii}iic{iiiiii}c{dddddd}c{iiiiii}c{dddd}dddddc{d}dddddc{i}iiiiic{d}dddddcc{iiiiii}c{dddddd}c{iiiiii}c{dddd}dddddc{d}dddddc{i}iiiiic{d}dddddcc{iiiiii}c{dddddd}c{iiiiii}c{dddd}dddddc{d}dddddc{i}iiiiic{dddd}iiic{ii}iicc{iiiiii}c{dddddd}cc{i}iiiiic{d}dddddcccc{iiiiii}c{dddddd}cc{i}iiiiic{d}dddddcccc{iiiiii}c{dddddd}cc{i}iiiiic{dddd}iiic{ii}iiccc{iiiiii}c{dddd}dddddc{d}dddddcccccc{iiiiii}c{dddd}dddddc{d}dddddcccccc{iiiiii}c{dddd}dddddc ``` [Try it online!](https://deadfish.surge.sh/#LGvd9WS0r9+At/+L/f/iqqYAC3/4v9/+KqpgALf/i/3/4lP3Qvfgt/+KdVAv/2KqpgC3/4p1UC//YqqmALf/inVQL/9iU/dC9+Lf/inVQt/+L/f/iqqYv/2Kqpgt/+KdVC3/4v9/+Kqpi//YqqmC3/4p1ULf/i/3/4qqmL/9iU/dC/3UKdVC3/4p1UC//YqqmL/9iqnVQp1ULf/inVQL/9iqqYv/2KqdVCnVQt/+KdVAv/2Kqpi//YlP3Qlun4qqmL/9iqqYLf/inVQt/+L/f/iqqYv/2Kqpgt/+KdVC3/4v9/+Kqpi//YqqmC3/4p1ULf/iqn+L34v/2Kqpi//Yqp1UKdVC3/4p1UC//YqqmL/9iqnVQp1ULf/inVQL/9iqqYv/2KqdVCnVQt/+Kqf4vfgv/2Kqpgt/+KdVC3/4v9/+Kqpi//YqqmC3/4p1ULf/i/3/4qqmL/9iqqYLf/iqn+L34C//Yqp1UKdVC3/4p1UC//YqqmL/9iqnVQp1ULf/inVQL/9iqqYv/2KqdVCqn+L34C3/4v9/+Kqpi//YqqmC3/4p1ULf/i/3/4qqmL/9iqqYLf/inVQt/+L/f/iU/dC9+C3/4p1UC//YqqmL/9iqnVQp1ULf/inVQL/9iqqYv/2KqdVCnVQt/+KdVAv/2JT90L34t/+KdVC3/4v9/+Kqpi//YqqmC3/4p1ULf/i/3/4qqmL/9iqqYLf/inVQt/+L/f/iqqYv/2JT90L/dQp1ULf/inVQL/9iqqYv/2KqdVCnVQt/+KdVAv/2Kqpi//Yqp1UKdVC3/4p1UC//YqqmL/9iU/dCW6fiqqYv/2Kqpgt/+KdVC3/4v9/+Kqpi//YqqmC3/4p1ULf/i/3/4qqmL/9iqqYLf/inVQt/+Kqf4vfi//YqqmL/9iqnVQp1ULf/inVQL/9iqqYv/2KqdVCnVQt/+KdVAv/2Kqpi//Yqp1UKdVC3/4qp/i9+C//YqqmC3/4p1UAL/9iqqYLf/inVQAv/2Kqpgt/+Kqf4vfgL/9iqnVQp1UAAv/2KqdVCnVQAC//Yqp1UAA==) Deadfish - always way longer than the output and extremely inefficient. ]
[Question] [ First of all ... I would like to wish everyone a Merry Christmas (sorry if I am a day late for your timezone). To celebrate the occasion, we are going to draw a snowflake. Because the year is 201**5** and Christmas is on the 2**5**th (for a large portion of persons), we will draw a **Penta**flake. The Pentaflake is a simple fractal composed of pentagons. Here are a few examples [(taken from here)](http://mathworld.wolfram.com/Pentaflake.html):[![enter image description here](https://i.stack.imgur.com/kt6zm.gif)](https://i.stack.imgur.com/kt6zm.gif) Each Pentaflake has an order n. The Pentaflake of order 0 is simply a pentagon. For all other orders n, a Pentaflake is composed of 5 Pentaflakes of the previous order arranged around a 6th Pentaflake of the previous order. For example, a Pentaflake of order 1 is composed of 5 pentagons arranged around a central pentagon. # Input The order `n`. This may be given in any way except that of a predefined variable. # Output An image of the order `n` Pentaflake. Must be at least 100px wide and 100px long. It may be saved to a file, displayed to the user, or outputted to `STDOUT`. Any other form of output is not allowed. All image formats existing before this challenge are allowed. # Winning As codegolf, the person with the least number of bytes wins. [Answer] # Matlab, 226 ``` function P(M);function c(L,X,Y,O);hold on;F=.5+5^.5/2;a=2*pi*(1:5)/5;b=a(1)/2;C=F^(2*L);x=cos(a+O*b)/C;y=sin(a+O*b)/C;if L<M;c(L+1,X,Y,~O);for k=1:5;c(L+1,X+x(k),Y+y(k),O);end;else;fill(X+x*F, Y+y*F,'k');end;end;c(0,0,0,0);end ``` Ungolfed: ``` function P(M); function c(L,X,Y,O); %recursive function hold on; F=.5+5^.5/2; %golden ratio a=2*pi*(1:5)/5; %full circle divided in 5 parts (angles) b=a(1)/2; C=F^(2*L); x=cos(a+O*b)/C; %calculate the relative position ofnext iteration y=sin(a+O*b)/C; if L<M; %current recursion (L) < Maximum (M)? recurse c(L+1,X,Y,~O); %call recursion for inner pentagon for k=1:5; c(L+1,X+x(k),Y+y(k),O)%call recursion for the outer pentagons end; else; %draw fill(X+x*F, Y+y*F,'k'); end; end; c(0,0,0,0); end ``` Fifth iteration (already took quite a while to render). [![enter image description here](https://i.stack.imgur.com/OBKqq.png)](https://i.stack.imgur.com/OBKqq.png) A slight alteration of the code (unfortunately more bytes) results in this beauty=) [![enter image description here](https://i.stack.imgur.com/xgglE.png)](https://i.stack.imgur.com/xgglE.png) Oh, and another one: [![enter image description here](https://i.stack.imgur.com/r96D9.png)](https://i.stack.imgur.com/r96D9.png) [Answer] ## Mathematica, 200 bytes ``` a=RotationTransform b=Range r@k_:={Re[t=I^(4k/5)],Im@t} R@k_:=a[Pi,(r@k+r[k+1])/2] Graphics@Nest[GeometricTransformation[#,ScalingTransform[{1,1}(Sqrt@5-3)/2]@*#&/@Append[R/@b@5,a@0]]&,Polygon[r/@b@5],#]& ``` The last line is a function which can be applied to an integer `n`. Mathematica function names are long. Somebody should entropy-encode them and make a new language from it. :) When applied to `1`: [![enter image description here](https://i.stack.imgur.com/F0dvd.png)](https://i.stack.imgur.com/F0dvd.png) When applied to `2`: [![enter image description here](https://i.stack.imgur.com/vN6zI.png)](https://i.stack.imgur.com/vN6zI.png) [Answer] ## MATLAB, 235 233 217 bytes **Update:** a bunch of suggestions from [**@flawr**](https://codegolf.stackexchange.com/users/24877/flawr) helped me lose 16 bytes. Since only this allowed me to beat [flawr's solution](https://codegolf.stackexchange.com/a/67734/45297), and that I wouldn't have found the challenge without flawr's help in the first place, consider this a joint submission by us:) ``` N=input('');f=2*pi/5;c=1.5+5^.5/2;g=0:f:6;p=[cos(g);sin(g)];R=[p(:,2),[-p(2,2);p(1,2)]];for n=1:N,t=p;q=[];for l=0:4,q=[q R^l*[c-1+t(1,:);t(2,:)]/c];end,p=[q -t/c];end,p=reshape(p',5,[],2);fill(p(:,:,1),p(:,:,2),'k'); ``` This is another MATLAB solution, this one based on a philosophy of iterated function systems. I was mostly interested in developing the algorithm itself, and I haven't golfed too much on the solution. There's surely room for improvement. (I contemplated using a hard-coded fixed-point approximation for `c`, but that wouldn't be nice.) Ungolfed version: ``` N=input(''); % read order from stdin f=2*pi/5; % angle of 5-fold rotation c=1.5+5^.5/2; % scaling factor for contraction g=0:f:6; p=[cos(g);sin(g)]; % starting pentagon, outer radius 1 R=[p(:,2),[-p(2,2);p(1,2)]]; % 2d rotation matrix with angle f for n=1:N, % iterate the points t=p; q=[]; for l=0:4, q=[q R^l*[c-1+t(1,:);t(2,:)]/c]; % add contracted-rotated points end, p=[q -t/c]; % add contracted middle block end, p=reshape(p',5,[],2); % reshape to 5x[]x2 matrix to separate pentagons fill(p(:,:,1),p(:,:,2),'k'); % plot pentagons ``` Result for `N=5` (with a subsequent `axis equal off` for prettiness, but I hope that doesn't count byte-wise): [![N=5 pentaflake](https://i.stack.imgur.com/DJjZ9.png)](https://i.stack.imgur.com/DJjZ9.png) [Answer] # Mathematica, 124 bytes Mathematica supports new syntax for `Table` since version 10: `Table[expr, n]`, which saves another byte. `Table[expr, n]` is equivalent to `Table[expr, {n}]`. ``` f@n_:=(p=E^Array[π.4I#&,5];Graphics@Map[Polygon,ReIm@Fold[{g,s}~Function~Join[.62(.62g#+#&/@s),{-.39g}],p,p~Table~n],{-3}]) ``` The core of this function is using complex numbers to do tranformations and then convert them to points by `ReIm`. Test case: ``` f[4] ``` [![enter image description here](https://i.stack.imgur.com/JgYTK.png)](https://i.stack.imgur.com/JgYTK.png) [Answer] ## Mathematica, ~~199~~ 196 bytes Edging out Peter Richter's answer by a hair, here's one of my own. It leans heavily on graphics functionality, and less on math and FP. The CirclePoints builtin is [new in 10.1](https://reference.wolfram.com/language/ref/CirclePoints.html). ``` c=CirclePoints;g=GeometricTransformation; p@0=Polygon@c[{1,0},5]; p@n_:=GraphicsGroup@{ p[n-1], g[ p[n-1]~g~RotationTransform[Pi/5], TranslationTransform/@{GoldenRatio^(2n-1),n*Pi/5}~c~5 ] }; f=Graphics@*p ``` Edit: Thanks to DumpsterDoofus for GoldenRatio [Answer] # Mathematica, 130 bytes ``` r=Exp[Pi.4I Range@5] p=1/GoldenRatio f@0={r} f@n_:=Join@@Outer[1##&,r,p(f[n-1]p+1),1]~Join~{-f[n-1]p^2} Graphics@*Polygon@*ReIm@*f ``` I use a similar technique to [njpipeorgan's answer](https://codegolf.stackexchange.com/a/68543/39174) (in fact I stole his `2Pi I/5 == Pi.4I` trick), but implemented as a recursive function. Example usage (using `%` to access the anonymous function that was output on the last line): ``` %[5] ``` ![enter image description here](https://i.stack.imgur.com/hqyHQ.png) [Answer] ## Wolfram Language (Mathematica), ~~96~~ ~~90~~ 84bytes ``` Region@Polygon@ReIm@Nest[Join[Tr/@Tuples@{.62p,t=.39#},-t]&,{p=(-1)^(.4Range@5)},#]& ``` [![enter image description here](https://i.stack.imgur.com/Bos4W.png)](https://i.stack.imgur.com/Bos4W.png) ]
[Question] [ Consider a binary tree built the following way: * The root node is \$1\$ * For a given node \$n\$: + If \$n\$ is odd, its only child is \$2n\$ + If \$n\$ is even, one of its children is \$2n\$. If \$\frac {n-1} 3\$ is an integer and not already part of the tree, its right child is \$\frac {n-1} 3\$ * Recursively and infinitely define the tree this way, beginning from the root node. The resulting tree begins like this: [![collatz tree](https://i.stack.imgur.com/KxdQc.png)](https://i.stack.imgur.com/KxdQc.png) and continues forever, conjectured to contain all positive integers. If you choose any integer on this tree and work your way up through its parents, you'll find the [Collatz path](https://en.wikipedia.org/wiki/Collatz_conjecture) to \$1\$ for that integer. This is called a *Collatz graph* [This](https://upload.wikimedia.org/wikipedia/commons/0/0e/Collatz-tree%2C_depth%3D20.svg) is that tree to a depth of 20. We can read this tree as rows, from left to right, to create a list of lists: ``` [[1], [2], [4], [8], [16], [32, 5], [64, 10], [128, 21, 20, 3], [256, 42, 40, 6], [512, 85, 84, 80, 13, 12], [1024, 170, 168, 160, 26, 24], [2048, 341, 340, 336, 320, 53, 52, 48], ... ``` Flattened, this is [A088976](https://oeis.org/A088976). Your program should take a positive integer \$n\$ and output the first \$n\$ rows of this tree. You may output in any format that clearly and consistently shows a separation between each element in the row, and a distinct separation between the rows themselves. For example, spaces for the elements, and newlines for the rows. [This](https://tio.run/##VZBBboNADEXXcApvqoxT0pSgbCJxhV6AogoVoyKBZzQMjdrLU3ugUbJ9fvO/x@4nfFkulqWlDj7tMDTh98Pb62Q4g@CJoIQ3y4SXNOm7lfRTREKSzaiqvK6jwFCW8KojT2H2HF@kaSKR6onUWQ9sW4lZh9Uhr6Nvry@Nc8StOcE@KihYM9V@glOMhoZbMBEdIEfhxa3yPuNOOR6hwHRtpoFGbRbzsqb/k2keje6TyZZ4S/M02m8yKmnE9qnHQ2nLdqxnqITVojrfczD7B1NJz24OBhEzmMjJTXbvvMNlyc9/) is a sample program (ungolfed) that takes an integer and outputs each list on a line. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~37~~ 35 bytes ``` {x#x(,/{(4=6!x*4<x)(-6!)\2*x}')\,1} ``` [Try it online!](https://ngn.bitbucket.io/k#eJxLs6quUK7Q0NGv1jCxNVOs0DKxqdDU0DVT1Iwx0qqoVdeM0TGs5eJKUzA0AAD90ArT) ### How it works "n is even and `(n-1)/3` is an integer" is equivalent to "n is 4 mod 6". Avoiding the cycles is achieved by simply not allowing 4 to generate 1: **Claim:** A cycle cannot be formed midway into the tree. Any cycle in the tree must include the root, i.e. the number 1. **Proof:** Let's assume a node \$a\_0\$ has a child \$a\_1\$, which has a child \$a\_2\$, ..., which has a child \$a\_n\$, which in turn has a child \$a\_0\$. Also, let's call the Collatz \$3n+1\$ function \$f(x)\$. Then the following holds: $$ f(a\_1) = a\_0, f(a\_2) = a\_1, \cdots, f(a\_n) = a\_{n-1}, f(a\_0) = a\_n $$ If \$a\_0\$ has a parent (let's call it \$a\_{-1}\$), then \$f(a\_0) = a\_{-1}\$, which implies \$a\_{-1} = a\_n\$, and therefore \$a\_{-1}, a\_0, \cdots, a\_{n-1}\$ is also a cycle (which is one level closer to the root of the tree than \$a\_0, \cdots, a\_n\$). The same logic can be applied to \$a\_{-1}\$, \$a\_{-2}\$, ..., until the highest node reaches the root. Therefore, every cycle that exists in this tree goes through the root, i.e. the number 1. \$\blacksquare\$ The only cycle that involves the number 1 is the `[1, 2, 4]` cycle. Therefore, it suffices to prevent this cycle (i.e. stop 4 from generating 1) to prevent all cycles in the tree. ``` {x#x( ... )\,1} start with [1], iterate x times and collect values, and take first x values... ,/{ ... }' apply to each number and flatten... 2*x start with twice the input, (-6!)\ and append its floor division by 6 if (4=6!x*4<x) the original input is 4 mod 6 and it is over 4 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), 23 bytes ``` ḤḤ,’÷3ƊƊḂ?€FḞƑƇ>Ƈ1 1ÇС ``` [Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLhuKThuKQs4oCZw7czxorGiuG4gj/igqxG4biexpHGhz7GhzFcbjHDh8OQwqEiLCLDh8WS4bmY4oKsWSIsIiIsWyIxNSJdXQ==) I doubt this is optimal; I kind of ended up patching together like three fixes in a row on my original idea. Might retry later if I have time and remember. [Answer] # JavaScript (ES10), 70 bytes ``` f=(n,a=[1])=>n--?a+` `+f(n,a.flatMap(x=>x%6-4|x<5?2*x:[2*x,~-x/3])):'' ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjTyfRNtowVtPWLk9X1z5RO4ErQTsNJKqXlpNY4ptYoFFha1ehaqZrUlNhY2pvpFVhFQ0kdOp0K/SNYzU1rdTV/yfn5xXn56Tq5eSna6RpGBppav4HAA "JavaScript (Node.js) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~77~~ ~~75~~ 72 bytes -5 bytes thanks to [Dude coinheringaahing](https://codegolf.stackexchange.com/users/66833/dude-coinheringaahing), [G B](https://codegolf.stackexchange.com/users/18535/g-b) and [xnor](https://codegolf.stackexchange.com/users/20260/xnor)! ``` r=1, exec'print r;r=sum([[2*i]+[i/3][:i%6==4<i]for i in r],[]);'*input() ``` [Try it online!](https://tio.run/##BcE7CoAwDADQ3VNkkfopiB8c1JwkZBLFDLYltqCnr@@FL17eDTkr9rY43mM3QcVF0FXxSXdFNDTCLUk3Mi1SzojTJnx6BQFxoGyJ69U04kKKVZ1zP/0 "Python 2 – Try It Online") --- Assuming the Collatz conjecture holds, we can generate the tree by sorting Collatz paths. This is a lot longer, but maybe a bit more interesting: ``` c=lambda x:-1/x*[x]or c([x/2,3*x-1][x%2])+[x] k=0 exec'print[-w[k]for w in sorted(c(p)for p in range(-2**k,0)if-~k==len(c(p)))];k+=1;'*input() ``` [Try it online!](https://tio.run/##HcpBEoIgGEDhvadg0wgoo1CrHE7CsDDEYjBkiMa/TVcnbfu9Fz/5sQZRipHL@LxNI4Ir4x1QBXpNyGAFnWjPFBjXCk5Ck2YvlZd9ZcGaOiYXsmKb8nre/w25gF5rynbCBkdyWDwsjeFuMROU@rYnbmZfL@Viw/8iRA@@kXyoqQvxnTEphV9@ "Python 2 – Try It Online") [Answer] # [J](http://jsoftware.com/), 48 bytes ``` <6&(([:;<@(((],<.@%~)+:)#~1,(4<])*4=|)"0)&.>)<@1 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/bczUNDSiraxtHDQ0NGJ1bPQcVOs0ta00lesMdTRMbGI1tUxsazSVDDTV9Ow0bRwM/2typSZn5CukKRga/AcA "J – Try It Online") Just a port of [Bubbler's nice K answer](https://codegolf.stackexchange.com/a/233511/15469) into J, to see how they'd compare. The required boxing to handle ragged arrays, as well as some other details, made it harder to golf in J. [Answer] # [Perl 5](https://www.perl.org/), 60 bytes ``` $_=1;for$x(2.."@F"){s,\d+,2*$&.($&%6-4|$&<5?'':(1-$&)/3),ge} ``` [Try it online!](https://tio.run/##BcFLCsIwFAXQ@V1GeaaNJtGXn3905CoEEawiFBNaB4K6deM5ue27UAqdtry@pp5ejTWm2h8q@R7U8TJRdkzCNCRGUfsPiU3Y1fWqYU1CTp1Ut/ZbCsPCwSMgYo4FluAZmMEW7MAeHMDxl/Lznh5D0efc/QE "Perl 5 – Try It Online") For each input line: ``` $_=1; # init output string $_ with '1' for$x(2.."@F"){ # do input-1 times, input number is in "@F" due to -a s,\d+, # search-replace all positive ints in $_ with: 2*$& # 2 * the current int now in $& . # and possibly also another number ( $&%6-4|$&<5 # ...if $& % 6 == 4 and $& > 4 ? '' : (1-$&)/3 # negative x where x = ($&-1)/3 using '-' as separator ) ,ge # g=global, e=replacement from code not string } ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 58 bytes ``` NestList[If[#~Mod~6==4<#,##&,#&][2#,--+#/3]&/@#&,{1},#-1]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y@1uMQns7gk2jMtWrnONz@lzszW1sRGWUdZWU1HWS022khZR1dXW1nfOFZN3wEoVm1Yq6Osaxir9j@gKDOvRN8hzcHI4D8A "Wolfram Language (Mathematica) – Try It Online") Returns a list of row-lists. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~66~~ 64 bytes ``` ->n{[a=[1]]+(2..n).map{a=a.flat_map{|x|[x*2,x%6==4?x/3:1]-[1]}}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOjrRNtowNlZbw0hPL09TLzexoDrRNlEvLSexJB7Eqamoia7QMtKpUDWztTWxr9A3tjKM1QVqqa2t/V@gkBZtaBr7HwA "Ruby – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~69~~ 57 bytes ``` (`take`iterate(>>=g)[1]) g n=2*n:[n`div`3|n`mod`6==4,n>4] ``` [Try it online!](https://tio.run/##BcExDoMwDADAnVd4YICqHaCoQyXnIxTJFiRpRDARREy8HXP35322MarDn1aUebYUst0428oY9HXfDHXhQbB9yLcXmsJB71NoWSf6IHZPMd2gCwcBhLQFyVCCg6bVa3SR/a6vMaUb "Haskell – Try It Online") * saved 12 bytes thanks to @DelfadOr ! * Based on [@ovs answer](https://codegolf.stackexchange.com/a/233542/98541) 57 bytes alternative provided by @xnor ``` (`take`iterate(>>=g)[1]) g n=2*n:[k|k<-[2,4..n],3*k+4==n] ``` [Try it online!](https://tio.run/##BcExDoMwDADAva/w0AEoIJEyVTUfCZGwUJJGTq0IMvbtNXcfOtnnrAFXbbZK7LdU/UHVN8uCsbWTa28RBE0nL8s/fg/W9PM4iuufHT9mRHH6pSSAUI4kFe4QYDL630OmeOqwl3IB "Haskell – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes ``` ⊞υ¹FN«Iυ↓≔υη≔⟦⟧υFη«⊞υ⊗κ¿∧›κ⁴⁼⁴﹪κ⁶⊞υ÷κ³ ``` [Try it online!](https://tio.run/##Tc2xCsIwEAbguX2KGy8QB7U46CRWxEHpLg5pG20wJprk6iA@e2wKgrf9d8f3N51wjRU6xop8h8Rhylb5xTrAvXlQONK9lg4Zg3eeVU6ZgBvhAxIb3rKD7SUuS/syKa29V1eTjO4vns4cKOUR7UYo@5WVlmotW7yNXKYugGvT4s5JEYbaG4eCcdg@SWiPBYeDbUnbtF@wYeDn7E0oVa9amU7zEfvknxinszjp9Rc "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υ¹ ``` Start with the first row of just `1`. ``` FN« ``` Loop over the desired number of rows. ``` Iυ ``` Output each element on its own line. ``` ↓ ``` Leave a blank line between rows. ``` ≔υη ``` Save the current row. ``` ≔⟦⟧υ ``` Start a new row. ``` Fη« ``` Loop over the saved row. ``` ⊞υ⊗κ ``` Add the current element, doubled. ``` ¿∧›κ⁴⁼⁴﹪κ⁶ ``` If the current element is greater than 4 but equal to 4 modulo 6, then... ``` ⊞υ÷κ³ ``` ... add the current element, integer divided by 3. [Answer] ## [Perl 5](https://www.perl.org/), 63 bytes ``` @n=1;map{say"@n";@n=map{$_*2,$_<5||$_%6-4?():($_-1)/3}@n}0..pop ``` [Try it online!](https://tio.run/##K0gtyjH9X1qcqlBmqmdoYP3fIc/W0Do3saC6OLFSySFPyRooAOKqxGsZ6ajE25jW1KjEq5rpmthraFppqMTrGmrqG9c65NUa6OkV5Bf8///f0BgA "Perl 5 – Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), 67 bytes ``` >(n,a=[1])=show(a),0<n-1>[(a.|>j->[2j;~-j÷3][1:1+(j%6==4<j)])...;] ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/304jTyfRNtowVtO2OCO/XCNRU8fAJk/X0C5aI1Gvxi5L1y7aKMu6Tjfr8Hbj2GhDK0NtjSxVM1tbE5sszVhNPT0961igGUYGmv8B "Julia 1.0 – Try It Online") based on [ovs's answer](https://codegolf.stackexchange.com/a/233542/98541) output is in the form ``` [1][2][4][8][16][32, 5][64, 10][128, 21, 20, 3]... ``` ]
[Question] [ Write code that takes a string as input, and outputs a [truthy or falsey value](http://meta.codegolf.stackexchange.com/a/2194/31516) depending on whether or not the string follows these rules: If you stack each character on top of each other, convert to binary and sums each column, then all the sums should be identical. You may assume the input string contains only printable ASCII-characters (code points 32 - 126). As an example: The input `O5vy_+~` should return a truthy value, since its binary representation is: ``` 1001111 | O 0110101 | 5 1110110 | v 1111001 | y 1011111 | _ 0101011 | + 1111110 | ~ ------- 5555555 <- Sum of bits in each column. Should give a truthy value. ``` The input `PPCG` should return a falsey value, since its binary representation is: ``` 1010000 | P 1010000 | P 1000011 | C 1000111 | G ------- 4020122 <- Should give a falsey value ``` --- The twist is: **Your code should return a truthy value if it's used as input to your function / program.** I.e. the code must adhere to the same rules as above (your code can contain characters that are not ASCII 32-126). Your program/function only needs to handle printable ASCII as input. If your code contains something else, 8 bit, 16 bit encoding, Unicode, a custom made character set (or something else), then the binary representation of it should adhere to the same rules, but your code doesn't need to handle it as input. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so standard rules apply. [Answer] ## JavaScript (ES6), ~~123~~ ~~122~~ ~~120~~ 110 bytes ``` S=>[...S].map(S=>R.map((_GSSSSSSVWWW,V)=>R[V]-=S.charCodeAt()>>V&1),R=[_=3^3,_,_,_,_,_,_])&&!R.some(S=>S^R[_]) ``` Below is a hexdump with bit sums. ``` Addr. | Dump | #6 #5 #4 #3 #2 #1 #0 ------+-------------------------------------------------+--------------------- 00-0F | 53 3D 3E 5B 2E 2E 2E 53 5D 2E 6D 61 70 28 53 3D | 8 11 9 11 9 9 9 10-1F | 3E 52 2E 6D 61 70 28 28 5F 47 53 53 53 53 53 53 | 20 18 19 17 14 20 19 20-2F | 56 57 57 57 2C 56 29 3D 3E 52 5B 56 5D 2D 3D 53 | 30 24 32 25 26 30 29 30-3F | 2E 63 68 61 72 43 6F 64 65 41 74 28 29 3E 3E 56 | 41 37 37 32 34 38 36 40-4F | 26 31 29 2C 52 3D 5B 5F 3D 33 5E 33 2C 5F 2C 5F | 47 47 48 43 44 47 46 50-5F | 2C 5F 2C 5F 2C 5F 2C 5F 5D 29 26 26 21 52 2E 73 | 54 57 55 54 56 56 54 60-6D | 6F 6D 65 28 53 3D 3E 53 5E 52 5B 5F 5D 29 | 64 64 64 64 64 64 64 ``` ### Demo ``` let f = S=>[...S].map(S=>R.map((_GSSSSSSVWWW,V)=>R[V]-=S.charCodeAt()>>V&1),R=[_=3^3,_,_,_,_,_,_])&&!R.some(S=>S^R[_]) console.log(f("O5vy_+~")) console.log(f("Hello World!")) console.log(f(`S=>[...S].map(S=>R.map((_GSSSSSSVWWW,V)=>R[V]-=S.charCodeAt()>>V&1),R=[_=3^3,_,_,_,_,_,_])&&!R.some(S=>S^R[_])`)) ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~10~~ 9 bytes ``` BXs&=?I&] ``` Input is a string enclosed with single quotes (if the input contains single qoutes, escape them by duplicating). Output is `3` as truthy and nothing (empty output) as falsy. [Try it online!](https://tio.run/nexus/matl#@@8UUaxma@@pFvv/v7q/aVllvHadOgA "MATL – TIO Nexus") The code in binary is as follows: ``` B 1 0 0 0 0 1 0 X 1 0 1 1 0 0 0 s 1 1 1 0 0 1 1 & 0 1 0 0 1 1 0 = 0 1 1 1 1 0 1 ? 0 1 1 1 1 1 1 I 1 0 0 1 0 0 1 & 0 1 0 0 1 1 0 ] 1 0 1 1 1 0 1 Sum 5 5 5 5 5 5 5 ``` ### Explanation ``` B % Input string (implicit). Convert each char to its ASCII code, and % then to binary. This gives a binary matrix, with each char of the % input corresponding to a row Xs % Sum of each column. Gives a row vector &= % All pairwise equality comparisons ? % If all are true I % Push 3 & % Specify that the next function, namely implicit display, will % take one input, instead of the whole stack which is the default ] % End % Display (implicit) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` OBUSE&889. ``` **[Try It Online!](https://tio.run/nexus/jelly#@@/vFBrsqmZhYan3//9/dX/Tssp47Tp1AA)** Or see [tests and self-input](https://tio.run/nexus/jelly#@@/vFBrsqmZhYan3/3D7o6Y1//9Hq/ubllXGa9ep6yioBwQ4u4NohDL1WAA) (the code is all printable ASCII, which have the same values in Jelly's [code page](https://github.com/DennisMitchell/jelly/wiki/Code-page), as seen below). ``` Char -> Hex -> Decimal -> Binary O 0x4F 79 0b1001111 B 0x42 66 0b1000010 U 0x55 85 0b1010101 S 0x53 83 0b1010011 E 0x45 69 0b1000101 & 0x26 38 0b0100110 8 0x38 56 0b0111000 8 0x38 56 0b0111000 9 0x39 57 0b0111001 . 0x2E 46 0b0101110 ------- 5555555 ``` ### How? ``` OBUSE&889. - Main link: string O - cast to ordinals B - convert to binary U - upend (reverses each to prepare for vectorised sum) S - sum (vectorises) E - all equal? (yields 1 if all bit-sums are equal and 0 if not) 889. - 889.0 & - bitwise and (1 & 889.0 is 1; and 0 & 889.0 is 0) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 bytes ``` OBUSE$*8?8 ``` Uses no no-ops or comments. [Try it online!](https://tio.run/nexus/jelly#@@/vFBrsqqJlYW/x/@HuLYfbHzWtiVR4uGP7o4Y5CsEFOZklCoklCjmZealpqakpxToKuYkFCsn5Kak6CsWpBYlFiSWpCkmVCAV6///7m5ZVxmvXcQUEOLtzIYwHAA "Jelly – TIO Nexus") ### Binary breakdown ``` O 1 0 0 1 1 1 1 B 1 0 0 0 0 1 0 U 1 0 1 0 1 0 1 S 1 0 1 0 0 1 1 E 1 0 0 0 1 0 1 $ 0 1 0 0 1 0 0 * 0 1 0 1 0 1 0 8 0 1 1 1 0 0 0 ? 0 1 1 1 1 1 1 8 0 1 1 1 0 0 0 ———————————————— ∑ 5 5 5 5 5 5 5 ``` ### How it works ``` OBUSE$*8?8 Main link. Argument: s (string) O Ordinal; map all characters in s to their code points. B Binary; convert each code point to base 2. U Upend; reverse each binary array to right-align the digits. 8? If 8 is non-zero (it is): SE$ Sum the corresponding digits and test the the sums for equality. Else (never happens): * 8 Raise all binary digits to the eighth power. ``` [Answer] # Mathematica, 88 bytes ``` Total@IntegerDigits[ToCharacterCode@#,2,7]~MatchQ~{"?";a_ ..}& ``` Contains many unprintable characters between the quotes. Has 49 of each bit. Here's the hexdump: ``` 0000-0010: 54 6f 74 61-6c 40 49 6e-74 65 67 65-72 44 69 67 Total@In tegerDig 0000-0020: 69 74 73 5b-54 6f 43 68-61 72 61 63-74 65 72 43 its[ToCh aracterC 0000-0030: 6f 64 65 40-23 2c 32 2c-37 5d 7e 4d-61 74 63 68 ode@#,2, 7]~Match 0000-0040: 51 7e 7b 22-3f 1f 1f 1f-1f 1f 1f 1f-1f 1f 1f 1f Q~{"?... ........ 0000-0050: 1f 1f 1f 1f-1f 1a 1a 1a-1a 18 18 18-18 18 10 22 ........ ......." 0000-0058: 3b 61 5f 20-2e 2e 7d 26 ;a_...}& ``` [Answer] # Octave, ~~53~~ 52 bytes Making a complete rewrite helped me golf the code 5 bytes, but I had to add more no-ops, making it a net-save of only 1 byte. ``` @(_)~diff(sum(de2bi(+_)))%RRPPPVVVW?????????________ ``` I can't add a TIO-link, since none of the online interpreters have implemented the communication toolbox necessary for `de2bi`. Changing it to `dec2bin` instead would cost 4 bytes (2 for working code, and two no-ops). I found no way to avoid any of the 27 no-ops. All function names and parentheses are between either below 64, or higher than 96, meaning all "necessary" characters have a 1 in the 6th position (from the right, 2^5). I had a solution with only 23 no-ops, but the code itself was longer. The actual code is 25 bytes, and has the following column sum when counting the bits of the binary equivalent: ``` 15 22 6 15 10 9 13 ``` There are 22 bits in the 6th position from the right (2^5), and only 6 bits in the 4th position from the right (2^3). That means, we have to add *at least* 16 bytes, to get the 6 up to 22. Now, the comment character `%` adds a bit to the 6th position, increasing it to 23. All printable ASCII-characters needs at least one of the two top bits to be `1`. Therefore, adding 17 bytes will give us at least 27 bits in each of the two "top spots" (2^6 and 2^5). Now, we have 27 bits in the top two spots, and 22 in the rest. In order to get to an equilibrium, we have to add 10 bytes, to get to an even 32 bits in each position. **An explanation of the new code (52 bytes):** ``` @(_)~diff(sum(de2bi(+_))) @(_) % An anonymous function that take a variable _ as input % We use underscore, instead of a character, since it has the % most suitable binary represetation de2bi(+_) % Convert the input string to a binary matrix sum(de2bi(+_)) % Take the sum of each column diff(sum(de2bi(+_))) % And calculate the difference between each sum ~diff(sum(de2bi(+_))) % Negate the result, meaning 0 becomes true, % and everything else becomes false ``` A vector containing only 1s (true) is evaluated to true in Octave, and a vector containing at least one zero is evaluated to false in Octave. **An explanation of the old code (53 bytes):** ``` @(_)!((_=sum(de2bi(+_)))-_(1))%RRRFVVVVVVVVV_____???? @(_) % An anonymous function that take a variable _ as input % We use underscore, instead of a character, since it has the % most suitable binary represetation ! % Negate the result, meaning 0 becomes true, and everything else becomes false de2bi(+_) % Convert the input string to a binary matrix sum(de2bi(+_)) % Take the sum of each column (_=sum(de2bi(+_))) % Assign the result to a new variable, also called _ % It's not a problem that we use the same variable name, due % to the order of evaluation ((_=sum(de2bi(+_)))-_(1)) % Subtract the first element of the new variable _ % If all elements of the new variable _ are identical, then this % should give us a vector containing only zeros, % otherwise, at least one element should be non-zero !((_=sum(de2bi(+_)))-_(1)) % And finally, we negate this. ``` A vector containing only 1s (true) is evaluated to true in Octave, and a vector containing *at least* one zero is evaluated to false in Octave. [Answer] ## JavaScript (ES6), ~~139~~ ~~111~~ 107 bytes ``` f= S=>![...""+1E6].some((____________ABQWWWWWWWWW,P)=>P*=R^(R^=R,[...S].map(Q=>R+=Q.charCodeAt()>>P&1),R),R=0) ``` ``` <textarea oninput=o.textContent=f(this.value) style=width:100% rows=10>S=>![...""+1E6].some((____________ABQWWWWWWWWW,P)=>P*=R^(R^=R,[...S].map(Q=>R+=Q.charCodeAt()>>P&1),R),R=0)</textarea><div id=o>true ``` Contains ~~81~~ ~~63~~ 61 of each bit. [Answer] # Scala, 149 bytes ``` _.map(C=>("0"*7++(BigInt(C)toString 2))takeRight 7 map(_-48)).transpose.map(_.sum).toSet.size==1//______________________________ ``` ### Usage: ``` val f:(String=>Any)=_.map(C=>("0"*7++(BigInt(C)toString 2))takeRight 7 map(_-48)).transpose.map(_.sum).toSet.size==1//______________________________ println(f("string here") ``` ### Hexdump: ``` 00000000 5f 2e 6d 61 70 28 43 3d 3e 28 22 30 22 2a 37 2b |_.map(C=>("0"*7+| 00000010 2b 28 42 69 67 49 6e 74 28 43 29 74 6f 53 74 72 |+(BigInt(C)toStr| 00000020 69 6e 67 20 32 29 29 74 61 6b 65 52 69 67 68 74 |ing 2))takeRight| 00000030 20 37 20 6d 61 70 28 5f 2d 34 38 29 29 2e 74 72 | 7 map(_-48)).tr| 00000040 61 6e 73 70 6f 73 65 2e 6d 61 70 28 5f 2e 73 75 |anspose.map(_.su| 00000050 6d 29 2e 74 6f 53 65 74 2e 73 69 7a 65 3d 3d 31 |m).toSet.size==1| 00000060 2f 2f 5f 5f 5f 5f 5f 5f 5f 5f 5f 5f 5f 5f 5f 5f |//______________| 00000070 5f 5f 5f 5f 5f 5f 5f 5f 5f 5f 5f 5f 5f 5f 5f 5f |________________| 00000080 1f 1f 1f 1f 1e 1e 1e 1e 16 16 16 16 16 12 12 10 |................| 00000090 10 10 10 10 10 |.....| ``` ### Ungolfed: ``` string => string.map(char => ( "0" * 7 ++ BigInt(char).toString(2) ).takeRight(7).map(n=>n-48) ).transpose .map(bits=>bits.sum) .toSet .size == 1 //______________________________ ``` ### Explanation: ``` string => //create an anonymous function with a parameter string string.map(char => //map each char in the string to ( "0" * 7 //a string of 7 zeroes ++ //concatenated with BigInt(char).toString(2) //the ascii value as a binary string ).takeRight(7) //the last 7 items from this sequence .map(n=>n-48) //where each digit is mapped to its numerical value ).transpose //transpose, so the colums become rows and vice-versa .map(bits=>bits.sum) //maps the bits in each column to their sum .toSet //and convert the sequence of sums to a set .size == 1 //which has 1 element of the sums are the same //______________________________ ``` [Answer] # [J](http://jsoftware.com/), 45 bytes ``` [:(*/@:={.)[:+/2 #.inv 3 u:]NB.____UUUUUUUUDD ``` [Try it online!](https://tio.run/nexus/j#RY5xa8IwEMX/91Nkc2sSradTBl0k6tRNBmMrLaaDUoOr7SxMHU0VxoZf3aWhsndw3O9x3D3FWQexTgueH08hI432iPEfoCFrtruoDtn2gHpoz6KXMUiteaXp9ERrl4BTzrCtakWMOEP49fbwLZtHjPoIu@5kVg6qBJ8PQgDwI9gsv4gmzwxEznwjEQSBLaj2QxG1uA/xeplPdqvkviB0MBDWDbU9HkreW/Rs@V8RtawLD9Ruk5RX/YUXag9XeXS3dajx3H@4ajhDx@QyaDnOHRg0bfymLD58siJDIyLpcZWlKVH7DVkl3feMNCWl9NrzXNcVQgTDs2Sl80vSZqieLOM11d9rSbzeoV9GsCrybPuB@zhP1P6zwNQG7Zf5AKWo3Nfrpz8 "J – TIO Nexus") Includes test cases for most submissions submitted, along with the source code. [Answer] # [Haskell](https://www.haskell.org/), 118 bytes ``` _R _S=mod _S 2:_R(div _S 2) _Z _S|_V:_W<-take 7.foldl1(zipWith(+))$_R.fromEnum<$>_S=all(==_V)_W --________ ``` [Try it online!](https://tio.run/nexus/haskell#@x8fpBAfbJubnwKkFIys4oM0UjLLwGxNrvgoIKMmPswqPtxGtyQxO1XBXC8tPyclx1CjKrMgPLMkQ0NbU1MlPkgvrSg/1zWvNNdGxQ5oWmJOjoatbXyYZnw4l65ufHy8vLy8uDAYCAnFg8D/3MTMPAVbhYKizLwSBRUFoE1KeFwSk0cFp8Tkgd0SExoMRa4hTjEuzsY4sBEIgx2r9B8A "Haskell – TIO Nexus") Usage: `_Z "some string"` returns either `True` or `False`. There are some unprintable chars in the comment on the last line, so here is a string of the program using escaped chars: ``` "_R _S=mod _S 2:_R(div _S 2)\n_Z _S|_V:_W<-take 7.foldl1(zipWith(+))$_R.fromEnum<$>_S=all(==_V)_W\n--___\US\US\US\ETB\DC3\DC3\DC3\DC3\DC3\DC3\DC2\DC2_____" ``` Each bit occurs 68 times. --- The shortest code I came up with was 82 bytes: ``` b n=mod n 2:b(div n 2) (all=<<(==).head).take 7.foldl1(zipWith(+)).map(b.fromEnum) ``` However the sums of the bits for this code are `[33,28,41,48,20,79,46]`, so `79 - 20 = 59` no-ops plus 2 bytes for starting a comment would additionally be needed, totalling in 143 bytes. While rearranging the program I found that using upper case letters as variable names helps to level the sums because they don't have the bit in the 6th position set. Because Haskell does not allow variable names to start with an upper case letter they need to be prepended with `_`, which also does not set the 6th bit. In doing so I ended up with the above solution which has 97 bytes before adding the no-ops and the bist sum to `[50,47,56,56,48,68,60]`, so `(68 - 47) = 21`, so only 21 bytes need to be added in the comment. [Answer] # PHP, ~~95~~ ~~93~~ 91 bytes I am so happy that PHP function names are case insensitive! ``` FOR(ZZSSSSQ__*;$W=ORD($argn[$T++]);)FOR($V=7;$V--;)$R[$V]+=$W>>$V&1;PRINT MIN($R)==MAX($R); ``` where the `*` must be replaced with ASCII 151 (0x97). (PHP would complain about any control character in the code - apart from `\r` and `\n`, but I need something with bit 4 set, so I added 128.) +1 byte for pure printable ASCII: Use `_7` instead. Run with `echo '<input>' | php -nR '<code>'` or [test it online](http://sandbox.onlinephpfunctions.com/code/1bc6b8b35bfe0fc8e9cb8520dc54264b2ce8805d). Output is `1` for truthy, empty for falsy. [Answer] # Python 2, 117 bytes All "spaces" are tabs to reduce number of 0x20 bits. ``` def Y(S): O=map(sorted,zip(*['{:07b}'.format(ord(W))for W in S])) return O[1:]==O[:-1]#V_____________ ``` Contains 66 of each bit. (There is no `'%07b'` as explained [in this issue](http://bugs.python.org/issue13602).) Hex dump: ``` 00000000: 64 65 66 09 59 28 53 29 3a 0a 09 4f 3d 6d 61 70 def.Y(S):..O=map 00000010: 28 73 6f 72 74 65 64 2c 7a 69 70 28 2a 5b 27 7b (sorted,zip(*['{ 00000020: 3a 30 37 62 7d 27 2e 66 6f 72 6d 61 74 28 6f 72 :07b}'.format(or 00000030: 64 28 57 29 29 66 6f 72 09 57 09 69 6e 09 53 5d d(W))for.W.in.S] 00000040: 29 29 0a 09 72 65 74 75 72 6e 09 4f 5b 31 3a 5d ))..return.O[1:] 00000050: 3d 3d 4f 5b 3a 2d 31 5d 23 56 5f 5f 5f 5f 5f 5f ==O[:-1]#V______ 00000060: 5f 5f 5f 5f 5f 5f 5f 16 16 16 16 16 16 16 16 16 _______......... 00000070: 16 16 14 14 10 ..... ``` ]
[Question] [ # How many atoms in the hydrocarbon? A hydrocarbon is a chemical compound which consists of only hydrogen and carbon atoms. For this challenge, we will only consider the three simplest kinds of hydrocarbons: **alkanes**, **alkenes**, and **alkynes** with no branches. An **alkane** with \$n\$ carbon atoms contains \$2n+2\$ hydrogen atoms. An **alkene** with \$n\$ carbon atoms contains \$2n\$ hydrogen atoms. An **alkyne** with \$n\$ carbon atoms contains \$2n-2\$ hydrogen atoms. Each kind of hydrocarbon is named with a prefix indicating the number of carbon atoms it contains, followed by the suffix `ane`, `ene`, or `yne` if it is an alkane, alkene, or alkyne respectively. The numerical prefixes are as follows: ``` 1 <-> meth 2 <-> eth 3 <-> prop 4 <-> but 5 <-> pent 6 <-> hex 7 <-> hept 8 <-> oct 9 <-> non 10 <-> dec ``` For example, we can see `propane` has 3 carbon and 8 hydrogen atoms, and `heptyne` has 7 carbon and 12 hydrogen atoms. ## Challenge Your task is to write a function or program that receives a string or list of characters representing the name of a hydrocarbon, and produces or outputs the number of carbon and hydrogen atoms in a molecule of that hydrocarbon. For each of the 30 hydrocarbon names, the code must accept at least one possible capitalization of that name. For example, it is fine if your code works for `mEthane` but not `methane`, and `ETHAnE` but not `ETHANE`, and `Propane` but not `propane`. The inputs `methene` and `methyne` may give undefined output since those are not real chemicals. The input and output can be in any convenient format. You don't need to label which number represents carbon and which represents hydrogen, just keep the order of the numbers consistent. You may assume the input will correspond to a valid hydrocarbon, and there are at most 10 carbon atoms. ## Examples ``` Possible Input -> Possible Output Methane -> 1 4 propane -> 3 8 Heptyne -> 7 12 Decene -> 10 20 ``` ## Rules * No standard loopholes. * Shortest code in bytes wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~27 26~~ 24 bytes *Saved 1 byte thanks to @KevinCruijssen* *Saved 2 bytes thanks to @Grimmy* **Note:** This code was based on my understanding that only the capitalization of the first letter was customizable. It has since been clarified that it applies to *all* letters, leading to [this significantly shorter answer](https://codegolf.stackexchange.com/a/196708/58563) by Grimmy. Expects `mEpBPhHond` for the capitalization of the first letter. ``` ćC•>·¿*•s÷θD>,₂I3(èH÷+·, ``` [Try it online!](https://tio.run/##yy9OTMpM/f//SLvzo4ZFdoe2H9qvBWQUH95@boeLnc6jpiZPY43DKzwOb9c@tF3n/3@P1IKSyrxUAA "05AB1E – Try It Online") ### How? We define the following magic constant: $$M=1902159854$$ The number of carbon atoms is given by: $$c=\left(\left\lfloor\frac{M}{n}\right\rfloor\bmod 10\right)+1$$ where \$n\$ is the first character of the input turned into an 05AB1E code point (0-9, A-Z, a-z, ...). ``` input | n | floor(M/n) | mod 10 -------+-----+------------+-------- meth- | 48 | 39628330 | 0 Eth- | 14 | 135868561 | 1 prop- | 51 | 37297252 | 2 But- | 11 | 172923623 | 3 Pent- | 25 | 76086394 | 4 hex- | 43 | 44236275 | 5 Hept- | 17 | 111891756 | 6 oct- | 50 | 38043197 | 7 non- | 49 | 38819588 | 8 dec- | 39 | 48773329 | 9 ``` ### Commented ``` # example input: 'Heptyne' ć # extract the first character -> 'H' C # turn it into an integer -> 17 •>·¿*• # push the magic constant 1902159854 s÷ # swap + integer division -> 1902159854 / 17 = 111891756 θ # keep the last digit (therefore a modulo 10) -> 6 D> # duplicate and increment the copy , # print the number of carbon atoms ₂ # push 26 I # push the input string 3(è # extract the 3rd to last character -> 'y' H # parse it as base-36 -> 34 ÷ # integer division -> 26 / 34 = 0 + # add to the number of carbon atoms - 1 -> 6 · # double , # print the number of hydrogen atoms ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ ~~12~~ 11 bytes ``` .uJ4ôCx<O1ǝ ``` [Try it online!](https://tio.run/##LcwxCsIwGMXxvaconVUQHMUiNSAObcAIOrYS0KGpaBUDXsVbeAMHjxXf@5rpDz8er7vVzdmG18PnWTpepFnut2Fy38y@n@I5r6a/dxiF1vZr72zCWqekdWmTyFEjXq6VprJklt7sejJCRWSsnJExKmOUflJ7MkJFBtRmUG0G1jKujvKMUBFi2bmDkyggsgSubMElwiWC5R8 "05AB1E – Try It Online") This takes full advantage of the rule that only one possible capitilization has to be handled for each input. All inputs are at least 6 letters long, so we can store 6 bits of data in the capitilization. 4 of those bits are used to store the carbon count, and the remaining 2 store half of the extra hydrogen count (0 for alkynes, 1 for alkenes, 2 for alkanes). ``` .u # uppercase? (returns a list of 0s and 1s) J # join that list to a string 4ô # split in chunks of 4 digits C # convert each chunk from binary x # double each, without popping the original list < # -1 from each O # sum 1ǝ # replace the second element of the list with this sum ``` Alternative 11: ``` .u2β3‰<.¥¦ƶ ``` [Try it online!](https://tio.run/##Jc4xCsJAFIThPqcI1ppCWzEEXbB6BozFlht5EAt3RRNxwcLLaC0WHiCFpYfwIuu8pPoZvmbcyZQ7DtezTwfxaBYPUr8OSTP@via/23OatPf28XmHYdhzXWniSKpISZfGcoR4qyRM3TLAw9HlGihVtt8ZuGwKDS43NUMRI8hUe6CUqd8ZuFIXDUYUdSsDVpwXXhBl228DdvPCgxFlu5UB7YrkMiKPyVk5vOCtHEbkMILDfw) [Answer] # [R](https://www.r-project.org/), ~~96~~ ~~86~~ ~~82~~ 79 bytes ``` `!`=utf8ToInt;(5-rev(K<-!scan(,""))[3]%%16)/2*0:1+match(K[1],!"mepbPhHond")*1:2 ``` [Try it online!](https://tio.run/##K/r/P0Exwba0JM0iJN8zr8Raw1S3KLVMw9tGV7E4OTFPQ0dJSVMz2jhWVdXQTFPfSMvAylA7N7EkOUPDO9owVkdRKTe1ICkgwyM/L0VJU8vQyuh/SmpyZV7qfwA "R – Try It Online") Accepts the prefixes with capitalization `mepbPhHond` in order; returns `c(Carbon, Hydrogen)`. `yea` for this answer. Thanks to Robin Ryder for golfing down [4 bytes](https://tio.run/##K/r/P0Exwba0JM0iJN8zr8Ta21axODkxT0NHSUnTOlkjz0Y3N7EkOUPDO9owVkdRKTe1ICkgwyM/L0VJU8dIK09bw1S3KLVMw1sz2jhWVdXQTFPfSPN/SmpyZV7qfwA). [Answer] # JavaScript (ES6), 62 bytes Similarly to other answers, expects all names in lowercase, except `Pent-` and `Hept-`. Returns `[carbon, hydrogen]`. ``` s=>[n='epbPhHond'.search(s[0])+2,n+/a/.test(s)-/y/.test(s)<<1] ``` [Try it online!](https://tio.run/##bcmxDsIgEADQ3R8BUgvVuTh37N50oHAVTb0jHDHp12Pi4GC6veQ93duxz49UWqQAdbWV7W1CKyAtYxwIg9AMLvsoeepm1VzP2BhndAEuklVr9p/7/jJXT8i0gd7oLlcpXlCiQxBKnf4mZUrHM0Aq@@EE8PCN@gE "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), ~~84~~ 79 bytes A version where the capitalization doesn't matter. Returns `[carbon, hydrogen]`. ``` s=>[n=-~'519.80.76423'[parseInt(s[0]+s[2],28)%17],n+/a/.test(s)-/y/.test(s)<<1] ``` [Try it online!](https://tio.run/##bcm7CsIwFADQ3f@QJLRN2vpohdbJQQfBPWQI6a0PShJ6g9DFX4/i4CDdDpyHfmo0492HzLoOYt9GbPfSttmLbIodr3NebdflikivR4STDRRlrhKUpUrLmi2LSqU2EVrwAPhJlonp56YpVDTOohuAD@5Ke0rOEG7aAmFs8TeX0fn5OYIP0@wcwMA34hs "JavaScript (Node.js) – Try It Online") ## How? ### Carbon We can concatenate the first and third characters of each prefix to build a unique string identifier. *Example:* `meth` → `mt` We can convert this string ID to an integer ID in \$[0..11]\$ (still unique) by parsing it as base-28 and applying a modulo \$17\$ (these values were found with a brute-force search). Because the character set of base-28 is `'0'` to `'r'`, the parsing stops if a character above `'r'` is encountered. *Example:* `mt` → `m` → \$22 \bmod 17=5\$ The results are summarized in the following table: ``` input | key | base 28 -> dec. | mod 17 -------+------+-----------------+-------- meth- | 'm' | 22 | 5 eth- | 'eh' | 409 | 1 prop- | 'po' | 724 | 10 but- | 'b' | 11 | 11 pent- | 'pn' | 723 | 9 hex- | 'h' | 17 | 0 hept- | 'hp' | 501 | 8 oct- | 'o' | 24 | 7 non- | 'nn' | 667 | 4 dec- | 'dc' | 376 | 2 ``` ### Hydrogen Neither `'a'` nor `'y'` appears in any of the prefixes. Therefore, it is safe to test whether the suffix is `-ane` or `-yne` by looking for these letters in the entire input string. The following expression: ``` /a/.test(s) - /y/.test(s) ``` evaluates to either \$-1\$ for `-yne`, \$0\$ for `-ene` or \$1\$ for `-ane`. Given the number \$n\$ of carbon atoms, the number of hydrogen atoms is: ``` (n + /a/.test(s) - /y/.test(s)) << 1 ``` (and because `<<` has a higher precedence than `+` and `-`, the parentheses can be omitted) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 33 31 bytes ``` Kx"mepbPhHond"hQhKy+K/%CePPQ7 3 ``` [Try it online!](https://tio.run/##K6gsyfj/37tCKTe1ICkgwyM/L0UpIzDDu1LbW1/VOTUgINBcwfj/f6Wk0pLKvFQlAA "Pyth – Try It Online") Uses, as you can see, `mepbPhHond` capitalization. Probably can be golfed much further. Returns carbon, hydrogen on newlines ## How it works ``` Kx"mepbPhHond"hQhKy+K/%CePPQ7 3 x hQ - The index of the first letter of the input "mepbPhHond" - in "mepnPhHond" K hK - Assign to K... and then print K+1 CePPQ - The codepoint of the third last character in the input (Q[:-1][:-1][-1]) /% 7 3 - Modulo 7 divided by 3 (ane, ene, yne -> 2, 1, 0) +K - ... plus K y - ... times 2, and print implicitly ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), 60 bytes As other answers, all the names except for those starting with `Prop-` or `Hept-`, must be lowercase. ``` lambda x:(c:=' mePbphHond'.find(x[0]),c+'ea'.find(x[-3])<<1) ``` -4 bytes thanks to @Arnauld [Try it online!](https://tio.run/##XcyxDoMgEADQvV/hBpfWpo1LY3R3dG8dEI5gUo4LYcCvx8HEgfUNj/fkAnUfjsWOv/JXfjWqyb3U/Sgaj/PKbgpkxNNuZGT@vhZ46LtAdUnbLTAMbygcN0rSSuExOUUoAG6XzTFwbRNy2iszqLEiRkq1OcznVg4) --- ### Fun fact: Another interesting fact I observerd is the following one: * \$ord(a)=97\to9-7=2\$ which is the number we have to add for alk**a**nes. * \$ord(e)=101\to1-0-1=0\$ which is the number we have to add for alk**e**nes. * \$ord(y)=121\to1-2-1=-2\$ which is the number we have to add for alk**y**nes. I don't think that I can modify my answer using this way to be less bytes thank it is right now, but I thought it was worth mentioning and maybe another answer can use it effectively! An implementation of the above idea is the [following one](https://tio.run/##XcwxC4MwEIbhvb8iW2KrpdSlCO6O7q2DJheMmOSIJ@ivt4qlQ258uPfDlXrv8heGTZefbWxtp1q2FEIWJWcW6g77yjvF79o4JZb3o0nS51XeAqhZgvgFJh0Kkw2pbVEYR@lEQfhw/Gd5kxx30cFbpmcnyftxYsaiD8TOmQ3DXgktuAXqWwd8D/5WB4@xVYC0RqZAQkQIjmLrYTnXti8): ``` lambda x:(c:=' mePbphHond'.find(x[0]),2*c+reduce(lambda i,j:i-j,map(int,str(ord(x[-3]))))) from functools import reduce ``` which obviously is much more bytes (119). [Answer] # [Python 2](https://docs.python.org/2/), 66 bytes ``` def f(s):n='mePbpHhond'.find(s[0]);return-~n,2*(n+ord(s[-3])%50%3) ``` [Try it online!](https://tio.run/##LY6xDoIwFEVn@Yq3kFIFQyAuGHZGdsKg9jUw8Nq0z0QWf70WYTu5Jzm5duXJUBWCQg0687KhVizYP20XdyWueiaV@aEc5d0hvx0VX8qrc0YX4zZR1KNMb2Vay8Do2UMLQwzw9CAUOYjeGXugRWLccULL644dfg6v8LXpMdHGAcNM8C82ycm6mRg4jw9ZJuEH "Python 2 – Try It Online") Over thinking it a bit. Accepts only lower case, except for 'Prop' and 'Hept' (which must be capitalized). Returns (carbon, hydrogen). # [Python 2](https://docs.python.org/2/), ~~84~~ 82 bytes ``` def f(s):n=int('8702563914'[hash(s[:-3])%876%10]);return n+1,2*(n+ord(s[-3])%50%3) ``` [Try it online!](https://tio.run/##LY45DoMwEADr8IptkO1AJI5whIiXIAoUFpkia8veFLzesUi6KWaksQdrQ1UIK26wSa8GGndiKfquqJq2fpR3MenFa@mn4VbPKu27Ni2LWT0d8scRUFbm1VVSZtwapdNpirRWgdGzhxEm8UbWC6HIQVhn7B81Wj5@uOILI83JZhww7ARnPCQX6@IOcB7nWCXhCw "Python 2 – Try It Online") Only accepts lower case. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~74~~ 67 bytes ``` ->s{z=" etthroutenexepctonec".index s[1,2];[z/2,z-2*(s[-3]<=>?e)]} ``` [Try it online!](https://tio.run/##VdBBDoIwEIXhqzRdqQGNuFTwIE0XBR/BBW0DJamAZ0eMZRp3X/K/2Uw3lK@lzpe06Kcx54zBuaYzg4OGh62c0aj48akf8KwX5ySTVzGesmRMs8OuF@lF3vLijr18L4K3cI3S4AnjfwLp9ZPtjFWRiAyDcnCKBNJ2Dr3lLxEZBg28IoFE1ToVicgwMNXWV4EUqjZakUAK9YFKkUD6VnlslZ1mP1smfFILL9evfQA "Ruby – Try It Online") Thanks @Value Ink for ~~golfing it for me. :-)~~ -7 bytes [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/mathematica/), ~~26~~ 25 bytes ``` Tally@*AtomList@*Molecule ``` Thanks to att for the byte reduction. [![enter image description here](https://i.stack.imgur.com/XYCRy.png)](https://i.stack.imgur.com/XYCRy.png) [Answer] # [Python 3](https://docs.python.org/3/), 83 bytes ``` x=input();n=list('_mepbPhHond').index(x[0]);print(n,2*n+{'a':2,'e':0,'y':-2}[x[-3]]) ``` [Try it online!](https://tio.run/##BcFRC4MgFAbQn3N1sxH2ZvTeY@8iw6GQsD4v5cCIfrs7h8@yZgyt1SmBf0XIEdM3HUXQe4v8WdY5I5B8JYRYRbW9kyPvCUVA6QeeF3kyWlEk0ys6yXT6ttV2g3OyNd4ze8Q/ "Python 3 – Try It Online") -51 bytes thanks to 79037662 [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 39 bytes ``` ≔⊘⁺³⌕”↶↓>AkQN!{a⁶⟧”…θ⁻Lθ⁵ηI⟦η⊗⁻⁺η№θa№θy ``` [Try it online!](https://tio.run/##RY0xC8IwFIR3f8Uj0wvESZw6SUQcFLqLQ9o@mkB4SZO20F8fUx287Y777nprUh@ML@WSsxsZ78avNGDrl4wnBTfHAwogiKmDSBYsBWAYhAK99Z60DREnBU/HFXgQj7PFSSo4y10KrGwObXI8ozZ5xpdVcA1L5@vHj/k@1VSHpZbqlDBiB/9@q16@pWxKiSlEw1SOq/8A "Charcoal – Try It Online") Link is to verbose version of code. Takes input in lower case and outputs carbon and hydrogen atoms on separate lines. Explanation: ``` …θ⁻Lθ⁵ ``` Remove the last 5 characters of the input. ``` ⌕”↶↓>AkQN!{a⁶⟧”... ``` Search for the resulting prefix within the compressed string `e prb peh heo n d`. Note that there's a space before the `e`, so that the the prefixes are found at positions `-1` for me(th?ne), `1` for e(th?ne), `3` for pr(op?ne) etc. ``` ≔⊘⁺³...η ``` Add 3 to the position, then halve and store the resulting number of carbon atoms. ``` I⟦η ``` Output the carbon atoms... ``` ⊗⁻⁺η№θa№θy ``` ... and adjust for whether there is an `a` or `y` in the input, before doubling to give the number of hydrogen atoms. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 65 bytes ``` x=>(l=" mepbPhHond".IndexOf(x[0]),~-l+x[x.Count-3]%7/3<<1);int l; ``` [Try it online!](https://tio.run/##bY1BC4IwGIbv/YoxCDZSKzx0cHoJwkCoQ9BBPNj81IFu4iasS399GR065OU9PA88L9c@18KdJslZJrRhvC3HxENESOOheWjSxM7GCelijHoYHtc2VbLCwVlWYC81sfmuoN7L7zY2t8FRTdL4YbE@bEPG9jSaE6iL3K@HaqLNKGSDBI2Thojgpj7PhNJodR@FgUxIIDXBPZi2lID/xDCqYVGkMJjnkqiAw5e7Nw "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 32 30 bytes Thanks to [this user](https://codegolf.stackexchange.com/users/89930/79037662) for pointing out that I forgot to account for -ane, -ene, -yne ``` .0="mepbPhHond"?).@-3=7%3/(+2* ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/X8/AVik3tSApIMMjPy9FyV5Tz0HX2NZc1VhfQ9tI6/9/j9SCksq8VAA "GolfScript – Try It Online\"") This uses the same concept as in [this answer](https://codegolf.stackexchange.com/a/196677/80383) Explanation: ``` .0= Make a copy of input and select first letter "mepbPhHond"?) Find index of letter and increase by one for number of carbons .@ Duplicate for number of hydrogens and bring input to top of stack -3= Get the a, e, or y in ane, ene, yne 7%3/ Ascii value mod 7 integer divide 3 (+ Decrement and add to number of carbons 2* Double ``` Uses `mepbPhHond` capitalization. Example Execution: Input: propene ``` .0= Stack: 'propene' 'p' "mepbPhHond"?) Stack: 'propene' 3 .@ Stack: 3 3 'propene' -3= Stack: 3 3 'e' 7%3/ Stack: 3 3 1 (+ Stack: 3 3 2* Stack: 3 6 ``` ]
[Question] [ *Inspired by [this video by Matt Parker](https://www.youtube.com/watch?v=Mf2H9WZSIyw)* The distances between the letter keys of a QWERTY keyboard are somewhat standardised. The keys are square and both the horizontal and vertical spacing are 19.05mm (so if there were no gaps between the keys, their side lengths would be 19.05mm), and the three rows of keys are offset by ¼ and ½ a key size. Here is a diagram: [![Diagram of a QWERTY keyboard with the non-letter keys blurred and the distances between the letter keys annotated](https://i.stack.imgur.com/dRPT5.png)](https://i.stack.imgur.com/dRPT5.png) Your task is simple: given two letters, output the Euclidean distance between their centres (or between any two equivalent relative positions, for that matter) on a QWERTY keyboard as described above. The rows of the QWERTY keyboard in a more easily copyable format are: ``` QWERTYUIOP ASDFGHJKL ZXCVBNM ``` `Q`, `A`, and `Z` are aligned to the left with only the ¼ and ½ offsets described above; the keys at the rightmost end (`P`, `L`, and `M`) do not line up as well. Of course, given the same letter twice, your output should be 0. ## Rules * You may accept input in uppercase or lowercase, and as characters, strings, or ASCII codepoints, but this must be consistent + You may assume the input will always be valid; behaviour for non-Latin-letters is undefined * Your output must be in millimeters, and be accurate to within 0.1mm of the actual value * You may use [any reasonable 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 ## Test cases A full list can be found [here](https://gist.github.com/pxeger/ae20549834c04f1e40a4fa4ba91a0079) (original list calculated by Matt Parker, published [here](http://pi-ratebay.com/files/all_keyboard_distances.txt)) ``` In Out A B 87.82 B Q 98.18 G C 34.34 H J 19.05 L J 38.10 P X 143.27 Y Y 0 4 K [behaviour undefined] ``` **Note**: of course *your* keyboard has different measurements. Of course *your* keyboard uses AZERTY, or Dvorak, or something else. Of course *your* keyboard is 3-dimensional with keys that aren't completely flat, so the distances vary a little. Of course *your* keyboard has wobbly keys that mean the distances aren't even constants. Of course *you* live in a universe with Heisenberg's Uncertainty Principle in which you cannot truly know that the keys are that far apart. **This is obviously an idealised model of a keyboard; please don't argue about these things in the comments!** Image above modified from [work by Denelson83 on English Wikipedia](https://en.wikipedia.org/wiki/QWERTY#/media/File:KB_United_States.svg), used under [CC-BY-SA 3.0](http://creativecommons.org/licenses/by-sa/3.0/). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~25 24 23~~ 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to [Nick Kennedy](https://codegolf.stackexchange.com/users/42248/nick-kennedy)! (use of `)` to avoid repeated mapping) -2 thanks to [emanresu A](https://codegolf.stackexchange.com/users/100664/emanresu-a)! (Accuracy is only required to be within \$0.1\$mm of the true value) ``` ØQœi×4:3+ɗ\)ạ/×4.76ÆḊ ``` A monadic Link that accepts a list of two upper-case characters and yields a floating-point number. **[Try it online!](https://tio.run/##y0rNyan8///wjMCjkzMPTzexMtY@OT1G8@GuhfpAnp652eG2hzu6/v//7@gEAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///wjMCjkzMPTzexMtY@OT1G8@GuhfpAnp652eG2hzu6/j/cvUXncLvKo6Y13kAc@f@/oxOXUyCXuzOXhxeXjxdXQARXZCQA "Jelly – Try It Online"). ### How? Finds horizontal and vertical distances measured in quarter-key lengths of \$\frac{19.05}{4} = 4.7625\$ then takes the norm of the vector (i.e. uses Pythagoras). Since \$4.76\$ is good enough\* for requirements, that is used as the quarter-key length. ``` ØQœi×4:3+ɗ\)ạ/×4.76ÆḊ - Link: characters, [A, B] ) - for each (c in [A, B]): ØQ - Qwerty keyboard -> ["Q..P","A..L","Z..M"] œi - first multi-dimensional index of c in Qwerty keyboard ×4 - multiply by four -> [row(c)×4, column(c)×4] \ - cumulative reduce by: ɗ - last three links as a dyad: 3 - three : - (row(c)×4) integer divide (3) i.e. 4->1; 8->2; 12->4 + - add (column(c)×4) -> [row(c)×4, column(c)×4+(row(c)×4:3)] (i.e. quarter steps down and right from a point a quarter left of the top-left of Q required to reach the bottom right of each of [A, B]) / - reduce by: ạ - absolute difference -> [vertical, horizontal] quarter steps ×4.76 - multiply by 4.7625 -> [vertical, horizontal] distances ÆḊ - vector norm -> distance between keys ``` \* [Here](https://tio.run/##y0rNyan8///wjMCjkzMPTzexMtY@OT1G8@GuhfpAnp65mZHp4baHO7q4cKsAywNNcHy4c7rRoa2H24FShyfa6Blq/v8PAA "Jelly – Try It Online") is a suite showing all values are within \$0.1\$mm of the actual values - checking that all possible pairs using a quarter-key length of \$4.76\$ are within \$0.1\$ of those calculated using a quarter-key length of \$4.7625\$. (All results are actually also within \$0.1\$mm of Matt Parker's \$2\$ decimal place values - see [this](https://tio.run/##PZm7rutaFYb7/RQuaBCSiVeykhVEcxInseNLfIsvES0F6LwALQVHoqU4tLSICoF0gI4tCh5j8yKb/x//8GyWZuzpOcf4xnXO9etffvvtb75@/fzH9j9/@NXn73c/2/7kv9//4sdf/vmnn@JXfNh//t2XH37/9csPf/3336@fv8PzL//48/ijn8fJpy//@tvn7/732798/fpN9E20@fRNdIo@DvHHG0bn6D2J344YpdH2I0749sLRjqNr9H6Ik3eMbtFhH7/xWRYd3@M3Psuj5O0YH/nxPUqSXbzl@yJKttt4ywlllLy/aaUKc/HZB4Z1lGz28Y6fPaJk9xF/7DFsomR/iA8HDNsoOcb7HUZd9P4eHzjq@WzDRYfosI2PW4ye2DSJE645RvtjvOXEKXrbxh8JRnO03enZEh0hBpd@RW8JxTwBhBCcAIO/z67@CSCE5AQQe5D9wOjqa50AYl0hC6OcmKDxCRzWeUVYpXTZToCw7lG7OicgOLzFBz5roo9jvONubXT8oF4nAtjE@y1GfVhliHZ4xpWf0W5HFCfov643RR@b@LjHaHbjnaC/DHqC/jLjGfpLvjP0l1RnMODf1PU6Q3/tdIb@67Oba3iG/usKuUt@hv6S8gz9xfdML5C9zwCwbl@7cGf6wOYQbzizMSfZJBi2jv4MBBL@DATr1oMrfgYC4TsHBGcgELQzEKzPFjfRGQikbgoE6@jkqqRAIEVTYODfi/tiCgRaKyUC/y5zLVIgkIulQCAdUyBQpKREoPBIgUBcUiAQq5QI5MipIbCYSoFgt4@PCUad@3QawiAFAmFJicACIgUCAUqBYLsh8hQIVoUWD6aUCGzeRQiwygUIBPwCBLL6BQik/AUYOOfqq16AQLJdgGD9Lnd1L0DwsY2TA0ZIBpuEol/I4G0Tv3Nm5f59AQN568UYGKILGSiDXMBAqC9gIM0vYCAaFzGwt0@HfgEDGf8CBusXc9BycYNdwEAudGUk2LMrI8G4XIMbXMVgw7cX1/4KDnxzC28yl@MKBrLFFQzWVQuX7QoEInQFAdn@ykAw17uCgFzoSgDyh2uIg6sA7PlJH7YbHMUVAGTcKwCsok9upGtIhdeQCq4AoI1vACABbwCgb29Mh/bFLdSFG9OBrXcLsXADBL7Jwu/c5bgxFfp3haO4AcC6UxV2r8NOD4d3AwChuEF/udKNecDw36D/ut7gTG7QX3rdgv436C92N6ZC321xYjfoLxNk0F9myYL@WaiLGcuB7ZaFcpAxEEy3LDhBBgb8nbscGUuivynC7DKsVbnWGfRf93w4uwz6i0TGWqgAygBA@DMAEMaMEWBQMgCQYlnIAhlrgcHLAGBVdnFkGQAoE@UA4EknZya0PJmDgJJ6DgKyRg4CIpWDgCTMQUBS5woD6J6DAv/eXaScacA2zUFAAucqhja79lDMmQSMWQ4CYpaTgLJBDgLSO2ceVITkQCCmOfsB/3r0qpAzCSit5CwGKjS5osBWf60l504KmnoPieAOCgJ3BwVtfgcFYb2H/ugeasI9xMIdFKT/HST4pghvyjC7cuvfgx/cQUFk7qAgtndSUPa8g4Lc8A4KMsedBdF84y4Ie34yugvfCUFOdAcEGf1OBmaJOxmoQBdkINhFqIkFPcG@KegJtmHBuqglC7qCgSnoCoajCBmxYJNo8hQhIAqA4Jsy/F4hFCEZFIAgeIVcYce3dAX4JCXp3AaFucJOXw9OpmA62EijtTMsSEEIC3MF13hxcoW7AlrUkhjUuJasi/Z9CQz@UcmioD1LgtCqJUCIThm65TJ0CCUzw0Zfr5mxDB5RAgZ/r1mhDGWhVEzs@axxJCVBvH/EWw671RAlSch4JUgIT8ke0fQrQUJmLElCHEuSWJVenF5JEojIZPepstRg76vQJ1YgIfUqgNCaFVOD1fQKGESsoj@YEhX9Yadna4KsmB7M6hUwrKMyzKsi/l775AoYlCQqBoWlqMr8AXImGHbeSFSkIDNVwR8qUrCepmJUmEEqSw3v8fGA4eyWq9ggWPtQEYJsXBOClqwBQQLVrBC2UA0IUrhmZjApamYGU70ODXMdDgw1IEiZOkCoWSV8Xhm@rcJudcQ5D1e9ZoWwDFcTgtSoQ2aoAUF2qZkeTaE6lMiaFcIsWYOBrFYDgWxaMyKMVQ0EwvIgAR3UHiCgnR8WEJZQHxYQlo8fDAhxezAgrHA8GBBWLh4MCEtpD2WGDVe/u2QPeoK5@EPZYc95lcN66NCw5RePiLObsEK7BuwDEFah@7WsPXhoNO0eopBwNHqBe1g8bLXwvNaDR@gVHxYP2/jt8KkhCB1TGx6i7fuGIPRRQxDasyEIrdqwXxKeBiTEpAEJMWkUE5CpYddodBo1DTs@K51Jw6bpoAVrN0ITSmYDGvwNEock3vFBt1qiIQrZrwEK8WnYM5qCDc9OsmRDFiLZkMWq9uL8GrLYJ/Eh@dSShZmoBQq5Uct6aS7YgoQST6v7BKjXMjX425snqJb1UgmspUeIWMtiobTa2oWCZavWLhQs77UMDcV@yyShCGhJQ9K3dA6BaMGEDzpXt2UDbam4DX7R2mWCwWrpGBbFbThCtOwgLYxaXiYYv5ZHCAuUjkcIM1vHqmnzOl0oQJKOB2ozYKfTJNbr1EHv@cXNhelAQsQ6HiNMrI4HaiPW8UBtxDo7UCdasHJRO54mfeLDBezsHGE6dUAg5Ttg4O8@SDcEmZ5hzhg0m9x2HQgoDLvQPXU8Q5hD9vKFDUdrwezDGaIPh6geBMSiDz10H9qGniFhevd0BUVMDwTSp6cnSJ@eDOQqPT1B2bnncdLSXk9HUBz2pCDf73mc3GjmeqvQgwT/Dm7BHhQUoH1ooHr5wZ5v1@N0z5Cw8O3DpdLAk5Q9G0BBBAcep3d6lvqeQ4iIgRcrxmPQSQJ7DCyWJuWgiyWQGQBBvjEAggw9gIE8YuBx0p/V7n8DT1PGcuBpygAO0H99th6nB56mTPMBDPjmGWQbg7xTkGN2iw86SNgKL09GT2uhzWpPAjC1n@wW/HXqeJ4AIEGeLJS2/VMt9I7PMofyDDXiqe5xz3mF43kCgKA8WSMM95MdpK/ycEWe6hgSrtKuHvQM6eDJNtos/gwXCk9Q4N/RtX2yUBrDJztoS/vPQOBpHbTlzxEI5P5jaBVG1gcfpR4SIwjIUGO4WxvD3eIY@qWRqcDojawN5o4jXcD3KN3hR9WGhHvUrsQIAhJ1ZAysAraeMkYeKA3aSB/wpddrpVHZYMsFx4i/19P0qOsU22BxI4/KBNh@AgAZb2KBtJ0m9kqm7EQAZrwp5MIJAGTGCQC0xwQA8u3JMoGZbKIPKPFNTAWqD5OlAqsPE1OBKsEECipJE1OBUsVEDCoPky6ZbfvO1Zl0uwYfm8KhcmI6MMNPPEm4cFPE2bPjm0J1nHS5iPVn3qyZBWcdqbHWHPxgDnesc7hsn8Md8xz65pm3a0c9y1cLzrxeM6PPdr1mqW@26zVr1Gder5nIM9sEE2y2fGgtymz50Mr6zKpgdpnpC2bJmddrLtrgHjADghxpDq3jzNslU38GCP5e3FFnRoOpufBmxSJr0eEBai7qm7d8m3roLwwGQ7SoKti8m/vRohP1nvPWRmlhy2h@tICBvGfhRbsZaGEwmF4L7xZMykW9s@3ROJWFF@1GaglOsPByxZLUEirjEm4WFlbGnd5OYZXZNV/AgH9fTuvFWDCWL3bNNvsV/tHwCsngxZs1W/UVzg0vxsJRbzO398v@42JWfFksmOlfFgtm@he9QCe3l8XCTpvXrubL/uFitn/ZP1yskXvxptkgvZQUt5zZB9EHV@9FDPLBVzhGvdQh7Ph6vW1/gcNK4BVt/g8 "Jelly – Try It Online")) [Answer] # [R](https://www.r-project.org/), ~~145~~ ~~142~~ ~~138~~ ~~125~~ ~~124~~ ~~102~~ 100 bytes *Edit: -4 bytes thanks to ovs* ``` function(x,j=2-sapply(x,regexpr,'lo,kimjunhybgtvfrcdexswzaq'))dist(cbind(y<-j%%3,j%/%3+2^y/4))*19.05 ``` [Try it online!](https://tio.run/##bc3BDoIgAMbxe4/BxoTCrKxDW75KmyAqZIiICb284a1Gx@93@P5mGWZurK/EaIulnhSzolfIEVmc0rHUuvNhGN5wpw1Jup48xFNOqvW0sa/asIq7cX6XQ4Lx@oEYFapC/pZKCHMiYQbz3enuszPG2@N1f7h8BRFDoAQEUIDx5pdp4CHmJjCLuQ0sY@7@sw7sYvaB/crLBw "R – Try It Online") **Ungolfed** ``` qwertydist=function(x){ # x = input = vector of two characters k='lo,kimjunhybgtvfrcdexswzaq' # k = 26-character vector of keys of each keyboard column exept last (in reverse). j=2-sapply(x,regexpr,k) # j = indices of x in reversed k, & offset by a fixed value so that the missing 'p' ends-up in the right place y<-j%%3 # y = row of each key z=j%/%3+2^y/4 # z = col of each key, adjusted +.25 for row 1 & +.5 for row 2 d=dist(cbind(y,z))*19.05 # d = euclidean distance between keys, in millimetres } ``` [Answer] # JavaScript (ES6), ~~114~~ 113 bytes *Saved 1 byte thanks to @Shaggy* Expects `(a)(b)`. ``` a=>b=>Math.hypot((g=c=>(x="WERTYUIOPASDFGHJKLZXCVBNM".search(c))-[y=x>8,39,73][y+=x>17]/4)(a)-g(b,Y=y),y-Y)*19.05 ``` [Try it online!](https://tio.run/##Vc/JboMwEAbgO09h@WS3xqwVoMpIIc3apE33UMTBEJZUURwBquDpKRRRqceZT/@M/i/@zcu4OF4q@SwOSZuyljM3Yu6WVznNm4uoEMpYzFxUM/gxe37131aPu8nL3XyxXN9vPvfTd@9hC2mZ8CLOUYyxHDSsdm1iOMQywqC57ibNChUTI47lDEXEZw0mjezjK82h6k17G0gABABOIAHQgyAkQFGAbVFbH8Dr4WkEx6aaPcCih@kIhkkNc4BlD@sRft8MsPkHRndKHWDXw/4vYRpUtwbxe/FHUaVQoqkoZryriwJOQBRiwFwQi3MpTgk9iQz1WwLSrjCKMK3E/FgnB6RjjNsf "JavaScript (Node.js) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 39 bytes ``` ƛ£k•ƛ¥v=;:vaThD£ɾ0p∑4/∇iTh+¥";÷∆d19.05* ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C6%9B%C2%A3k%E2%80%A2%C6%9B%C2%A5v%3D%3B%3AvaThD%C2%A3%C9%BE0p%E2%88%914%2F%E2%88%87iTh%2B%C2%A5%22%3B%C3%B7%E2%88%86d19.05*&inputs=%27qb%27&header=&footer=) -2 thanks to pxeger. +2 because of a bug Ugh, what a mess. Vyxal has several bugs right now, so the find command isn't working, among other things. Takes a two-char string of lowercase letters. ``` ƛ ; # Map... £ # Store to register k•ƛ ; # Map rows of qwerty keyboard to... ¥v= # Is equal to register (current value) : # Duplicate this va # Foreach, check if any are true Th # Find the only truthy index - this is the correct keyboard row D£ # Duplicate and store a copy to register ɾ0p∑4/ # Horizontal offset of this row - nth triangle number/4 (There's probably a better way to do this, `0p` because Vyxal) ∇ # Shift, putting a copy of the row number above the list of indices on the stack i # Index this into the list of indices Th+ # Find the index of the key and add to previously calculated horizontal offset ¥" # Pair with vertical offset ÷ # Iterate onto the stack ∆d # Pythagoras' Theorem 19.05 # Multiply by 19.05 ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~108~~ 97 bytes ``` lambda x,y:abs(p(x)-p(y))*4.76 p=lambda c:(a:='.LO,KIMJUNHYBGTVFRCDEXSWZAQ'.find(c))%3*4j+a--a//3 ``` [Try it online!](https://tio.run/##Lcq7DoIwAIXhnafoYtoilwGihoQBUEHEC17By1AgRIyWBhjg6bEknuHLGX7WNa@SajNW9bn56D/km2QEtFJnkKRGDLVYZqjDWNSV6URg5j9IDUQMEyrBTlqvNv5568W2e7osD858ER2vNyuESl7QDKUYjzRRf4@JLBNV1fq8rEANCgru0LKhBO2Q4zocz@cEA/uIE8fDC@HTEAAfqwraoByJNcb9Dw "Python 3.8 (pre-release) – Try It Online") `p` maps a character to a complex number corresponding to its key's position, at a scale where the key size is 4; the magnitude of the difference of `p` of the given characters, rescaled, gives the answer. `find` returning -1 when the substring is not found is used to handle P. -2 using the suggestion of a decimal multiplier from emanresu A, taken one step further – with the value 4.76, the maximum error is slightly over 0.09, just within the limit. -9 by transposing the keyboard and making some other changes with that. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes ``` ØQœi2*÷8Ʋ+¥\)ạ/ÆḊ×19.05 ``` [Try it online!](https://tio.run/##AVgAp/9qZWxsef//w5hRxZNpMirDtzjGsivCpVwp4bqhL8OG4biKw5cxOS4wNf874oCcIC0@IOKAnTvDhwrhu7TDh@KCrFn//0FCCkJRCkdDCkhKCkxKClBYCllZ "Jelly – Try It Online") A monadic link taking a list of two characters and returning a float. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~60~~ 56 bytes ``` I×¹⁹·⁰⁵₂ΣE²X↨EEθ⌕”&⌈‽↶ ›I✂TFsG�¦ιAo⊟↧”λ⎇ι﹪λ³⊘⊘÷⊗⊗⊕λ³±¹¦² ``` [Try it online!](https://tio.run/##NYzNbsIwEIRfxeK0lgwCKg6oN0AVHECo8AKLvSQuG5s4dvh5eZPQdqXRN5rRji4xaI@c8z5YF2GJTYSjraiByXw0nilxqBMG@vY@wiFVsMUrTJXY@xsFWGBD76RXrcSXdQYGNT5vzZ2MDuc2FqdH6dJPZS8Xz3wdKMFSKnGk4DA8wCqx9SaxB1bioyvWyC0Z@MPGxZVtrSFY@XTiLvnnxulAFbnY@W5R9t/yzR0VGAkmvZ/K3/vMWRd52PIL "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a string of two lower case letters. Explanation: The compressed string contains the letters in a staggered arrangement. The vertical offset is simply the index modulo `3`, while the horizontal offset is computed by dividing the index by `3` and rounding to the nearest multiple of `0.25`. Pythagoras is then used to compute the final result. ``` E² Loop twice (horizontally/vertically) Eθ Loop over input ⌕...λ Find char indices in compressed string E ⎇ι Extract either ﹪λ³ Vertical offset ⊘⊘÷⊗⊗⊕λ³ Horizontal offset X↨ ±¹¦² Take the squared difference Σ Take the sum ₂ Take the square root ×¹⁹·⁰⁵ Multiply by literal 19.05 I Cast to string for implicit print ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~33~~ ~~28~~ 27 bytes -1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)! Builtins for multi-dimensional index and euclidean distance would be helpful. Takes input in lowercase. ``` vžVyδkZDŠkDŠÍo+‚}-nOt19.05* ``` [Try it online!](https://tio.run/##yy9OTMpM/V9zbuv/sqP7wirPbcmOcjm6IBuID/fmaz9qmFWrm@dfYmipZ2Cq9f9/YhJXUiFXejJXRhZXThZXQQVXZSUA "05AB1E – Try It Online") **Commented:** ``` v } # iterate over each character y in the input žV # push ["qwertyuiop", "asdfghjkl", "zxcvbnm"] yδk # for each row, find the index of the current char in it (-1 if not found) ZD # get the maximum one (the only one not equal to -1) twice (call this x) Š # rotate top 3 values on the stack (x [indices] x) k # find the index of x in the indices (call this y) DŠ # duplicate y and rotate top 3 values (y x y) Ío # 2**(y-2) + # add to x (y x+2**(y-2)) ‚ # pair up both values [y, x+2**(y-2)] - # take the element-wise differences nOt # Euclidean norm (square, sum, square root) 19.05* # multiply by constant 19.05 (*1905/100 would be the same length with integer compression) ``` [Answer] ## [Perl 5](https://www.perl.org/), 129 + 4 (`-apl` options) = 133 bytes ``` ($x,$y,$u,$v)=map{$i=index+QWERTYUIOPASDFGHJKL_ZXCVBNM,$_;$==$i/10;$i%10+(0,1,3)[$=]/4,$=}@F;$_=19.05*sqrt(($x-$u)**2+($y-$v)**2) ``` [Try it online!](https://tio.run/##HY7basJAFEXf5yvOwynkMokzyYiRMFBjq9ZbtVdTkZBiSgdsEqMRpfTXmw59W7Bgr11m1a7dNAaeKV4o1hRPpvxKy29UUuXb7GwvX28fnuLnu/tF7/FmMByNJ9PkbdV/ieYzikmIUqJqcRaiuuLMNhjl1DfXKDctQVH@XA9CTCTvuqxtHfbV0dApB2vTsjzbwIujexrNpulBBEHHDTwSwRK6gcsDMoQ@@ML1BRnBGP5HyFSTry0jC1gBF77rdUgMMTAiYALr9@wzPamirqDW/z9Unm03v0V5VEV@aJy03P0B "Perl 5 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 88 bytes ``` ->a{p,q=a.map{|i|b=:_QAZWSXEDCRFVTGBYHNUJMIK_OL_P=~/#{i}/ b*4/3+-b%3*4i} (p-q).abs*4.76} ``` [Try it online!](https://tio.run/##PZnbjttGEobv5ykIZwPYjk2LI40OAWYDSaRESjyfKcMw7F0YcJJFHDu5WCTeV/fWX3@xbwYtstld9dWxez7/@f6/3z48fnv5z3d/fXrx@@M7/z/vPv3198e/3z/@@Lba34ZmjMJjferb82GK8@6SJde3Rfq2fPzfq@/@@vj11d3756tXyx9evv9@@Xz18evd008vf3/mv3v/5fnK36y/fvvy@GTv7b3F3d47eNuNv72X0dF7CPz7nYxCb7n1A7yNMFphdPIeNn7wIKOzt1n793gWe7sH/x7PEi@43/k7fHzxgmDlL/H@6gXLpb/EhNQLHu65UiZz5bOtDHMvWKz9FT4rvGC19bdrGZZesN74m40MKy/Y@euVjGrv4cHfYNTg2QKLtt5m6e@WMupk08APsGbvrXf@EhMH737pbwMZjd5yxWeTtxMxsPTNuw8g5kFAEMFBYOD30dQ/CAgiOQiItaDbyuhkax0ExLxC7EYJMInGB@Ewz7u6VVKT7SAQ5j1yU@cgCDb3/gbPSm@781fYrfJ2W@h1AICFv17KqHGrtN5KnmHlzlutgOIg@s/rDd524e/WMhrNeAfRnwY9iP4041H0p3xH0Z9SHYUB/oam11H0505H0X9@djYNj6L/vEJikh9Ff0p5FP3J9wgvoL2PAmDePjfhjvCBxcZfYGapTrIIZFgZ@qMgoPBHQTBv3ZriR0FAfEeH4CgICO0oCOZnk5noKAiobigI5tHBVAkFARUNBQP@RuaLoSDgWiEQ2HexaREKArpYKAioYygIGCkhEDA8QkFALqEgIKsQCOjIoSLQmAoFwWrt7wIZ1ebToQuDUBAQSwgEGhChICCgUBAsF0AeCoJZocmCKQQCnRcRgawSCQICjwQBrR4JAiofCQbMOdmqkSCgbJEgmL9LTN1IEGyXfrCRkSSDRQDRIzC4X/gPmJmZf0fCgN4aKQNFFIEBM0gkDIg6EgbUPBIGpBGRgb7tDHokDGj8SBjMX4xOy8kMFgkDutAJkaDPTogE5XJybnAigwXeRqb9STjgzdm9iU2OkzCgLU7CYF71arKdBAEJnYQAbX9CIKjrnYQAXegEAPSHk4uDEwGs8UnjtmsNxUkA0LgnATCLPpiRTi4VnlwqOAkAbnwWABTwLAD47RnpUL84u7pwRjrQ9c4uFs4CAW9i9zsxOc5Ihfbd1VCcBcC8U@Z2z91OhcE7CwCiOIv@dKUz8oDiP4v@83qtMTmL/tTr7PQ/i/5kd0YqtN0mI3YW/WmCWPSnWWKnf@zqYoxyoLvFrhzECATVLXZOEAsD/E5Mjhgl0d5c3ezUrZWZ1rHoP@9ZGLtY9CeJGLWQARQLAOKPBQAxxogAhRILACoWuywQoxYovFgAzMpOhiwWAMxEiQCwpJMgE2qeTIQAk3oiBGiNRAiQVCIEKGEiBCh1wjAQ3ROhgL8XEylBGtBNEyFAgRMWQ52dWygmSALKLBECZJaAALNBIgSod4I8yAhJBAGZJugH7OveqkKCJMC0kqAYsNAkjAJd/TaXnAsocOrFJYKLUCC4i1Dg5hehQKwX1x9dXE24uFi4CAXqfxESeHN1b1I3OzPrX5wfXIQCyVyEAtleQIHZ8yIU6IYXoUBzXFAQ1TcuhLDGJ7258AUQ6EQXgUCjX8BALXEBAxboKxgQ9tXVxCs8Qb@5whN0wyvqIpe8whUUzBWuoDiuLiNe0SSqPFcXEFcBgTep@z1DuLpkcBUIhHelK6zwFq4gPglJarPBVV1hxa9bI3NFOlhQo7kzvIICEV7VFUzjychdzRWkRU2BgY1rirqo36eCwT5KURS4ZwoQXDUVEKSTum45dR1Cisyw4NdzZkydR6QCA7/nrJC6spAyJtZ4VhqSFCAetv4Sw3o2RAoSNF4qJIgnRY@o@qVCgmZMQYIcU5CYlZ6MXgoSEpHB6i7T1KDvM9cnZkKC6mUCgmtmSA1a0zPBQGIZ/EGVyOAPKz6bE2SG9KBWzwTDPErdvMzD77lPzgQDk0SGoNAUlak/iJyBDGtrJDJQoJky5w8ZKGhPkyEq1CCZpoYHf7eR4WiWy9AgaPuQAQJtnAMCl8wFAgXKUSF0oVwgUOEcmUGlyJEZVPXcNcy5OzDkAoHK5A5Cjiph81L3beZ2yz3MKUz1HBVCM1wOCFQjd5khFwi0S470qArlrkTmqBBqyVwY0Gq5IKBNc0SEssoFAbEUIMCDWiEEuHOhAaEJtdCA0HxcICDIrUBAaOEoEBBaLgoEhKa0gplhgdUvJlkBT1AXL5gd1piXGayCh4Ylvig8zC7dCtUcsIVAmIVu5rJW4NCo2hWkEGDUW4ErNB6WXHic60HhesVC42Hp32/uSoDgMbXEIVq/LwGCH5UAwT1LgOCqJfol4imFBJmUQoJMSsaEyFSia1Q6JZuGFZ6lxqRE07ThgrkZoXQlsxQa@C0kNoG/woN6tkQJFLRfKSjIp0TPqAqWODvRkiVYkGQJFrPak/ErwWId@JvgrgILNVElKOhGFeqlumAlJJh4Kt4niHoVUoO9PVuCqlAvmcAqeASJVSgWTKuVXihotqr0QkHzXoXQYOxXSBKMgAo0KH0F5yCISpjgQW3qVmigNRVXzi8qvUxQWBUcQ6O4ckeICh2khlGFywTlV@EIoYFS4wihZqtRNXVezQsFkaTGgVoNWPM0KevV7KDX@OJswtRCgsRqHCNUrBoHaiVW40CtxGo9UAdcMDNRa5wmbWJhAtZ6jlCdakFA5WvBgN@Nk651MnVuTu80G8x2tRBgGNaue6pxhlCHbOgLC4zmgtm4M0TjDlGNECCLxvXQjWsbGoSE6t3AFRgxjSCgPg08gfo0YEBXaeAJzM4NjpOa9ho4AuOwAQX6foPj5IIz51uFRkjgb2sWbIQCA7RxDVRDP1jj7XycbhASGr6Nu1RqcZLSZ61QIMEWx@kVn4W2Z@siosXFivJoeZKQPVoUS5Wy5cWSkGkFAn2jFQg0dCsM6BEtjpP2LDf/a3GaUpYtTlMKsBX952fzcbrFaUo1b4UB3nROtt7JOzg5RrN4y4OErnCzZNRpC61W6wBA1e7QLdjr0PB0AoCCdCiUun3HFnqFZ7FB6VyN6Ng9rjHvang6AUAoHWqE4u7QQdoqhSnSsWMIsEo1e1Dn0kGHNlot3rkLhU4o4G9v2nYolMqwQwetab9zBDrtoDV/9oKA7t@7VqFHfbBRaCHRCwEaqnd3a727W@xdv9QjFSi9HrVB3bGHC9geqTl8z9oQYI/clOiFAEXtEQOzgJWljB4HSoXWwwds6flaqWc2WGLB3sPv@TTd8zpFN5jMyD0zgWw/CAAab0CB1J0G9Eqq7AAAarzB5cJBANCMgwDgHoMAoG8PmgnUZAN8gIlvQCpgfRg0FWh9GJAKWAkGocCSNCAVMFUMwMDyMPCSWbevTZ2Bt2viY4M7VA5IB2r4AScJE27wMHs0fIOrjgMvF2X9ETdrasGRR2pZa3R@MLo71tFdto/ujnl0ffOI27UdnyWzBUdcr6nRR71e09Q36vWaNuojrtdU5BFtggo2aj7UFmXUfKhlfURVULuM8AW15IjrNROtNQ8YBQIdaXSt44jbJVV/FBD4PZmjjogGVXPCzYpG1sTDg6g5sW9e4m1ooT8hGBTRxKqg887mRxNP1GvMmxulCS2j@tEkDOg9Ey7a1UATgkH1mnC3oFJO7J11j9KoTLhoV1KTc4IJlyuapCZXGSd3szChMq74dnCrjKb5JAzw92a0bogFZXlD16yzb@4fDTeXDG64WdNVb@7ccEMs7Pg2Nnvf9D8uasWbxoKa/qaxoKa/wQt4crtpLKy4eW5q3vQfLmr7m/7DRRu5G26aFdKNSXGJmY0TvTX1bsBAH7y5Y9SNHcIKr@fb9ptwmAncvMUT/8unXz/@8fQfr57d/fL4Mrh7@vnx@U973//p9sz/9Pm3f//5rz@efn7Gf3f9/Pcn7/XPL558v/3w5PsPr39@Y8OnGL/88vqXHx6DN69Xvv8yeOP/8dvbD8/efL37ro0aKXhdW3ZSUYs620splg6jSNNiaH68@@716zRq20g6on1Sv3nhHffpsUv3bRR6/T7tohdeVNeF9GxFVu5reTokbeztD0UfeeG@3b/xvbzLojo5cr70O3VkO2ER2axp6yQ/S@Nx8tIoP8vnW0zw6mgf7g9JmrST/@3/ "Ruby – Try It Online") Used a symbol instead of a string as suggested by Dingus. Also improved formula for converting `b` to a complex number (saved several bytes, although it requires another dummy character at the start of the string.) # [Ruby](https://www.ruby-lang.org/), 95 bytes ``` ->a{p,q=a.map{|i|b='QAZWSXEDCRFVTGBYHNUJMIK<OL>P'.index i b/3*4+b%3*3/2+b%3*4i} (p-q).abs*4.76} ``` [Try it online!](https://tio.run/##PZlrr9vGEYa/n19BOA1iOzYjHunoUvQkkERKpMT7nTKMwm5qwE7bOHYCtEjy29155x3ul@MVudydeea660@/vf3fl3ePX15@/@b3jy9@eXzj//vNx9//eP/H28dvqv1taMYoPNanvj0fpjjvLlly/VuRfl9@47//z4///K/3/u7td8vnq2/ffr18vvzuXv9dvf/z7unHl78889@8/fx85W/Wf375/Phk7@29xd3eO3jbjb@9l9HRewj8@52MQm@59QO8jTBaYXTyHjZ@8CCjs7dZ@/d4Fnu7B/8ezxIvuN/5O3x88YJg5S/x/uoFy6W/xITUCx7uuVImc@WzrQxzL1is/RU@K7xgtfW3axmWXrDe@JuNDCsv2PnrlYxq7@HB32DU4NkCi7beZunvljLqZNPAD7Bm7613/hITB@9@6W8DGY3ecsVnk7cTMbD0zbsPIOZBQBDBQWDg99HUPwgIIjkIiLWg28roZGsdBMS8QuxGCTCJxgfhMM@7ulVSk@0gEOY9clPnIAg29/4Gz0pvu/NX2K3ydlvodQCAhb9eyqhxq7TeSp5h5c5brYDiIPrP6w3eduHv1jIazXgH0Z8GPYj@NONR9Kd8R9GfUh2FAf6GptdR9OdOR9F/fnY2DY@i/7xCYpIfRX9KeRT9yfcIL6C9jwJg3j434Y7wgcXGX2BmqU6yCGRYGfqjIKDwR0Ewb92a4kdBQHxHh@AoCAjtKAjmZ5OZ6CgIqG4oCObRwVQJBQEVDQUD/kbmi6Eg4FohENh3sWkRCgK6WCgIqGMoCBgpIRAwPEJBQC6hICCrEAjoyKEi0JgKBcFq7e8CGdXm06ELg1AQEEsIBBoQoSAgoFAQLBdAHgqCWaHJgikEAp0XEYGsEgkCAo8EAa0eCQIqHwkGzDnZqpEgoGyRIJi/S0zdSBBsl36wkZEkg0UA0SMwuF/4D5iZmX9HwoDeGikDRRSBATNIJAyIOhIG1DwSBqQRkYG@7Qx6JAxo/EgYzF@MTsvJDBYJA7rQCZGgz06IBOVycm5wIoMF3kam/Uk44M3ZvYlNjpMwoC1OwmBe9WqynQQBCZ2EAG1/QiCo652EAF3oBAD0h5OLgxMBrPFJ47ZrDcVJANC4JwEwiz6YkU4uFZ5cKjgJAG58FgAU8CwA@O0Z6VC/OLu6cEY60PXOLhbOAgFvYvc7MTnOSIX23dVQnAXAvFPmds/dToXBOwsAojiL/nSlM/KA4j@L/vN6rTE5i/7U6@z0P4v@ZHdGKrTdJiN2Fv1pglj0p1lip3/s6mKMcqC7xa4cxAgE1S12ThALA/xOTI4YJdHeXN3s1K2Vmdax6D/vWRi7WPQniRi1kAEUCwDijwUAMcaIAIUSCwAqFrssEKMWKLxYAMzKToYsFgDMRIkAsKSTIBNqnkyEAJN6IgRojUQIkFQiBChhIgQodcIwEN0ToYC/FxMpQRrQTRMhQIETFkOdnVsoJkgCyiwRAmSWgACzQSIEqHeCPMgISQQBmSboB@zr3qpCgiTAtJKgGLDQJIwCXf02l5wLKHDqxSWCi1AguItQ4OYXoUCsF9cfXVxNuLhYuAgF6n8REnhzdW9SNzsz61@cH1yEAslchALZXkCB2fMiFOiGF6FAc1xQENU3LoSwxie9ufAFEOhEF4FAo1/AQC1xAQMW6CsYEPbV1cQrPEG/ucITdMMr6iKXvMIVFMwVrqA4ri4jXtEkqjxXFxBXAYE3qfs9Q7i6ZHAVCIR3pSus8BauID4JSWqzwVVdYcWvWyNzRTpYUKO5M7yCAhFe1RVM48nIXc0VpEVNgYGNa4q6qN@ngsE@SlEUuGcKEFw1FRCkk7puOXUdQorMsODXc2ZMnUekAgO/56yQurKQMibWeFYakhQgHrb@EsN6NkQKEjReKiSIJ0WPqPqlQoJmTEGCHFOQmJWejF4KEhKRweou09Sg7zPXJ2ZCguplAoJrZkgNWtMzwUBiGfxBlcjgDys@mxNkhvSgVs8EwzxK3bzMw@@5T84EA5NEhqDQFJWpP4icgQxrayQyUKCZMucPGShoT5MhKtQgmaaGB3@3keFolsvQIGj7kAECbZwDApfMBQIFylEhdKFcIFDhHJlBpciRGVT13DXMuTsw5AKByuQOQo4qYfNS923mdss9zClM9RwVQjNcDghUI3eZIRcItEuO9KgK5a5E5qgQaslcGNBquSCgTXNEhLLKBQGxFCDAg1ohBLhzoQGhCbXQgNB8XCAgyK1AQGjhKBAQWi4KBISmtIKZYYHVLyZZAU9QFy@YHdaYlxmsgoeGJb4oPMwu3QrVHLCFQJiFbuayVuDQqNoVpBBg1FuBKzQellx4nOtB4XrFQuNh6d9v7kqA4DG1xCFavy8Bgh@VAME9S4DgqiX6JeIphQSZlEKCTErGhMhUomtUOiWbhhWepcakRNO04YK5GaF0JbMUGvgtJDaBv8KDerZECRS0XykoyKdEz6gKljg70ZIlWJBkCRaz2pPxK8FiHfib4K4CCzVRJSjoRhXqpbpgJSSYeCreJ4h6FVKDvT1bgqpQL5nAKngEiVUoFkyrlV4oaLaq9EJB816F0GDsV0gSjIAKNCh9BecgiEqY4EFt6lZooDUVV84vKr1MUFgVHEOjuHJHiAodpIZRhcsE5VfhCKGBUuMIoWarUTV1Xs0LBZGkxoFaDVjzNCnr1eyg1/jibMLUQoLEahwjVKwaB2olVuNArcRqPVAHXDAzUWucJm1iYQLWeo5QnWpBQOVrwYDfjZOudTJ1bk7vNBvMdrUQYBjWrnuqcYZQh2zoCwuM5oLZuDNE4w5RjRAgi8b10I1rGxqEhOrdwBUYMY0goD4NPIH6NGBAV2ngCczODY6TmvYaOALjsAEF@n6D4@SCM@dbhUZI4G9rFmyEAgO0cQ1UQz9Y4@18nG4QEhq@jbtUanGS0metUCDBFsfpFZ@FtmfrIqLFxYryaHmSkD1aFEuVsuXFkpBpBQJ9oxUINHQrDOgRLY6T9iw3/2txmlKWLU5TCrAV/edn83G6xWlKNW@FAd50TrbeyTs4OUazeMuDhK5ws2TUaQutVusAQNXu0C3Y69DwdAKAgnQolLp9xxZ6hWexQelcjejYPa4x72p4OgFAKB1qhOLu0EHaKoUp0rFjCLBKNXtQ59JBhzZaLd65C4VOKOBvb9p2KJTKsEMHrWm/cwQ67aA1f/aCgO7fu1ahR32wUWgh0QsBGqp3d2u9u1vsXb/UIxUovR61Qd2xhwvYHqk5fM/aEGCP3JTohQBF7REDs4CVpYweB0qF1sMHbOn5WqlnNlhiwd7D7/k03fM6RTeYzMg9M4FsPwgAGm9AgdSdBvRKquwAAGq8weXCQQDQjIMA4B6DAKBvD5oJ1GQDfICJb0AqYH0YNBVofRiQClgJBqHAkjQgFTBVDMDA8jDwklm3r02dgbdr4mODO1QOSAdq@AEnCRNu8DB7NHyDq44DLxdl/RE3a2rBkUdqWWt0fjC6O9bRXbaP7o55dH3ziNu1HZ8lswVHXK@p0Ue9XtPUN@r1mjbqI67XVOQRbYIKNmo@1BZl1HyoZX1EVVC7jPAFteSI6zUTrTUPGAUCHWl0reOI2yVVfxQQ@D2Zo46IBlVzws2KRtbEw4OoObFvXuJtaKE/IRgU0cSqoPPO5kcTT9RrzJsbpQkto/rRJAzoPRMu2tVAE4JB9Zpwt6BSTuyddY/SqEy4aFdSk3OCCZcrmqQmVxknd7MwoTKu@HZwq4ym@SQM8PdmtG6IBWV5Q9ess2/uPxpuLhnccLOmq97cueGGWNjxbWz2vun/uKgVbxoLavqbxoKa/gYv4MntprGw4ua5qXnT/3BR29/0P1y0kbvhplkh3ZgUl5jZONFbU@8GDPTBmztG3dghrPB6vm2/CYeZwM1bPPE/f/zX@1@f/uW7Z3c/Pb4M7p5@enz@w973f7g98z9@@vnH3/7x69NPz/i/Xh/@@Oi9@vDiydfbd0@@fvfqw2sbPsX45edXP337GLx@tfL9l8Fr/9ef//7u2es/775qo0YKXteWnVTUos72UoqlwyjStBiav9599epVGrVtJB3RPqlfv/CO@/TYpfs2Cr1@n3bRCy@q60J6tiIr97U8HZI29vaHoo@8cN/uX/te3mVRnRw5X/qdOrKdsIhs1rR1kp@l8Th5aZSf5fMtJnh1tA/3hyRN2sn/8n8 "Ruby – Try It Online") I used a `QAZ WSX`order because it splits into rows and columns by the application of `b/3 and b%3`, saving three bytes over the alternative `b/10` and `b%10`. `p` and `q` contain the coordinates as complex numbers, expressed as integer multiples of a quarter of a key. At the end we multiply by `4.76` which is in approximation of `19.05/4 = 4.7625`. The value `4.76*4 = 19.04` gives an error of `0.01mm` between two adjacent keys on the same row, giving a maximum error of `0.09mm` between `P` and `Q` which is within allowed limits. ]
[Question] [ # Introduction In Tennis, the server alternates serving on the left side or the right side of the court every point, starting on the right. It is possible to figure out which side to serve on for that point just based on the score; if there have been an even number of points you serve on the right, and after an odd number of points, on the left. Scoring in tennis works as follows: ``` Points | Corresponding Call | 0 | Love 1 | 15 2 | 30 3 | 40 ``` Once a player scores 4 points, they win the game. If the score is tied at 40-40, the call is "Deuce" rather than "40-40" or "40 all". At Deuce, the subsequent point is called as "Advantage [x]" or "Ad [x]" where x is the player who scored. If the opposite player scores next, the score returns to Deuce, but if the same player scores again, they win. # The Challenge Your task is to write a function that takes the score and returns a truthy or falsey value. The input may be a string containing the call or a list containing the scores. Love, Deuce, and Ad must be strings but the rest of calls may be any numerical type as well. Deuce may be represented by singleton list containing "Deuce" or a list with "Deuce" and another value of your choice. You may choose which side corresponds to truthy and falsey, but **you must specify which corresponds to which side in your answer**. The scores will be separated by a hyphen, except in the case of Deuce wherein it will be simply "Deuce". For advantage, the score will be "Ad-40" or "40-Ad". # Winning This is code golf, so the score is the number of bytes in your function and the answer with the lowest score wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. # Test Cases ``` Love-Love | True Love-15 | False Love-30 | True Love-40 | False 15-Love | False 15-15 | True 15-30 | False 15-40 | True 30-Love | True 30-15 | False 30-30 | True 30-40 | False 40-Love | False 40-15 | True 40-30 | False Deuce | True Ad-40 | False 40-Ad | False ``` These test cases are exhaustive, i.e. that list represents every possible input and its corresponding output. I used True for right and False for left. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 7 bytes ``` M`4|5 1 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7w3zfBpMaUy/D/f5/8slRdEMEFZhmaQmhjAwhtYsBlaAqRB9JAWSBpDBYDyhgbQGSANFAGSBqDxYAyJlAZE7CMCVjGJbU0OZXLMQUq75gCAA "Retina 0.8.2 – Try It Online") Link includes test cases. Outputs `0` for right and `1` for left. Explanation: ``` M`[45] ``` The number of 4s and 5s... ``` 1 ``` ... must equal 1 if the serve is on the left. [Answer] # [Perl 5](https://www.perl.org/) (-p), ~~17~~, ~~11~~, 10 bytes -6 using Neil's solution, -1 thanks to Dom Hastings re-ordering ``` $_=1^y;45; ``` [Try it online!](https://tio.run/##bY4xC8IwEEZ3f8URMgmxV3qZYoaCODk6ikVsBqGY0lpB8Lcba6ptGlxueLzvcbVpKuk404wpftAM1gJ4wVSbwGqZJMrxQqfHhyKpnNvZuxGfA0/YN51ZeJBKgB5sT1X7JRl6MimEgZLKoTEjPjKOeuAbM4UwVDKcKj8wRoZNT7J4Q/MsYfwLYfQLYfzLxnRnEyp5@aeblyF52fp2sdfWifoN "Perl 5 – Try It Online") 0 for false, <>0 for true [Answer] # [Python 2](https://docs.python.org/2/), 26 bytes Takes input in the same format as the test cases. Output is inverted, `1` for falsey cases and `0` for truthy ones. Normal output would be 1 byte longer with a `-` preprended. ``` lambda s:hash(s)*199%421%2 ``` [Try it online!](https://tio.run/##Rc@xCoMwFIXh3ae4S4gWBWPioOAgdOwjdLFVUaiJmNtCoe@epqaJS/gv51uyvnFSsjBjczWPbrn1Heh66vQU6@TEqoqIgpHC4KBRQwP0ol5D9nto@j9YGZLnIcWerAzWppM2uB@d4nlQNp2ywf3olDiU8Ep4dR6e931q@4O3PY2iUW2AMEvYv1BHAOs2SwRKskrDB4imQCDGFKRCGGNMEvMF "Python 2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 29 bytes ``` odd.sum.map(mod 882.fromEnum) ``` [Try it online!](https://tio.run/##bY9fa8IwFMXf/RQXGdjC6qJWkLEOZH@etrfBHubA0NzWYJuUJBUHfvZ1N3XTWvYSkt8959yTDbdbLIomS1aNFmJs63Jc8iootYDFYjrOjC6fVF2GTcmlggSEHgDkKdxFkKN70MqhcpbY3qNgTebXNRRSoSVZCFewyiG6P/oACnQgKcbxLb5vZIEQ3CQjGIWQn@aa5jKDQBhdwZQS/OUsPnhxCEkCwzdT4xDcBhX4K2BhEZ45nW1YVRuyyGvQIb2jCHZoZPYFqTYGU0cV7S0NKiOVozVcCfjIfL2EOhy8U4f@V/vP5kXvMPIHcb9q0ILJnLYcfje2ZMZacpbErCOZzI8ZF6QNOZkItBkXkph1JTN2TvkDp5Cjh8is74kvY2PW7xKzXpeY9bs8Yp1iV7IU/@QuRZd8p1nBc9tEaVX9AA "Haskell – Try It Online") An anonymous function taking a hyphenated call and returning `True` or `False`, just like in the test cases. Note: it looks like we're taking values "mod 882", but actually in Haskell `mod 882` is the function \$y \mapsto (882 \bmod y)\$. (That is: it's a partially-applied `mod x y`.) [Answer] # [Haskell](https://www.haskell.org/), 28 bytes ``` f s=[1|c<-s,elem c"45"]==[1] ``` [Try it online!](https://tio.run/##bY9Ba8JAFITv/oohFDRgMNZ4KaYgLT21t0IPVjBsXuLimg3ZVSzktzd9G1uNoZdl93sz82a3idmRUk2TwcSraS0WgRmToj2EF829dcxw3ewTWSBGqgdALrAIkJN90oWlwhpmJ4dGm31Svm2gZEGGZT7u8JkjeDz7AEUWkmNssqOPrVSE0SQeYugjv8w1z2WGUVrpEvec4C5Xce3EPuIY3nt1IA92SwXcFaQM4SXhsw0rDxVb5Bja53cQ4EiVzL4gdFWRsFzRPPCgrGRheU1SpFhlXG8Sc4faObXvfnVaN6/6SIE7mLtVgxZM57yl/t3YklnYkqskCjuS6fyccUPakIuJQZtxI4nCrmQWXlP@wCXk7GEy63ui29go7HeJwl6XKOx3eaaDoK5kmf6Tu0y75FtkKslNE4iy/AE "Haskell – Try It Online") Implement's [Neil's method](https://codegolf.stackexchange.com/a/214317/20260) of checking that the string has exactly one 4 or 5. [Test suite from Lynn](https://codegolf.stackexchange.com/a/214319/20260). Haskell doesn't have a nice way to count elements satisfying a property. We could do `filter(`elem`"45")`, but then it seems too long to check the resulting list is a single element, or check that it's one of `"4"` or `"5"`. We use a list comprehension to make a list with a `1` for each character that's in `"45"`, and check if we end up with the list `[1]`. Any value could be used in place of `1` here, including `s` itself. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` OP%25Ḃ ``` A monadic Link accepting a list of characters which yields `1` if serving from the right or `0` if serving from the left. **[Try it online!](https://tio.run/##y0rNyan8/98/QNXI9OGOpv@H2x81rQGi//@jo9V98stSdUGEuo4ChGNsAGIamuoamkIZJmARYwO4OiATosrEAKrKJbU0OVU9VkchWt0xBaoBKOmYAmUYw4yAS6HYCTEEzDSBWQ9TAGTCdQPVxerEAgA "Jelly – Try It Online")** ### How? ``` OP%25Ḃ - Link: list of characters e.g. "15-30" O - ordinals [49,53,45,51,48] P - product 286085520 25 - twenty-five 25 % - modulo 20 Ḃ - modulo-2 0 ``` --- Also 6 bytes using [Neil](https://codegolf.stackexchange.com/users/17602)'s [observation](https://codegolf.stackexchange.com/a/214317/53748) (inverted result): ``` f⁾45LḂ - Link: list of characters, S ⁾45 - list of characters = "45" f - filter (S) keep (those characters) L - length -> 0, 1, or 2; but only 1 when serving from the left Ḃ - modulo-2 ``` [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 12 bytes ``` {1-m:g/1|4/} ``` [Try it online!](https://tio.run/##bY5NC4JAEIbv/Yo5RPSB7CxOHQILITp1q2MXyTECzVAMJOuvb7aWrkuXgXl434f3xlm8UEkJowg8UA/pJMuzkBWJp8qDEl6JOO5nPBTgrWAdjfU/FROAKM0gvlw5V7v0zs7nQAWHrOCBBnIOUINtEOdf4qImXYTQiMh54@gRLWlLNdCOXoTQjLjYWX6glTSdmrh2h/paQnsLobWF0N6y4eLEZsQP/3j90CRv "Perl 6 – Try It Online") An anonymous function that returns zero for left and non-zero for the right. This uses [Neil's observation](https://codegolf.stackexchange.com/a/214317/76162) that there must be exactly one `1` or `4` for it to be the left side's serve. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 10 bytes ``` %%CSz287 2 ``` [Try it online!](https://tio.run/##K6gsyfj/X1XVObjKyMJcwej/f5/8slRdQ1MA "Pyth – Try It Online") ### Explanation, A little different to the others here... ``` %%CSz287 2 Sz - Sort the input string, (so that Love-15 and 15-Love provide the same string) CSz - Get the 256 base int value of the string. % ^ 287 - Modulo that number by 287 % ^ 2 - Return whether that number is odd or even. ``` [Answer] # [Scala](http://www.scala-lang.org/), ~~30~~ 29 bytes ``` _.matches("[^45]*[45][^45]*") ``` [Try it online!](https://tio.run/##TZBLq8IwEIX3@RVDVo0vLE03QoWKS125VO8lplMf1KSaKMLl/vY6RUuzOXM@@M5mnFaVauzhgtrDWp0N4MujKRzkdf3HnqqCcgYbfz@bI2RzWFhboTKQQfM7uSqvT@givv2R6X6wpfg0Lpp26Ujb4C3iK/vEcRt8xAA@GKcBJNMA5BfiNNgQdAuqSa90djINbILOppr0SmfL0Ja9LXt7iQ/9FfIiHOYFZ4I6AHOT0t5R6VPk4vY9Nf3JV6alIfCd53RKIiEEY//NGw "Scala – Try It Online") My solution uses false for right and true for left. * -1 Thanks to [Jo-King ♦](https://codegolf.stackexchange.com/users/76162/jo-king)! [Answer] # JavaScript (ES6), 26 bytes Using [@Neil's method](https://codegolf.stackexchange.com/a/214317/58563) saves 4 more bytes. Expects a string. Returns **0** for *left* or **1** for *right*. ``` s=>s.split(/4|5/).length%2 ``` [Try it online!](https://tio.run/##hZBBCoMwEEX3PUUIFMxCMzbj0oLQZS8hGq0lJNJYV7172iqUCjHZzOrx5vHv9Vzb5jGMU6pNK11XOluebWZHNUwJx1fBWaak7qfb8eQao61RMlOmT7qEXs0s0@@hjBHOSX7wAXlBCVkB8AICfoDfgLBvyIu1IAQsBbsvPsBSEDIghAwCtg0@YNMAHkDEXmAwEiGyA0JkB4TIDhf5bGTIULXxyKr9B9wb "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 30 bytes Expects a pair of string scores (or a singleton for `Deuce`). Returns **0** for *right* or **1** for *left*. ``` a=>parseInt(a.join`2`,36)%31%2 ``` [Try it online!](https://tio.run/##jZBfC4IwFEff@xRDEBRM79zqzSDoJegbRODQGYpsoubXX7KE/tDmnu7L4fwOt2ETG4q@7satkCVXVaZYduhYP/CzGAMWN7IWeZpHZB/6BPupKqQYZMvjVt6DKrh6FzlxL3qdWxiiJEF4Y4DwzkNogcAEEXhDRhMFm2neWYrWIF1kmdOQLlozUbCbZslvkwH6boL/EHGZoyvhFBz@RMHhTxQc/nTij4JrxGI6lq7hM/kJqSc "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 34 bytes Expects a string. Returns **0** for *left* or **1** for *right*. ``` s=>parseInt(s[0]+s[3]+s[5],35)%3%2 ``` [Try it online!](https://tio.run/##hZDBCoMwEAXv/YogCIbWummSowWhl0L/QDyIxmKRRIz199OqUCrE5LKnYXZ4r3IqdTW0/RhLVQvTpEan174ctLjLMdI5FEed0/nw4kQ5Dml4MZWSWnXi3Kln1ETBQ00ink@AMUoSRA42gPAAoRUAK0DhB9gNDPYNhK8FLmAp2H3xBZYCl4GBy0Bh22ADNg1gAajvBXNGMvDswMCzAwPPDjfxroTLkNX@yKz@B8wH "JavaScript (Node.js) – Try It Online") ### How? Looking at the 1st and the 4th characters provides enough information, except if the score is `Love-X` in which case we need to look at the 6th character as well. To make things easier, we just look at these 3 positions in all cases and hash them. Below is a summary of the process for each possible input. ``` input | s[0]+s[3]+s[5] | parsed as base-35 | mod 3 | mod 2 -------------+----------------+-------------------+-------+------- "Love-Love" | "LeL" | 26236 | 1 | 1 "Love-15" | "Le1" | 26216 | 2 | 0 "Love-30" | "Le3" | 26218 | 1 | 1 "Love-40" | "Le4" | 26219 | 2 | 0 "15-Love" | "1Lv" | 1991 | 2 | 0 "15-15" | "11undefined" | 2906423713803553 | 1 | 1 "15-30" | "13undefined" | 3064054991147303 | 2 | 0 "15-40" | "14undefined" | 3142870629819178 | 1 | 1 "30-Love" | "3Lv" | 4441 | 1 | 1 "30-15" | "31undefined" | 8423518420834803 | 0 | 0 "30-30" | "33undefined" | 8581149698178553 | 1 | 1 "30-40" | "34undefined" | 8659965336850428 | 0 | 0 "40-Love" | "4Lv" | 5666 | 2 | 0 "40-15" | "41undefined" | 11182065774350428 | 1 | 1 "40-30" | "43undefined" | 11339697051694176 | 0 | 0 "Deuce" | "Dcundefined" | 36875963981381680 | 1 | 1 "Ad-40" | "A4undefined" | 27969796811459804 | 2 | 0 "40-Ad" | "4Aundefined" | 11891406522397304 | 2 | 0 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` Ṣ“Œọ‘ḥḂ ``` [Try it online!](https://tio.run/##y0rNyan8///hzkWPGuYcnfRwd@@jhhkPdyx9uKPpfzRQyCe/LBVOzdVBiBiaovKNDVD5JjA@SCGyfjAfrhvMM0ZRC9cJEkbWCebDdYJ5xihq4TpN0HSaoOg0QegEedEltTQZpDAWJOeYgmEOSGhurIL14XaVR01rFLyBROR/AA "Jelly – Try It Online") (the footer tests the program on all possible inputs) Takes input in the form of a list of strings, e.g. `["Love","15"]`, `["40","Ad"]`, or `["Deuce"]`. Outputs 0 or 1, in the opposite sense from the table of test cases in the question (i.e. 0 = right, 1 = left). This is using much the same idea as the other answers: we simply find a hash function that happens to map each possible input to the correct output. In order to make it more likely that a randomly selected hash function would produce the correct result (therefore reducing the number of bytes needed to specify which hash function we want), the input list is sorted before hashing it (thus almost halving the number of cases we need to match; a score of *X*-*Y* always produces the same answer as a score of *Y*-*X*). There wasn't any skill that went into the selection of the hash function; there was a 2-12 probability that any given hash function would work, which is fairly high, so I simply tried Jelly's built-in hash functions in order from shortest to longest configuration, and picked the first one that worked. This is hash function [19,221]. Because configuring the hash function to output booleans would require a substantially larger configuration string, I just used the default output format (this one outputs numbers in the range 1…221) and took the least significant bit of the output as my output. ## Explanation ``` Ṣ“Œọ‘ḥḂ Ṣ Sort {the input list} ḥ Hash {the sorted list}, with configuration “Œọ‘ [19, 221] (compressed representation) Ḃ Take the least significant bit of the output ``` [Answer] # [Bash](https://www.gnu.org/software/bash/), 20 bytes ``` [[ $[$1] = *[14]* ]] ``` [Try it online!](https://tio.run/##ZZBLC4JAFIX38ysOIvQAYcRx04MQylXQpp24mJobBqXiaNGvtyk1lTYD33z33AP3JHVSX6azaR1FsCPbjbHGPHJFPEcc1zPGyldOmko4Ae4yZ@yZXG@EgqSCU6AkXUKmegmVsQss@/NhMTonmYENFrCNtZjKUsJqhcnuEE7YPnuQ83lwLCpq0PUBhPKmW/a44V4L/tOu32QH/A234wa/2YEWvNce79IdtuFm2rA3nhbDZYKPuwUfdQs@7t5SdaZeB@pvW6AGbI5TvwE "Bash – Try It Online") In Bash, any unset variables are 0 in `$[arithmetic mode]`. A quick test revealed that if the input was evaluated in arithmetic mode, the following pattern emerges: ``` Result: 0 10 -10 15 -15 25 -25 30 -30 40 -40 Side: R L L L L R R R R L L ``` Thus, if the arithmetic result contains a 1 or a 4, it is a left serve, otherwise it is a right serve. [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` %2`%25Πmc ``` [Try it online!](https://tio.run/##yygtzv7/X9UoQdXI9NyC3OT////75Jel6oIIAA "Husk – Try It Online") Same method as Jonathan Allan's answer. [Answer] ## Batch, 32 bytes ``` @set/an=(%1)/10%%3^&1 @echo %n% ``` Takes input on the command line and outputs `1` for serves on the left and `0` for serves on the right. Explanation: Based on @GammaFunction's answer, by performing arithmetic evaluation on the input, and assuming that the variables `Love`, `Ad` and `Deuce` are unset and therefore zero, the tens digit of the result is `1` or `4` for serves on the left and `0`, `2` or `3` for serves on the right. This is then further reduced via modulo with `3` and bitwise and with `1` to produce the desired result. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes ``` ⁼¹LΦθ№45ι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMO1sDQxp1jDUEfBJzUvvSRDwy0zpyS1SKNQR8E5vxSoQMnEVElHIVMTBKz//zcx0DU0/a9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Output is a Charcoal boolean, where `-` (True) means you serve on the left and empty output (False) means you serve on the right. Explanation: ``` Φθ Filter input where №45ι Literal string `45` contains character L Length ⁼¹ Equals literal `1` Implicitly print ``` Longer than Retina, sigh... (I found several formulations for 9 bytes, but none shorter that weren't buggy.) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 45S¢O≠ ``` Port of [*@Neil*'s Retina answer](https://codegolf.stackexchange.com/a/214317/52210), so make sure to upvote him!! [Try it online](https://tio.run/##yy9OTMpM/f/fxDT40CL/R50L/v/3yS9L1TU0BQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/E9PgQ4v8H3Uu@K/zP1rJJ78sVRdEKOlA2IamMJaxAYxlAmIZmsLUAVlgVUDaGCoDVmFsAFMBZIFVAGljqAxYhQlchQlUhQlUhUtqaTJI3DEFrtIxRSkWAA). **Explanation:** ``` 45S # Push 45, and convert it to a list of digits: [4,5] ¢ # Count both of those in the (implicit) input-string O # Take the sum of this pair of counts ≠ # And check that it's NOT equal to 1 # (after which the result is output implicitly) ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 7 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` ▒$ε*N%¥ ``` Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/214313/52210), so make sure to upvote him!! [Try it online.](https://tio.run/##y00syUjPz0n7///RtEkq57Zq@akeWvr/v5JPflmqLohQ4oKwDU1hLGMDGMsExDI0hakDssCqgLQxVAaswtgApgLIAqsA0sZQGbAKE7gKE6gKE6gKl9TSZJC4YwpcpWOKEgA) **Explanation:** ``` ▒ # Convert the (implicit) input-string to a list of characters $ # Convert each character to its codepoint integer ε* # Take the product of this list (reduce by multiplication) N% # Modulo-25 ¥ # Modulo-2 # (after which the entire stack joined together is output implicitly as result) ``` ]
[Question] [ The New York Times has a daily online game called [Letter Boxed](https://www.nytimes.com/puzzles/letter-boxed) (the link is behind a paywall; the game is also described [here](https://www.polygon.com/2019/2/1/18205854/new-york-times-crossword-letter-boxed-puzzle-game)), presented on a square as follows: [![Letter Boxed example from the New York Times](https://i.stack.imgur.com/9g0e2m.png)](https://i.stack.imgur.com/9g0e2m.png) You are given 4 groups of 3 letters (each group corresponds to one side on the picture); no letter appears twice. The aim of the game is to find words made of those 12 letters (and those letters only) such that: * Each word is at least 3 letters long; * Consecutive letters cannot be from the same side; * The last letter of a word becomes the first letter of the next word; * All letters are used at least once (letters can be reused). In this challenge, you are given the letters and a list of words. The goal is to check whether the list of words is a valid Letter Boxed solution. ## Input Input consists of (1) 4 groups of 3 letters and (2) a list of words. It can be in any suitable format. ## Output A truthy value if the list of words is a valid solution to the Letter Boxed challenge for those 4×3 letters, and a falsey value otherwise. ## Test cases Groups of letters=`{{I,C,O}, {M,R,E}, {G,N,S}, {A,P,L}}`. ### Truthy values * PILGRIMAGE, ENCLOSE * CROPS, SAIL, LEAN, NOPE, ENIGMA ### Falsey values * PILGRIMAGE, ECONOMIES (can't have CO since they are on the same side) * CROPS, SAIL, LEAN, NOPE (G and M have not been used) * PILGRIMAGE, ENCLOSURE (U is not one of the 12 letters) * ENCLOSE, PILGRIMAGE (last letter of 1st word is not first letter of 2nd word) * SCAMS, SO, ORGANISE, ELOPE (all words must be at least 3 letters long). Note that in this challenge, we do not care whether the words are valid (part of a dictionary). ## Scoring: This [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest score in bytes wins! [Answer] # JavaScript (ES6), ~~130~~ 126 bytes Takes input as `(letters)(words)`. Returns \$0\$ or \$1\$. ``` L=>W=>L.every(a=>a.every(x=>(W+'').match(x,a.map(y=>s+='|'+x+y))),p=s=1)&W.every(w=>w[2]&&p|w[0]==p&!w.match(s,p=w.slice(-1))) ``` [Try it online!](https://tio.run/##nY9Pa4MwGMbv/RTuYhK0dt11vEIQkUA0ogwP4iE4u3a4Ko2rFfrdXZwOdmhh7PAkzwvP7/3zLs9SladD262PzWs17mDk4Gbgcqc6V6cBS3DlYi/g4sxCiDgfsiv3@GJL7Vo8gKssQFdkXayBEGK3oGBLzGzhenD7/Kkwzfba548FQGs@9EsPpcO9o@pDWeH1VsMjN8DIc8SQjTwtgQrbyFGobaLlz2WgbaSVziXVNtbiqCieV6vNxuhOn91@WJXNUTV15dTNG95hTnCOYsaDhIU08JFtID/yuEh1V0Juhb1ExOmUSynj0899Gk1/JOKFZ0FIv/Fp7E7W6i9TPRGJkPnp/@begW5d9pLcjf@crrO/yDvh1KPhvJCYXpEENGIz7PNlp/EL "JavaScript (Node.js) – Try It Online") ### Step 1 We first iterate over \$L\$ to build a pipe-separated string \$s\$ consisting of all invalid pairs of letters. While doing so, we also make sure that each letter appears at least once in some word. ``` L.every(a => // for each group of letter a[] in L[]: a.every(x => // for each letter x in a[]: (W + '') // coerce W[] to a string .match( // and test whether ... x, // ... x can be found in it a.map(y => // for each letter y in a[]: s += '|' + x + y // append '|' + x + y to s ) // end of map() ) // end of match() ), // end of inner every() p = s = 1 // start with p = s = 1 ) // end of outer every() ``` ### Step 2 We now iterate over \$W\$ to test each word. ``` W.every(w => // for each word w in W[]: w[2] && // is this word at least 3 characters long? p | // is it the first word? (p = 1) w[0] == p & // or does it start with the last letter of the previous word? !w.match( // and finally make sure that ... s, // ... it doesn't contain any invalid pair of letters p = w.slice(-1) // and update p to the last letter of w ) // end of match() ) // end of every() ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~30~~ 29 bytes ``` FQṢ=Ṣ},i@€€’:3Iʋ,Ẉ>2ɗ,U=ḢɗƝ{Ȧ ``` [Try it online!](https://tio.run/##y0rNyan8/98t8OHORbZAXKuT6fCoaQ0INcy0MvY81a3zcFeHndHJ6Tqhtg93LDo5/djc6hPL/nvrPGqYo6Brp/CoYa7O4eVch5cDtUT@/x8drR7g6eMe5Onr6O6qrqOg7urn7OMf7Koey6UTre4c5B8QDBINdvT0AdE@ro5@INrPPwCq2tPd1xGiGM0cZ38/f19P12BiTMKmH@yO0CCoJMxZQBkkdWCpYGdHX4jR/iDSP8jd0c8TotTVB2x67H8lT2d/3yBXd79gxwAfJQA "Jelly – Try It Online") A dyadic link that takes the list of words as left argument and the flattened list of letters in the box as the right argument. It returns `1` for true and `0` for false. ### Explanation ``` F | Flatten the word list Q | Unique Ṣ | Sort = | Is equal to Ṣ} | The sorted letterbox letters , ʋ | Pair this with the following: i@€€ | The index of each letter of each word in the letterbox ’ | Decrease by 1 :3 | Integer divide by 3 I | Differences between consecutive ones (will be zero if any two consecutive letters in a word from same side of box) , ɗ | Pair everything so far with the following: Ẉ>2 | Whether length of each input word is greater than 2 , ɗƝ{ | Pair everything so far with the following, applied to each neighbouring pair of the input word list U | Upend (reverse) first word = | Compare characters to second Ḣ | Take first (i.e. last character of first word equals first character of second) Ȧ | Flatten all of the above and check there are no false values ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~37~~ ~~35~~ ~~33~~ ~~32~~ ~~31~~ ~~29~~ 28 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` εk3÷üÊ}DO2@¹ü«εüQO}²{¹˜êQ)˜P ``` -2 bytes by taking inspiration of the `ê` approach [*@Emigna* used in his 05AB1E answer](https://codegolf.stackexchange.com/a/183219/52210). -3 bytes thanks to *@Grimy*. Takes a list of list of characters for the words as first input, and the flattened list of twelve letters as second input. [Try it online](https://tio.run/##yy9OTMpM/f//3NZs48PbD@853FXr4m/kcGjn4T2HVp/benhPoH/toU3Vh3aennN4VaDm6TkB//9HRysFKOkoeQKxDxC7A3EQlO8LxI5QMVelWJ1oIKmj5AfEzlDV/kAcDJGN5YoGa3KGCvtCDXKFGuAHVQoyMACsPRYA) or [verify all test cases](https://tio.run/##yy9OTMpM/e8ZWlb5qGGejsLhvfZKCo/aJiko2Vf@P7c1ojI42/jw9sN7DnfVuvgbOVQe3nNo9bmth/cE@tdGVFcGH14VqHl6TsB/nf/RSp5KOkrOQOwPxL5AHATErkDsDsR@QBwMxI5AHADEPkqxXNHRSgGePu5Bnr6O7iB1rn7OPv7BrkqxOgrRSs5B/gEgDcGOnj4g9a6OICP8/AMgKj3dfR0hClGNcPb38/f1dA0maAgWvWDrQ4OgcjDX6CCrAssEOzv6gk0FedQ/yN3RzxOsztUHbHAsAA). **Explanation:** ``` ε # Map over the character-lists `y` of the (implicit) input-list of words: k # Get the index of each character in the (implicit) input-list of letters 3÷ # Integer-divide each index by 3 üÊ # Check for each overlapping pair of integers that they are NOT equal }D # After the map: duplicate the resulting list O # Get the sum of each inner list of truthy/falsey values 2@ # And check that each is larger than 2 (so all words had at least 3 letters) ¹ü # Get all overlapping pairs of character-lists from the input-list of words: « # And merge them together to a flattened list of characters ε } # Map over those merged character lists: üQ # Check for each overlapping pair of characters in the list that they are equal O # And take the sum of this (where we'd expect 1/truthy if the last character of # the first word and the first character of the second word are equal) # (NOTE: This could fail for inputs with identical adjacent characters, # but the earlier check of `εk3÷üÊ}` already covers for this) ²{ # Push the input-list of letters, and sort them ¹˜ # Push the input-list of list of word-letters, flattened, ê # and then uniquified and sorted as well Q # And check if both lists of characters are the same )˜ # Then wrap everything on the stack into a list, and deep flatten it P # And check if everything is truthy by taking the product # (which is output implicitly as result) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 42 bytes ``` εg2›}P¹εεUIεXå}ƶO}üÊP}P¹ü‚ε`нsθQ}P¹Jê²JêQP ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3NZ0o0cNu2oDDu08t/Xc1lDPc1sjDi@tPbbNv/bwnsNdASCJw3seNcw6tzXhwt7iczsCQSJeh1cd2gQkAgP@/49Wcg7yDwhW0lFQCnb09AHRPq6OfiDazz/AFUS7@nm6@zoqxXJFK3k6@4NEfIPAEu5@YH2OAT5Ksf91dfPydXMSqyoB "05AB1E – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 171 bytes ``` lambda l,w:(set(sum(l,[]))==set(''.join(w)))*all(a[-1]==b[0]for a,b in zip(w,w[1:]))*all((a in g)+(b in g)<2for x in w for a,b in zip(x,x[1:])for g in l)*min(map(len,w))>2 ``` [Try it online!](https://tio.run/##lVJLj5swEL7zK0bKwfYuXTX0tiqVEKIIiUcE3RPlYBaTUBkTYbNk@@dTG5J2N4dWPYw9Y8/3GMvHV3UYhHNu3e9nTvu6ocDt@RFLprCcesztsiLEdU2N0MOPoRN4JoTcUc4xLT9sK9ety49VO4xA7Ro6AT@7I57tudw@Vpc@TM35ntzjek0@O6b/ZIoZbqAn@7RAzfHeHHJy12vVnh4xZ8LW6l@cc@yWJYqQjXwdGapsKFGi01xHsJahTlMdxVp6Ot3piFFVWdbm2zipwyu8UD4xaVnHsRMKWhyb1l0Uh3mUeGGAbEBB6sdZoUnJ@y4/z3aFaSi8KDZ7HHip2dNsdwFGYeIZnLX5Srlkv@UWnr9q@lmaJVGgvRPYAH6mAik40BcGfgayE88M1EET0pHBIEwOkvZ66Rr2Xz5X/hCoaCBZFcSgoGZMwCRZQ/79NE/5leYJOrnAB6FttYutrQOcKcVGeUN1fVfN84Z1JeJUqgvM8Gx1NQ9jc6Vvu/HdvaPNm/sbhcL3knXyzKxZHnpptCoG8Z/h9Rdd0BL6SZrRgRpyY@HT1TvwQezJg3X@BQ "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 34 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ṫ=¥/ƝḢ€Ạȧ⁸Fe€ⱮZḄ;IẠƊȧF}fƑF{ ẈṂ>2ȧç ``` A dyadic Link accepting the words on the left and the letter groups on the right which yields `1` if valid and `0` if not. **[Try it online!](https://tio.run/##y0rNyan8///hzlW2h5bqH5v7cMeiR01rHu5acGL5o8YdbqlAzqON66Ie7mix9gSKHus6sdytNu3YRLdqroe7Oh7ubLIzOrH88PL/h5cDVf7/Hx2tHuDp4x7k6evo7qquo6Du6ufs4x/sqh7LpROt7hzkHxAMEg129PQB0T6ujn4g2s8/AKra093XEaIYzRxnfz9/X0/XYGJMwqYf7I7QIKgkzFlAGSR1YKlgZ0dfiNH@INI/yN3RzxOi1NUHbHrsf3VPZ7CkbxBY3N0PrMExwEcdAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hzlW2h5bqH5v7cMeiR01rHu5acGL5o8YdbqlAzqON66Ie7mix9gSKHus6sdytNu3YRLdqroe7Oh7ubLIzOrH88PL/h5cDVf7/H62goKwQUlRaklGpEJJaXKLgnFicWmzFpRCtHuDp4x7k6evo7qquo6Du6ufs4x/sqh7LpROt7hzkHxAMEg129PQB0T6ujn4g2s8/AKra093XEahYAWS@W2JOcSqq@ToY5jv7@/n7eroGE2NDLBb9YPeFBkElYc4FyiCpA0sFOzv6Qoz2B5H@Qe6Ofp4Qpa4@YNNj/6t7OoMlfYPA4u5@YA2OAT7qAA "Jelly – Try It Online"). [Answer] # [Haskell](https://www.haskell.org/), 231 bytes ``` import Data.List l&w=all((>2).length)w&&c w&&all(l!)w&&(h l)%(h w) h=concat l%w=null[x|x<-l,x`notElem`w] l!(a:b:c)=a#l?(b#l)&&l!(b:c) l!_=1>0 Just a?Just b=a/=b _?_=1<0 c#l=findIndex(elem c)l c(a:b:t)=last a==head b&&c(b:t) c _=1>0 ``` [Try it online!](https://tio.run/##pZBPT8JAEMXv@ymGRZo2QUSPhIU0tTY1/UNaPREC27Ja4tASuqQc/O64i5jgBaNe3uzOzPvlZQpevwnEw2G13lRbCfdc8l6wqiVBo2Ec0TRHd1YPRfkqC6sxjByU6D629NcsAK2O0sYiBcurMufK2mlYuUOc7t/3w2vs7hdlJV0U60UzI9gy@SAb5BbjbRybWRstw1BN3VLDObsd9cnjrpbAx8eSMX7DMjIfq9GwT/I2spdVufTLpdibQlEht5DkR6q0GHJtZawQfAmZCmzqNsnhSD6gkFJsa2Awpb4T0y4NE1epF6VK7UlAZ2TNV6VaWFYEYLOTqdwGJdCn7U6AFLWsB/Rs0KuLqoErOIGNKZ34gZf4oe0pLlA3coI4dRX2ksdJ4kmq11PbD3QNXDvSNYonJ4zvhfY3CtAHjvWfMjlxFIe@m/4r1ezXV3hOfjB9Hevsbup5hrpsTx07/Mwba40Tz478Ey44Rj58AA "Haskell – Try It Online") Not the best score. Some Haskell guru will probably be able to get this under 100 bytes. ### Usage ``` ["ICO","MRE","GNS","APL"]&["CROPS", "SAIL", "LEAN", "NOPE", "ENIGMA"] ``` ### Explanation ``` import Data.List l&w = all((>2).length)w && -- Every word has length > 2 c w && -- Every word ends with the same letter as the next one starts with all(l!)w && -- For every word: Consecutive letters are on different sides (and must exist on a side) (h l)%(h w) -- All letters are used h=concat -- Just a shorthand l%w=null[x|x<-l,x`notElem`w] -- The letters of l, with all letters of w removed, is empty l!(a:b:c)=a#l?(b#l)&&l!(b:c) -- Sides of the first two letters are different, recurse from second letter l!_=1>0 -- Until fewer than 2 letters remain Just a?Just b=a/=b -- Both sides must be different _?_=1<0 -- And must exist c#l=findIndex(elem c)l -- Find the side of letter c c(a:b:t)=last a==head b&&c(b:t) -- Last letter of the first word must be same as first letter of second word, recurse starting from second word c _=1>0 -- Until there are fewer than 2 words ``` [Answer] # [Haskell](https://www.haskell.org/), 231 bytes A different Haskell variation, exactly the same size as [@Paul Mutser's](https://codegolf.stackexchange.com/a/183232/86524) :) ``` import Data.List f x=filter(\a->length a>1)$concatMap subsequences x g=nub.concat.f p l(x:y)=foldl(\(m,n)c->(c,n&&length c>2&&(not$any(`isInfixOf`c)(f l))&&last m==head c))(x,True)y z l w=null(g l\\g w)&&null(g w\\g l)&&(snd$p l w) ``` [Try it online!](https://tio.run/##LY3RaoNAEEXf/YpBRHbBCO1jQUHSEASjIelbDWSz2dWl42rdlZj8vNU0T4c798xMzcyPQJwm1XRtb@GTWRZmylhHwhhJhVb0pGSrGIWubA0sfqMebzVndsc6MMPFiN9BaC4MjE4V6eES/tehdDpAMn7caSRbvCIpSRNoylcx4YH2/ddFHr/7PtGt9Zi@k7MyqZZqLOSZUyIBKZ1NZiw0UVQLdgVOKRmDr34Q9O48AOE2P0UkFWBZVnCb/Ve@LRnnTIy@et2i0qlhSkMEXa@0BQ8e8O2m68INwN0dNgu2@XFBss/cE8zt@lDsn5NjkmYLs02SL8yL/XNhk6fbXeKepj8 "Haskell – Try It Online") ### Ungolfed ``` -- generate all invalid substrings f :: [String] -> [String] f xs = filter (\x -> length x > 1) $ concatMap subsequences xs -- utility function to flatten and remove duplicates g :: [String] -> String g = nub $ concat $ f -- verify that all conditions are satisfied along the list p :: [String] -> [String] -> (String, Bool) p l (x:xs) = foldl (\(m,n) c -> (c , n && length c > 2 && (not $ any (`isInfixOf` c)(f l)) && last m == head c)) (x, True) xs -- put all the pieces together and consume input z :: [String] -> [String] -> Bool z l w = null (g l \\ g w) && null (g w \\ g l) && (snd $ p l w) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 126 bytes ``` ->l,w{(/(_|^)..(_|$)/!~s=w*?_)&&!!s.chars.uniq[12]&&/__|^_|_$|(_.*)\1/!~s.gsub(/(.)_\1/,'\1').chars.map{|x|l.grep(/#{x}/)}*?_} ``` [Try it online!](https://tio.run/##jZDRSsMwFIbv9xQWR9OMmlLvq4QQSiBNSovedDVs4qZQpTaWTZr66l26KWhR8Ob8EL7vP4c07fp92ETDxVXl7zov8JS5gwjZmMPA@dDRbnGtoOs6jkb3j6tGo/bl6bUIL0vXDZSFlVFz4ym0gMtwFNBWt2vbg6CyDz5YhgB@ms@rujN7U6Ft81B7wXm37wPY2/5@qKICMCKBD5KM2hmL3E6cclDOZnX7ps82ReUXIGU8zliC4xGignCZU1CW3xGSyXSUc8y4DU6xsCFkelJYnODR@LuVSCETRvP/9/4Ef7nxJptCX7f7ExzfTsCc4OS4dvwcmcVYsKNG@WnzcAA "Ruby – Try It Online") [Answer] # [Java (JDK)](http://jdk.java.net/), 188 bytes ``` g->w->{var v=0<1;int x=0,l,i=0,j,p,z,y=w[0][0];for(;i<w.length;i++)for(l=w[i].length,v&=y==w[i][0]&l>2,j=0,p=-9;j<l;v&=z>=0&z/3!=p/3,x|=2<<(p=z))z=g.indexOf(y=w[i][j++]);return v&x==8190;} ``` [Try it online!](https://tio.run/##nZJRj5pAEMff/RRTHwxbVw7vXnouS0IINSQCRtInw8NW0VuKQGBF0fOz2wXx2qbpNW0C7PKf/c3MzkzMKjaK19@ufJdnhYBY/qt7wRP1I@n9pm326UrwLG2Mq4SVJbiMp3DuAeT7rwlfQSmYkEuV8TXspE0JRMHT7TIEVmxL1B4F@Nz50W9WPC@iNV8xEemrF1Ysw2VoGLABet2OjMPIOFesgIpq@pjwVMCRajjBXH5jnOMTrulhqYXyIZusUAjXD2oSpVvxQvhwiBotkSd42Km4GtCatopkBonxiGPpK6ejZxLrCZHmk0G1wenh6QPNH57w8ZU@6rqS0xNCJ7pVebqOjv5GqW8@4uEwRKSIxL5IoRocKf00ftbI5Urau94LIEsgolKUQLsiAJyh71i@u7CnXmDOZ30M/bkzmy4c15zaGGzPmvmB3YcL/jNgLfx5gCEwnRmGmW16GDx/3tLO1DXfh3@JZvme7zp28F/x/iFOe6svi78g3eUx/GDfBwLLdJvEfAz@Ymp6TgPbs59zu5BeuzYj0YxU04/JrSvorSn3CZQDW7Badku5KwjMRirVUhQR2ykNuByHapknXChNDgipO5Z3Mz@ZiMySaAshVWTt5s3bZJJGB0S6qEFdiminZnuh5hIWSapsVJbnSX0Lo4XSg9wobVao4y695r1cvwM "Java (JDK) – Try It Online") ## Explanations ``` g->w->{ // Lambda accepting letter groups as a string and a list of words, in the form of an array of char arrays. var v=0<1; // Validity variable int x=0, // The letter coverage (rule 4) l, // The length of w[i] i=0, // The w iterator j, // The w[i] iterator p, // The previous group z, // The current group y=w[0][0]; // The previous character for(;i<w.length;i++) // For each word... for( l=w[i].length, // make a shortcut for the length v&=y==w[i][0]&l>2, // check if the last character of the previous word is the same as the first of the current. // Also, check if the length is at least 3 j=0, // Reset the iteration p=-9 // Set p to an impossible value. ; j<l // ; v&=z>=0&z/3!=p/3, // Check that each letter of the word is in the letter pool, // and that the current letter group isn't the same as the previous one. x|=2<<(p=z) // After the checks, assign z to p, // and mark the letter of the pool as used. ) z=g.indexOf(y=w[i][j++]); // Assign the current letter to y so that it contains the last at the end of the loop. // and fetch the position of the letter in the pool. return v&x==8190; // Return true if all matched // and if the rule 4 is enforced. } ``` ## Credits * -2 bytes thanks to ceilingcat [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 63 bytes ``` ⌊⁺⁺⁺⭆η›Lι²⭆⪫ηω№⪫θωι⭆⪫θω№⪫ηωι⭆η⭆ι⎇μ¬⁼Φθ№νλΦθ№ν§ι⊖μ∨¬κ⁼§ι⁰§§η⊖κ±¹ ``` [Try it online!](https://tio.run/##bZBNa4QwEIbv/RUhpxFS6Pbak1grFr9Yj@JBNGhoEtdsbPvv7cRiV7bOYYZ58s5X2qEx7djIZSmM0BZSoYWaFRRyvt670qKkT5sLDIxEhjeWG0i47u0AwmPk2UN3E72PQjvlF9JgnLH5SqZfIrwD9fRPPRyrEecGstHCB/Jwmht5Bd/GuuPfIBh5QrqlW8SaV94arri2vMNC1GS8xyvg5K12N@GWYEc3y9cdqL9xb0K6D5i2fTUj0vU44LvN9isob2cvy1JVNA5yyghNz6ELUVa64BcJrdkDqWgRJ9E5Tv1ofQ6zIMnLkNb18vgpfwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⌊⁺⁺⁺ ``` Concatenate the below expressions and output `0` if any of them includes a `0` otherwise `1`. ``` ⭆η›Lι² ``` For each word in the solution output whether its length is at least 3. ``` ⭆⪫ηω№⪫θωι ``` For each letter in the solution output whether it appears in the puzzle. ``` ⭆⪫θω№⪫ηωι ``` For each letter in the puzzle output whether it appears in the solution. ``` ⭆η⭆ι⎇μ¬⁼Φθ№νλΦθ№ν§ι⊖μ∨¬κ⁼§ι⁰§§η⊖κ±¹ ``` For each letter in the solution check that the previous letter is not in the same group, unless it is the first letter of a word, in which case check that it is equal to the last letter of the previous word, unless it is the first letter of the solution, in which case just ignore it. [Answer] # [Python 2](https://docs.python.org/2/), ~~168~~ 156 bytes ``` lambda l,w,J=''.join:(set(J(w))==set(J(l)))*all((v<1or u[-1]==v[0])*u[2:]*(2>(x in p)+(y in p))for u,v in zip(w,w[1:]+[0])for x,y in zip(u,u[1:])for p in l) ``` [Try it online!](https://tio.run/##ZY9Nb4JAEIbP9VdM6IFdXZvq0ZQmhGwIhq9AeqIcsGClWRfCh2j/PHWgX@pl3tmZZ2b2LU/NrpDLfqu99iLZb9IEBOvYWlPVh48ilytSZw1Zk45STRtTQSmdJkIQcnhaFBW00XwRa9oheozptI2Wq3hKls/kCLmEks7IaUzoFll2wNdnXpKOddFiFc9wDFtHdvpptazF1lAusShob2uRYhmewhQn4OdouuE56r6txJNJWeWygS2xGUSqb9lmoDu6yVWmctewvZCrMb2EjMDzQ5WBGuqWjWpz3UV1PZ@jctcyHf1m7m/57@K7e5BFAwlUWSKgK6qUwaZtIM32haybKmmyGt4SCbtEpiKDOpfvIpsjONAg8rqpL00owx0L7ygMlPHYy9n41X@uOcNzPcfi4Q03@EUE/aKiX1T0e0N/m8P@vwPXVGjozrjTw@gFpu5a4xS3x7X9Fw "Python 2 – Try It Online") Returns `1` for truthy, `0` for falsey. ]
[Question] [ *([Related](https://codegolf.stackexchange.com/q/1775/42963))* Given an integer `n > 1`, 1) Construct the range of numbers `n, n-1, n-2, ... 3, 2, 1` and calculate the sum 2) Take the individual digits of that number and calculate the product 3) Take the individual digits of *that* number and calculate the sum 4) Repeat steps 2 and 3 until you reach a single digit. That digit is the result. The first twenty terms of the sequence are below: ``` 3, 6, 0, 5, 2, 7, 9, 2, 7, 9, 1, 9, 0, 0, 9, 6, 7, 0, 0, 6 ``` Note: This sequence is NOT in OEIS. ## I/O and Rules * Numbers will get very large quickly, so the solution must be able to handle input numbers up to 100,000 without failure (it's fine if your code can handle past that). * The input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. ## Examples ``` n output 1234 9 3005 3 5007 5 9854 8 75849 8 100000 0 ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~77~~ ~~72~~ ~~71~~ ~~62~~ 60 bytes ``` lambda n:reduce(lambda x,c:eval(c.join(`x`)),'*+'*n,-n*~n/2) ``` *Thanks to @xnor for golfing off 2 bytes!* [Try it online!](https://tio.run/##LchLDoIwFEbhsa7inxBauGgpII9EN6ImIBTF4IUQMDhx66iJZ/ad/jXeOtZLjT1OS1s8LlUBzgZTTaURf89UZuZZtKLc3LuGRT7nUpLtuLbD5LHz5q2WS90NYDSMoeCrEZqgtYSLo6@DkBAoFREipWJCmkTfE0dJmBJ89eucrVf90PAI29pN8A42LDChFiyXDw "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` LOΔSPSO ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fx//clOCAYP///81NLUwsAQ "05AB1E – Try It Online") **Exlpanation** ``` L # push range [1 ... input] O # sum range Δ # loop until top of stack stops changing SP # product of digits SO # sum of digits ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` RSDPDƲÐL ``` [Try it online!](https://tio.run/##y0rNyan8/z8o2CXA5dimwxN8/v//bw4A "Jelly – Try It Online") Full program (it returns a singleton array containing the result, but the brackets aren't visible in STDOUT). [Answer] # [MATL](https://github.com/lmendo/MATL), ~~15~~ 13 bytes In tribute to the [Language of the month](https://codegolf.meta.stackexchange.com/questions/16337/language-of-the-month-for-may-2018-matl?cb=1): ``` :`sV!UpV!Utnq ``` [Try it online!](https://tio.run/##y00syfn/3yqhOEwxtACIS/IK//83NjAwBQA "MATL – Try It Online") I don't think there's a simpler way to get the digits of a number than to convert the number to a string `V`, then transposing it `!`, and converting this vertical vector back to a numeric one `U`. Saved 2 bytes thanks to the Creator1 himself! I forgot the implicit end, meaning I could remove `]`, and instead of comparing the number of elements with `1`, I could simply decrement that value and use it as a boolean directly. So, the explanation goes like this: ``` % Grab input n implicitly : % Range from 1 ... n inclusive ` % Do ... while s % sum the vector V!U % Convert the number to digits p % Take the product of these digits V!U % Convert the product into digits t % Duplicate the result n % Count the number of elements q % Decrement the number of elements % Loop until the number of elements is 1 % Implicit end ``` 1... of MATL, Luis Mendo. [Answer] # JavaScript (ES6), 60 bytes ``` f=(n,k=n*++n/2)=>k>9?f(!n,eval([...k+''].join('*+'[+!n]))):k ``` [Try it online!](https://tio.run/##FY5BboMwFET3PYWzsh1PXX@DAyQyXfUUiIVFoE1A31US5fokjDSLp9GT5pqe6T7cLv@PT87ncV2nqBhz5L0x/OV1bOe2@Z7UjjE@06I6a@1spOztNV9Yyb2Rndlxr7U@zuup8yhQIuCACjUakAMRyIMKUAkKoAOoAtWgBt7Bb2tRonAuIDhXoQp1uYlb@g875dtPGv4Ui9iKIfM9L6Nd8q@SSUlhBL8rtYhig0nx@8n6Ag "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f = recursive function taking: n, // n = original input k = n * ++n / 2 // k = current value, initialized to sum(i=1..n)(i) ) => // k > 9 ? // if k has more than 1 digit: f( // recursive call to f() with: !n, // a logical NOT applied to n eval( // the result of the expression built by: [...k + ''] // turning k into a list of digits .join('*+'[+!n]) // joining with '*' on even iterations or '+' on odd ones ) // end of eval() ) // end of recursive call : // else: k // stop recursion and return the last value ``` --- # Alternate version, 59 bytes (non-competing) A non-recursive version that only works for **n < 236172**. (It covers the requested range but does not qualify as a valid generic algorithm.) ``` n=>[...'*+*+'].map(o=>n=eval([...n+''].join(o)),n*=++n/2)|n ``` [Try it online!](https://tio.run/##FYtBboMwFET3OYV3tvHU9Tc4EEVm11NEWVgEWiL6jUiUVe9O45FmMe9p7umVHsM2r88Pzrdxn@LOsb9Ya2VlKiOv9jetKsee4/hKiyqGjXzze55ZZa3BVTSGP73@4/188ajRIOCIFh1OIAcikAfVoAYUQEdQC@pAJ3gHX2zdoHYuIDjXog1dU44l14Od8vaVhh/FIvZiyPzIy2iX/K1kUlIYwe9KLaIoY1Kstd7/AQ "JavaScript (Node.js) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~72~~ 71 63 bytes ``` g=map(read.pure).show f n=until(<10)(sum.g.product.g)$sum[1..n] ``` Thanks to @BMO for a byte and @nimi for 8 bytes! [Try it online!](https://tio.run/##FchBDoMgEADAe1@xBw@YkM1SJdZE@hHjgVRFUkCCkD6ftnOcQ1/vzblajfI6srTpFWNJW4vXcX5uOwRVQraOTYJadhWPBmM61/LKaNrmF7NADEv12gZQEJMNGRrYYWqeMIt71/OOSHJJNPBBPvqRC/pb6hc "Haskell – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~14~~ ~~13~~ 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ñu┌↕a√äJ²┐ ``` [Run and debug it](http://stax.tomtheisen.com/#p=a475da1261fb844afdbf&i=1234%0A&a=1) Was pretty fun to make. I wonder if there is a more concise way to do the comparison at the end. **Explanation** ``` |+wE:*E|+c9> # Full Program Unpacked |+ # Create range and sum it wE:* # Start loop, digitize number, product of digits E|+ # Digitize number, sum digits c9> # Duplicate, check length is = 1 # Otherwise loop back to the 'w' character ``` -1 bytes thanks to ovs -3 bytes thanks to Scrooble [Answer] # [R](https://www.r-project.org/), ~~152 130~~ 109 bytes ``` function(w,x=w*(w+1)/2,y=prod(d(x)),z=sum(d(y)))"if"(z>9,f(,z),z) d=function(x)x%/%10^(0:max(0,log10(x)))%%10 ``` [Try it online!](https://tio.run/##PYzLCoMwEEX3/QoRhJk6xUlM8EHTTymIkiL4QitGfz7VTc/qci6c2dvg@Qi8XYf6244DbOTMdoctFphI2s00jw004BDpMMvan3tHxLC1IRyvgizQcV54a8y/4dBFSST4DVz2lQOmbvwIviIYnd4v1TR1O9QgSylIyFRRyqxJM2dU5FpRpnNVkOALpMCi9z8 "R – Try It Online") @Giuseppe found ~~21~~ 42 bytes with various R things I'm not used to yet, along with a way to get the digits of a number without coercing to string and back, and with fewer bytes! ``` # Old d=function(x)strtoi(el(strsplit(paste(x),""))) # New d=function(x)x%/%10^(0:max(0,log10(x)))%%10 ``` `options(scipen=9)` ~~is~~ was required for the case of 9854 for the old function, because the first product stage ends up as 80000, which R prints as 8e+05. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 16 bytes -4 thanks to @user ``` f←{⍎¨⍕×/⍎¨⍕+/⍵}⍣≡⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR719h1Y86p16eLo@jKkNZG2tfdS7@FHnwke9m4EKFcxNLUwsudIUDA1AAAA "APL (Dyalog Unicode) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` ωöΣdΠdΣ ``` [Try it online!](https://tio.run/##yygtzv7//3zn4W3nFqecW5BybvH////NAQ "Husk – Try It Online") [Answer] # [Pyth](https://pyth.readthedocs.io), 11 bytes ``` usj*FjGTTsS ``` [Try it here!](https://pyth.herokuapp.com/?code=usj%2aFjGTTsS&input=1234&test_suite=1&test_suite_input=1234%0A3005%0A5007%0A75849%0A100000&debug=0) ``` usj*FjGTTsS – Full program. N = The input. S – Range. Yield [1, N] ⋂ ℤ. s – Sum. u – While no two consecutive iterations yield the same result, do (var: G): *FjGT – Digital product. sj T – Digital sum. ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes ``` ≔Σ…·¹NθW›θ⁹≔ΣΠθθIθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU8juDRXwzMvOae0OLMsNSgxLz1Vw1BHwTOvoLTErzQ3KbVIQ1NTU0ehUNOaqzwjMydVQcO9KDWxBCheqKNgqampgGROQFF@SmlyiUYhTEdAUWZeiYZzYjFYzPr/f3NTCxPL/7plOQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔Σ…·¹Nθ ``` Sum the integers up to the input. ``` W›θ⁹≔ΣΠθθ ``` While the result is greater than 9, take the sum of digits of the product of digits. ``` Iθ ``` Cast the result to string and implicitly print it. [Answer] # [Gaia](https://github.com/splcurran/Gaia), 8 bytes ``` ┅⟨Σ₸∨Π⟩° ``` [Try it online!](https://tio.run/##ASEA3v9nYWlh///ilIXin6jOo@KCuOKIqM6g4p@pwrD//zEyMzQ "Gaia – Try It Online") The old explanation (before fixing a bug that is Gaia’s fault IMO :P): ``` ┅⟨ΣΠ⟩° – Full program. N = The input. ┅ – Range. Push [1, N] ⋂ ℤ to the stack. ⟨ ⟩° – While no two consecutive iterations yield the same result, do: Σ – Sum (or digital sum, when applied to an integer). Π – Digital product. ``` Saved 1 byte thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis). [Answer] ## F#, 175 bytes ``` let d n=seq{for i in(string n).ToCharArray() do yield string i|>uint64} let c n= let mutable r=Seq.sum{1UL..n} while r>9UL do r<-d r|>Seq.reduce(fun a x->x*a)|>d|>Seq.sum r ``` [Try it online!](https://tio.run/##LY7BasMwEETv@oolULALNnJjNzHEglJ6y6HQ5lR6UC05Edhys5ZamzjfrkpO97AM7MzbaYak7lE610oDAnQ1yPOl6REUKB0NBpU@go7T9/75xPEJkU9RDKKHSclWwL9BzcwqbR7zKwmc2nMIBNVZw79aCVi9yXM62O6SHfZpqq8Efk8qHFh52Ace7hIBOLPgQylsLaPGauAwJmy85/HMxO3oIQTQfexetMHptfd/2efytuPKB/D4AxUQCF5lJMLCGSFhcOvo9cx8R7@@fXvTaFjd2VW8RAlQ57KHde7WlBauoHTjym2Ru02xzUuX0TB/) The only caveat to the function is that the input value must be of type `uint64`. Ungolfed it's a little like this: ``` let d n=seq{for i in(string n).ToCharArray() do yield string i|>uint64} let c n = let mutable r = Seq.sum {1UL..n} while r > 9UL do r<-d r |> Seq.reduce(fun a x->x*a) |> d |> Seq.sum r ``` The function `d n` converts the number `n` into its component digits. It first converts to a string, then gets each character in the string. Each character must then be converted back into a string, otherwise the characters will be converted to their ASCII values instead of their "real" values. The `c n` function is the main function, with `n` as the initial value. In this function `r` is our running value. The `while` loop does the following: * Convert `r` into its component digits (`d r`). * Get the product of all those digits. This uses [`Seq.reduce`](https://msdn.microsoft.com/visualfsharpdocs/conceptual/seq.reduce%5b%27t%5d-function-%5bfsharp%5d) which takes a function with the accumulated value (`a`) and the next value in the sequence (`x`) and in this case returns the product. The initial value is the first element in the sequence. * Convert this product value into its component digits (`d`). * Sum the digits from before, and assign this to `r`. [Answer] # [Ruby](https://www.ruby-lang.org/), 57 bytes ``` ->n{("*+"*n).chars.reduce(-~n*n/2){|x,y|eval x.digits*y}} ``` [Try it online!](https://tio.run/##FcHdCoMgGADQVxEhKPflzJTqol4kumhlKxgy/BlFtld37BzjH0dc2ph3@kwxuWGiMzqto7HUqNlPKs2/mug7z86wwxHUZ3yhnc7bc3OWHNcVe8Ip5QUUvBRQMiZBMlZBU0sBlaxFAwX7G6gap/UMLqC3dxbhxKK2Q4nFSe8ALb0bhiv@AA "Ruby – Try It Online") [Answer] # Befunge, 136 bytes ``` 101p&::*+2/>:82+%01g*01p82+/:#v_$01gv X v_v# #:/+82p10+g10%+82: <p100< v:g10$ >#<#^ #<^ >82+/#v_.@ >101p^ ``` You can [try it here](http://www.quirkster.com/iano/js/befunge.html). While not all interpreters have a large enough cell size, it works with small numbers for pretty much anyone out there. For a larger number of `n` you might need a interpreter like [BefunExec](https://www.mikescher.com/programs/view/BefunUtils). [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), ~~35~~ 33 bytes ``` 1AY:P*2,TYMR*YR+:a(?Bt :a(qlBaSD$ ``` [Try it online!](https://tio.run/##S8/PScsszvhv6Oju6Wrt7vffyDHSKkDLSCcyxzdIKzInSNsqUcPeySJIkQvMSAx2Ufn/34jLmMuEy5TLjMucy4LLksvQgMvQyNiEy9jAwJTL1MDAnMvSwtSEy9zUwgQkCQIA "Gol><> – Try It Online") -2 bytes by Jo King. Extensive use of functions and implicit infinite loops. ### Example full program & How it works ``` 1AGIE;GN 2AY:P*2,YlMR*YlR+:a(?B8R! :a(?BaSD$ <main program> 1AG Register row 1 as function G IE; Take number input; halt on EOF GN Call G and print the result as number Repeat indefinitely <function G> 2AY Register row 2 as function Y :P*2, Sum of 1 to n Y Call Y (break into digits) lMR* Product Y Call Y lR+ Sum (an implicit zero is used) :a(?B Return if the result is less than 10 8R! Skip initial 8 commands Repeat indefinitely <function Y> :a(?B Return if the top is less than 10 aSD Divmod by 10; [... n] => [... n/10 n%10] $ Swap top two, so the "div" goes to the top ``` [Answer] # Japt, ~~16~~ ~~14~~ 13 bytes ``` _ì ×ìx}gN®õ x ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=X+wg1+x4fWdOrvUgeA==&input=OTg1NA==) --- ## Explanation ``` :Implicit input of integer U ® :Map N :The array of inputs (which just contains U) õ : Range [1,U] x : Reduce by addition _ }g :Take the last element of N, run it through the following function and push the result to N : Repeat U times and then return the last element of N ì : Split to an array of digits × : Reduce by multiplication ìx : Split to an array of digits and reduce by addition ``` [Answer] # PHP 7, 89 bytes ``` for($a=$argn*-~+$argn/2;$a>9;)$a=array_sum(($s=str_split)(array_product($s($a))));echo$a; ``` Run as pipe with `-r` or [try it online](http://sandbox.onlinephpfunctions.com/code/d941fd16493db3862b495c31fb417589bf084271). * PHP always takes input as string, so I have to use `+` to cast to int for `~` to work as wanted. * Pre-increment would not work: no matter where I put it, it would effect both operands. * But: It doesn´t matter if the single digit takes place before or after the iteration (additional iterations wouldn´t change a thing); so I can use `for()` instead of `do ... while()`. * PHP 7 or later is required for the inline assignment of the function name. Older PHP requires one more byte: `for($s=str_split,$a=...;$a>9;)$a=array_sum($s(...));` (Not assigning `str_split` to a variable at all would waste another byte.) [Answer] # [Perl 6](http://perl6.org/), 49 bytes ``` {($_*.succ/2,{[+] ([*] .comb).comb}...9>=*).tail} ``` [Try it online!](https://tio.run/##HcTRCoIwGAbQV/kQCV3xN3VLB20vIjJsNBAUQ@tCxp59UefivJ7bfEvLgZOHTqHILaP949y1voT@PKDo2QBy6/Io/0ciUkazkt7jNMe0jwey3EIbBI/cxgx@3XCv6kag4VxCct5CdVKglZ1QqPiPSV8 "Perl 6 – Try It Online") [Answer] # [Tcl](http://tcl.tk/), 118 bytes ``` proc S n {set r [expr $n*($n+1)/2] while \$r>9 {set r [expr [join [split [expr [join [split $r ""] *]] ""] +]]} set r} ``` [Try it online!](https://tio.run/##bY@9DoIwAIT3PsWFdFAZLH8BHHwCNsbSgWATa0ppSo0mhGdHxMGYeMuXfLkbznd6WawbOtQwmEbp4cDl0zpQc9hRE0b7YyzI46q0REPdufxt8dugDPhotfL/FHUIAoGDEBtDIWay7edFmc5BEa96iUm31kpzQQX@8WJGzMhXR3GSImEsQ8ZYjrLIUuRZkZaI2DuE6L616wlaYbJ3P64HTg14vVLMyws "Tcl – Try It Online") [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 91 101 93 bytes ``` Function F($a){$o=$a*($a+1)/2;1,2|%{$o=[char[]]"$([char[]]"$o"-join'*'|iex)"-join'+'|iex};$o} ``` [Try it online!](https://tio.run/##TVBta4MwEP5sfsUhKU3q2cW3qojQL/MX7JuUIS6jDjGdWlZQf7vTbGt3HMfz3CVP7slFfcm2O8u6tkvVynnOrk3ZV6qBjNGCD1SltNgt0HL4k5s46I6btZmX56LNTyeTsgdUpv2hqma7246VvPFfZmk2JVRND/UX2fVkIAYt0iPjxMirpl80mLvfuw63jsxxPR89IQIMhAgxjgIfwyDyY3TEGhxG2MAAtIB0LRawDOgrT2AixqIrbxdZ9vJtmZoewgFBIAQILkKIEP8Djq5CZ6xPhn/0oDuevhjpFCYxqndYPkSbMxFMsOUn3N/j6059e5UwwXPdyZ8VJzIRsnqevwE "PowerShell Core – Try It Online") Ungolfed a little... ``` Function F ($a) { $o=$a*($a+1)/2; 1..2 | % { $o = [char[]]"$o"-join '*' | iex; $o = [char[]]"$o"-join '+' | iex; } $o | Write-Output } ``` First steps were to split the integers into digits -- did this by splitting the integer into an array of stringscharacters. Afterwards, insert the operand, and then evaluate the string as a command. Then, it's a matter of doing the multiple-add cycle until the input is one digit. `iex` is an alias for `Invoke-Command` which evaluates a string passed into the first param position. Edit: As requested by [@AdmBorkBork](https://codegolf.stackexchange.com/users/42963/admborkbork), I have added a function header to the byte count. Also, I did a little math and realized that an upper bound on the number of iterations is `< log log 10^6 < log 6 < 2`, so that saved another six bytes. Edit x2: [@AdmBorkBork](https://codegolf.stackexchange.com/users/42963/admborkbork) found a more terse way of converting the integer into a math expression, and then suggested piping it into `iex`. This saved 8 bytes. Thank you! [Answer] # [Perl 5](https://www.perl.org/) `-p`, 61 bytes ``` $_*=$_/2+.5;$_=eval((eval s/./$&*/gr.1)=~s/./+$&/gr)while$_>9 ``` [Try it online!](https://tio.run/##K0gtyjH9/18lXstWJV7fSFvP1Fol3ja1LDFHQwNEKhTr6@mrqGnppxfpGWra1oG42ipqQK5meUZmTqpKvJ3l//@GBv/yC0oy8/OK/@sWAAA "Perl 5 – Try It Online") [Answer] # Java 8, 129 bytes ``` n->{long r=1,i=n;for(;i>1;r+=i--);for(;r>9;r=(i+"").chars().map(p->p-48).sum(),i=1)for(int s:(r+"").getBytes())i*=s-48;return r;} ``` [Try it online.](https://tio.run/##bVGxboMwEN37FadMdikISFBCXDN0b5aMbQeXkPRSMMg2kaKIb6c2UIlIsWxL7/zu7r3zWVyEfz789nkptIZ3gfL2BIDSFOoo8gJ2DgKUtTxBTmwcJGU21NljtzbCYA47kMChl352G5iKRy/IJTvWijDMIqY8jr5Px4DKUqY4QW@xoEH@I5QmNKhEQxo/a/zVhga6rQi1FSLqElxXvSVq4J8K83Y1hU2h@My1pTNVmFZJUKzr2Sirab9LK2tSd6nxAJW1RvZGoTx9fIGgo6//8shjBvgau9vz6PAGYNsYgoPfCUTxcjXHyzBM5jgJw/Ucp5vkjr9ONqv0rmDo1oORDqJHAU7fpHd/1aaogro1QWOtmFK6MW4/zcKTgf0fOlXq@j8) **Explanation:** ``` n->{ // Method with integer parameter and long return-type long r=1, // Result-long, starting at 1 i=n; // Temp integer, starting at the input `n` for(;i>1; // Loop as long as `i` is not 1 yet r+=i--); // And increase `r` by `i` for(;r>9 // Loop as long as `r` is not a single digit yet ; // After every iteration: r=(i+"").chars().map(p->p-48).sum(), // Set `r` to the sum of digits of `i` i=1) // And reset `i` to 1 for(int s:(r+"").getBytes())i*=s-48; // Set `i` to the product of the digits of `r` return r;} // Return `r` as result ``` [Answer] # [Julia 0.6](http://julialang.org/), 56 bytes ``` f(n,k=(n+1)n÷2)=k>9?f(0,sum(digits(prod(digits(k))))):k ``` [Try it online!](https://tio.run/##yyrNyUw0@/8/TSNPJ9tWI0/bUDPv8HYjTdtsO0v7NA0DneLSXI2UzPTMkmKNgqL8FBg7WxMErLL/5yYWACUy80py8h51zEjTUdAwNDI20VEwNjAw1VEwNTAw11GwtDAFipibWphY6igYGoCApuZ/AA "Julia 0.6 – Try It Online") Pretty straightforward: calculate `(n+1)n÷2` for sum from 1..n, check if it's a single digit number (`>9`), if it's not, try again with k set to the sum of the digits of the product of the digits of k, else return k. [Answer] # [J-uby](https://github.com/cyoce/J-uby), 38 bytes This is me resisting forking J-uby to add a bunch of single-character aliases for useful functions. ``` :+|:sum|:!~&((d=:digits)|:/&:*|d|:sum) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWN9WstGusiktza6wU69Q0NFJsrVIy0zNLijVrrPTVrLRqUsCymlDVdgUKbtGGRsYmsVwglrGBgSmEZWpgYA5hWVqYQmXNTS1MLCFMQwMQiIWYsmABhAYA) ## Explanation ``` :+ | :sum | :!~ & ((d = :digits) | :/ & :* | d | :sum) :+ | :sum | # Range 1..n, then sum, then :!~ & ( ) # Until a fixed point is reached... ((d = :digits) | # Get digits (while saving the function to d for later), then :/ & :* | # Reduce with product, then d | :sum # Get digits, then sum ``` ]
[Question] [ # Introduction Your goal is to find the least number of ones you need to add or multiply together to get the input value, this is [A005245](//oeis.org/A005245). ## Input One positive integer ***N***. ## Output The smallest number of ones that must be added/multiplied to get ***N***. ### Sample Input > > 7 > > > ### Sample Output > > 6 > > > ### Explanation > > (`1` + `1` + `1`) \* (`1` + `1`) + `1` = 7 > > > Because this requires `6` ones, the output is `6` > > > ### Test cases ``` 1 1 2 2 3 3 5 5 10 7 20 9 50 12 ``` As this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, lowest number of bytes wins. [Answer] # [Python 2](https://docs.python.org/2/), ~~74~~ 70 bytes ``` f=lambda n:min([n]+[f(j)+min(n%j*n+f(n/j),f(n-j))for j in range(2,n)]) ``` [Try it online!](https://tio.run/##LY/BasMwEETP1lcMFBNtrFBHpRdDesxPhBxcJLUS9SqoCqQt/XZ3FXoaZnZ3Hnv5qu@Z7bqGw8e8vLoZPC2R9YnPwynoRENz3KctD0HzYyIjsktEIRckREaZ@c1ra5jOtDofUP1n1dsbTaprS9yWbmK6S4lcsentFbsXiGzQQ7OBVBIpdT/cG1iDJ4Nng/0o6QMWv@T4PdeYWTVAaDdHHBAMnMjPb2PFICjOteHcBCcvyOwo1aorvl4L37N/jB2FMNL6Bw "Python 2 – Try It Online") ### Alternate version, 59 bytes (unverified) ``` f=lambda n:min([n]+[f(j)+f(n/j)+f(n%j)for j in range(2,n)]) ``` This works at least up to **n = 1,000,000**, but I have yet to prove that it works for all positive **n**. [Try it online!](https://tio.run/##LY7BbsIwEETP8VeMhCJsMCK46iUSPfITiEOQ7dYRWSPXkQJVvz2sgdNod2fm7fWWfyKZefb7SzecbQdqh0DySKf10cterb2k7UvqXvmY0CMQUkffThpN6qRm6zyy@81yNalWVMVExTTxUF1ToIxlbUZsvsCyRA1JGtyolBDP4E7DaHxofGrsGt4uMLghhnuXQyRRAL5kDtjDa1iWv//CCp5RFHPB2RaW/@bbgatFlVweEz13b4xpmNCo@QE "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 14 bytes Thanks Dennis for saving 2 bytes! ``` ÆḌḊ,Ṗ߀€+U$FṂo ``` [Try it online!](https://tio.run/##y0rNyan8//9w28MdPQ93dOk83Dnt8PxHTWuASDtUxe3hzqb8////GxoAAA "Jelly – Try It Online") --- ## Logic explanation Given a number **n**: * If it's `1`, the answer is `1`. Otherwise: The representation is either `a + b` or `a × b`, where `a` and `b` are expressions. Consider all possible values of `a` and `b`: * If the representation is `a + b`, then `a` and `b` are in range `[1 .. n-1]`. * If the representation is `a × b`, `a` and `b` are proper divisors of `n` larger than `1`. In both cases, the list `[[<proper divisors of n larger than 1>], [1, 2, ..., n-1]]` is computed (`ÆḌḊ,Ṗ`), map the current link over each number `߀€`, add the correct pairs together (`+U$`) and get the minimum value (`FṂo`). ## Code explanation ``` ÆḌḊ,Ṗ߀€+U$FṂo Main link. Assume ***n*** = 10. ÆḌ Proper **d**ivisors. *[1,2,5]* Ḋ **Ḋ**equeue, remove the first element. *[2,5]* ,Ṗ Pair with **Ṗ**op. Auto convert ***n*** = 10 to range *[1,2,3,4,5,6,7,8,9,10]* and remove the last element *10*, get *[1,2,3,4,5,6,7,8,9]*. ߀€ Apply this link over each element. +U$ Add with the **U**pend of itself. FṂ **F**latten and get the **Ṃ**inimum element. o Logical **o**r with ***n***. If the list is empty, minimum returns *0* (falsy), so logical or convert it to ***n***. ``` [Answer] ## JavaScript (ES6), ~~108~~ 96 bytes ``` f=n=>n<6?n:Math.min(...[...Array(n-2)].map((_,i)=>Math.min(f(++i)+f(n-i),n%++i/0||f(i)+f(n/i)))) ``` Very inefficient; `Array(n>>1)` speeds it up slightly at a cost of a byte. Explanation: `n%++i` is non-zero if `i` is not a factor, so `n%++i/0` is `Infinity` (and therefore truthy, and also definitely not minimal) if `i` is not a factor, but `NaN` (and therefore falsy) if `i` is a factor. Edit: Saved 12 bytes with inspiration from @edc65. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 66 bytes A port of [Dennis's Python answer](https://codegolf.stackexchange.com/a/154240/9288): ``` f(n)=vecmin(concat(n,[f(j)+min(n%j*j+f(n\j),f(n-j))|j<-[2..n-1]])) ``` [Try it online!](https://tio.run/##FY3BCoMwEER/ZSkUdjUrjefaH4keJJiSha4hSE/@e1wv82B4zJS1Zv6W1hIqTf8t/rJi3DWuB6oLCYX6u9KndNKbNAs5AwvRKW8O4zAo@2UhammvqDCBd@BfDkrNaiPwAP5Y3AcmXQ "Pari/GP – Try It Online") --- # [Pari/GP](http://pari.math.u-bordeaux.fr/), 72 bytes Longer, but more efficient: ``` f(n)=if(n<6,n,vecmin([if(d>1,f(d)+f(n/d),1+f(n-1))|d<-divisors(n),d<n])) ``` [Try it online!](https://tio.run/##Tc2xDsJACAbg3acgTkfk4jHU6doXMQ5GrGGQXq5NJ9/9pDFRlz/wEaBcq8ZHaW0Mhr165hMZrffbUy2cHWRg8sSDz46CxFsRGfElOYquOk919mWSbBfENk41GPTABJwISlVbHPYQB4/tDeLuo136cZe@zOnPvfGjbw "Pari/GP – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 213 bytes **Edit:** I've been [severely beaten](https://codegolf.stackexchange.com/a/154244/61563). ``` f(n)={d;n<6&return(n);if(n<=#a,a[n]&return(a[n]),a=vector(n));for(i=1,n-1,a[i]||a[i]=f(i));a[n]=min(vecmin(vector(n\2,k,a[k]+a[n-k])),if(isprime(n),n,vecmin(vector((-1+#d=divisors(n))\2,i,a[d[i+1]]+a[d[#d-i]]))))} ``` [Try it online!](https://tio.run/##VY3BDoIwDIYfhsSsoTtMoxfYk@AOi2OmIRQykIv47LMzevCyLn@//@vsE@n7nHNUDPYZGm4vh9Svj8QSNCRxayuPvmP3y8sf0Nutv61TEgyaKJOsQdZGUHL7Xl4bFcmy8HYkVlL4jk/vesRB6MHVQujBAaDco2VONPaiRcb/htKmroINtNEypaVcFgeJI3RUG1dEoauCJicygFcWFa8qqvMJIL8B "Pari/GP – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 181 bytes ``` def F(N,n,s="",r=""): try: if n<1:return(eval(s)==N)*0**(`11`in s or"**"in s)*s for c in"()+*1":r=F(N,~-n,s+c)or r except:r return r f=lambda N,n=1:F(N,n).count(`1`)or f(N,-~n) ``` [Try it online!](https://tio.run/##JY69DsIwDIRn@hRWpjgERPhZIrIy9hlaSiIqgVu5AcHCqxcHFut0Z/u78Z2vA23n@RITnHRtyU5BKcsy0FeQ@e2rRZ@Ajs5zzA8mHZ/tTU8YQo1mY4xunGt6ggkGVsaoItFM1SINDB30pDQujVOeQwF8VoJYdighVxBfXRyzF/V/Ll4Kt/Z@vrQgZYLzv1K47oYHZUE15TCJt/oQzgVRCwK0s7C1sLOwt3BADyP3lMsizl8 "Python 2 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 59 bytes Saved 3 bytes thanks to Martin Ender. Using CP-1252 encoding, where `±` is one byte. ``` ±1=1;±n_:=Min[1+±(n-1),±#+±(n/#)&/@Divisors[n][[2;;-2]]] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78///QRkNbQ@tDG/PirWx9M/OiDbUPbdTI0zXU1Dm0URnM1lfWVNN3cMksyyzOLyqOzouNjjayttY1io2N/e@SHx1QlJlXEp2no6CkoGunoKSjADQrVkehGihiCEQGtbHWXBA1pgbIikwN4BKGBigyQG6s9X8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), -p 78 bytes 79 bytes in old style counting (`+1` for `-p`) The fact that perl must use an extra `$` for all scalar access really hurts the length of golfs that do a lot of arithmetic... This method is mostly like the others already posted (try multiplication and addition to build a target number, take the cheapest). It however doesn't repeatedly recurse down so it can be used for relatively large inputs. It also doesn't try to minimize the cost of building a number by addition or multip[lication because perl 5 has no builtin `min` and numeric sort is looooooong (as seen from the sort still in the code). Instead I just assume if a number is a factor of the target that I will use multiplication. That is safe since if e.g. `3` is a factor of `12` (so it sums the cost of `3` and `12/3`) later in the loop it will consider `9=12-3` which will not be a factor, so `9+3` with the same cost as `3+9` will get tried anyways. However that may fail for targets `<= 4` (it only does for `1` and `2`). Adding `$_` to the list to minimize fixes that. Which is unfortunate since I don't actually need that for the base cases because I already initialize `@;` with the proper starting values so it costs 3 bytes. ``` #!/usr/bin/perl -p ($_)=sort{$a-$b}$_,map{$;[$_]+$;[$'%$_?$'-$_:$'/$_]}//..$_ for@;=0..$_;$_=pop@ ``` [Try it online!](https://tio.run/##FchBCsIwEEbhq3TxSxSbZLroxhDsPUSGChUEdYakrkqv7mhX7@PpVJ69ferU9KGjQMn24EOuUuYFo8dtBbevURekC/h63OJ24DOcB5/g4v@uMYYAbu5ShpRpcwJnFR3MOiL6is4PeVfz@gM "Perl 5 – Try It Online") ]
[Question] [ What are some tips for code-golfing in Swift? Its focus on safety seems to make it difficult to golf in, but that makes little tips and even more useful. Are there any features in Swift that may help it excel in code-golf in certain applications? Please post one tip per answer. [Answer] # Ranges One thing that is really helpful is creating ranges using the `...` or `..<` operators For example ``` array[0..<n] //first n elements of array array[k..<n] //kth through nth elements of array array[k...n] //kth through n-1 elements of array ``` So, to get the 2nd through 4th values of an array ``` let myArray = ["ab", "cd", "ef", "gh", "ij", "kl", "mn", "op"] print(myArray[1..<4]) //["cd", "ef", "gh"] ``` ### Practical Use ``` let a = [3, 1, 4, 1, 5, 9] ``` Using ``` for v in a[0...3]{print(v)} ``` Is 8 bytes shorter than ``` for n in 0...3{let v=a[n];print(v)} ``` [Answer] # Closures: The use of variables the hold a function vs. using a function itself can help: **65 bytes:** ``` var r:(String,Int)->String={return String(repeating:$0,count:$1)} ``` **66 bytes:** ``` func r(s:String,i:Int)->String{return String(repeating:s,count:i)} ``` Small difference here, but it'll show more in some puzzles. # Shortening Functions: Looking at the previous example reminds me of something. Sometimes, if you will be using a function enough times, it is worth the space to rename it: This: ``` String(repeating:$0,count:$1) ``` To this: ``` var r:(String,Int)->String={return String(repeating:$0,count:$1)} ``` Or, actually, this is better: ``` var r=String.init(repeating:count:) ``` That way you just call `r("Hello World",8)` instead of `String(repeating:"Hello World",count:8)` # Leaving Out Type Declarations: I once created a closure without setting the argument type, thus creating a shorter answer: ``` var f={(i)->Int in i-1+i%2*2} ``` *The compiler inferred that `i` is in `Int`.* # Create Arrays the Fast Way: If you need an array of `Ints`, use a `Range` to create it: ``` Array(0...5) ``` This does the same thing as: ``` [0,1,2,3,4,5] ``` # Arrays Instead of `If` or `Switch`: Instead of doing this: ``` if n==0{return "a"}else if n==1{return "b"}else{return "c"} ``` You can probably do this: ``` return ["a","b","c"][n] ``` # Shorten Types: If you are using type conversion a lot, you might want to create a type alias: ``` typealias f=Float ``` # Map: Remember that you often don't need to use the `return` keyword in the `map` function. # Running Swift Online: Although [Try It Online](https://tio.run/nexus) does not support Swift [It does now](https://tio.run/#swift4)! [Answer] # Getting Rid of Argument Labels Argument labels eat up a lot of characters: ``` String(repeating:"-",count:81) ``` ``` g.joined(separator:"") ``` But function types in Swift have no argument labels, so if we use the function type instead of the initializer/method directly, we don't need argument labels. The shortest way I know is to put the initializer/method in a closure, then call the closure, and immediately call the resulting function: ``` {String.init}()("-",81) ``` ``` {g.joined}()("") ``` This works for overloaded methods as well, as long as the compiler can infer the method to call from the parameter types. [Answer] ## `try` In Swift 2.x and above, functions that traditionally handled errors by passing a pointer to an `NSError` object as a function parameter now `throw` their error. This means that this: ``` var regex = NSRegularExpression(pattern: "\"((http)s?://.*?)\"", options: nil, error: nil) ``` now looks like: ``` do { let regex = try NSRegularExpression(pattern: "\"((http)s?://.*?)\"", options: []) } catch { print(error) } ``` This can be shortened by using `try?` or `try!`. `try?` will evaluate the expression to `nil` if an error is thrown. `try!` will crash your program if an error is thrown, and should be only used in cases where there will never be an error thrown. ``` let regex = try! NSRegularExpression(pattern: "\"((http)s?://.*?)\"", options: []) ``` `try?` and `try!` save at least 13 bytes from the `do-try-catch` loop. Note that you also save at least one more byte by passing in an empty array (`[]`) for options instead of `nil` as well. [Answer] ## Reducing Arrays Iterating with `for-in loops` through an array to get a single value such as the sum of the elements inside, or the product of its elements may be too long for how simple it actually is. You can just use the `reduce()` method. Some examples: ``` var array = [1,2,3,4,5,6,7] ``` Adding up the elements in an array with `for-in` loops: ``` var sum = 0 for item in array{ sum += item } print(sum) ``` can be simplified to: ``` print(array.reduce(0, +)) ``` And getting the product of the elements inside of the array with for-in loops: ``` var multiplier = 1 for item in array{ multiplier *= item } print(multiplier) ``` can also be reduced to: ``` print(array.reduce(1, *)) ``` [Answer] # Enumeration You can chain `forEach` from `enumerated()` on a collection type to get a reference to the object (or value type) in a collection, as well as its index: ``` [1,2,3,4,5].enumerated().forEach{print($0,$1)} ``` or ``` for (c,i) in [1,2,3,4,5].enumerated(){print(c,i)} ``` or (even shorter `CountableClosedRange` syntax) ``` (1...5).enumerated().forEach{print($0,$1)} ``` Prints: ``` 0 1 1 2 2 3 3 4 4 5 ``` [Answer] ## Substring Sometimes, you can save bytes by falling back onto Foundation types instead of using pure Swift types. Compare accessing a substring of an `NSString` vs a Swift `String` type: ``` let x:NSString = "hello world" x.substringToIndex(5) // "hello" let y = "hello world" y.substringToIndex(y.startIndex.advancedBy(5)) // "hello" ``` Even with the 9 characters lost by declaring `x` as an `NSString`, you save 25 more by using the Foundation type, since `substringToIndex` takes an `Int` as a parameter for `NSString`, vs an `Index` struct (`String.CharacterView.Index`) for Swift `String` types. I should note that the availability of Foundation types may differ across multiple platforms (OS X, Linux, etc). Most Foundation classes are `NSUnimplemented` in the open-source version of Swift. [Answer] # .map() Combining `.map()` with trailing closure syntax can tighten up for-loops. We can put the things we want to iterate over into an array, then use `.map()` to perform some action on each element. For example, we can use `.map()` to write that old chestnut, Fizzbuzz, in one line. ``` var d: [Int] = Array(1...100) d.map{$0%15 == 0 ? print("Fizzbuzz") : $0%3 == 0 ? print("Fizz") : $0%5 == 0 ? print("Buzz") : print($0)} ``` Outside of golf, `.map()` can help cut down on repetition. For example, suppose you have a view you need to position programmatically. You can put the anchors for the view into an anonymous array and run `.map()` over it to set each constraint's `.isActive` to true, like so: ``` _ = [ view.topAnchor.constraint(equalTo: view.topAnchor, constant: 40), view.widthAnchor.constraint(equalTo: view.widthAnchor), view.centerXAnchor.constraint(equalTo: view.centerXAnchor), view.bottomAnchor.constraint(equalTo: view.bottomAnchor) ].map { $0.isActive = true } ``` [Answer] # Import You can replace `import Foundation` with `import UIKit` for 5 bytes shorter, as UIKit does import Foundation already. [Answer] Swift's ternary operator is very terse: `condition ? action : other`action If the condition is true, do one thing, if not, do something else. ``` textColor = bgIsBlack ? .white : .black ``` This makes the `textColor` white if the background is black, or black if the background is any other color. The nil coalescing operator is even terser: `a ?? b` Let's say you're checking JSON for a certain key so you can present the key's value as title text. If the key isn't present (i.e value is nil), we want to give the title default text. ``` title = keysValue ?? "Not Available" ``` [Answer] # Golfing variable assignments in control flow structures using tuples Consider you want to use a `while` loop, and you want to use the same thing in both the condition and the block to follow. Then, an inline assignment in a tuple would most likely help. The longer your attribute, the better! Consider this (3 bytes shorter): ``` func f(s:[Int]){var k=s,i=0;while(i=k.count,i>0).1{print(i,i+k[i-1]);k.removeLast();}} ``` over this: ``` func g(s:[Int]){var k=s,i=0;while k.count>0{i=k.count;print(i,i+k[i-1]);k.removeLast();}} ``` Notice the `(i=k.count,i>0).1` part, which is quite interesting. --- Inspired by one of [Herman Lauenstein's](https://codegolf.stackexchange.com/users/70894/herman-lauenstein) [answers](https://codegolf.stackexchange.com/a/150469/59487). [Answer] # Repeating Strings Unfortunately, Swift does not support String multiplication with `*`, likewise Python. A good method you can use instead is `String(repeating:count:)`, but unfortunately that's not really golfy. Compare these two approaches: ``` var a=String(repeating:"abc",count:3) ``` and ``` var a="";for _ in 0..<3{a+="abc"} ``` The second one is a couple of bytes shorter, but that cannot be used in a closure... Better yet, and it also works in closures: ``` (0..<3).map{_ in"abc"}.joined() ``` And what if I do it multiple times? Well, you can use `String.init()`. Now, this may save lots of bytes. For example (68 bytes): ``` let k=String.init(repeating:count:) print(k("abcd",9)+k("XYZxyz",9)) ``` instead of (74 bytes): ``` print(String(repeating:"abcd",count:9)+String(repeating:"XYZxyz",count:9)) ``` or (70 bytes): ``` var f={String(repeating:$0,count:$1)} print(f("abcd",9)+f("XYZxyz",9)) ``` But make sure your String is long enough. If you are using `String(repeating:"abc",3)`, it is *much* better to use `"abcabcabc"` instead. [Answer] # Conversion to string When possible, it is shorter to use string interpolation than to use the `String` method for converting to a string. ``` String(a) ``` vs ``` "\(a)" ``` ]
[Question] [ Space indentation users, *unite*! We must fight against all the [lowly tab users](https://codegolf.stackexchange.com/questions/56001/my-god-its-full-of-spaces)! Your mission (should you choose to accept it) is to write a program or function that takes in two arguments: * A string: This is the input. * A positive integer: This the number of spaces per tab. You must go through every line of the string and replace every tab *used for indentation* with the given number of spaces, and every tab not used for indentation (e.g. in the middle of a line) with one space. Note that lines such as `\t \tabc` are undefined behavior; they were inserted by the evil tab users to complicate your programs. According to the Tabs Must Die Society, your program must be as short as possible to avoid detection by the evil tab users. ## Example `\t` is used to represent tabs here. Input string: ``` a \t\tb\tc d ``` Input number: ``` 4 ``` Output: ``` a b c d ``` The middle line was indented by 8 spaces, 4 per tab (since the given number was 4). Input string: ``` \ta\t\tb ``` Input number: ``` 4 ``` Output: ``` a b ``` **NOTE:** This is *not* a duplicate of the [tab expansion challenge](https://codegolf.stackexchange.com/questions/18960/expand-tabs-implement-expand1); it requires a very different input format and slightly different requirements. [Answer] # K5, ~~53~~ 45 bytes ``` {{,/(b+a&~b:x*&\a:9=y){$[x;x#" ";y]}'y}[x]'y} ``` In action: ``` {{,/(b+a&~b:x*&\a:9=y){$[x;x#" ";y]}'y}[x]'y}[4;(,"a";"\t\tb\tc";,"d")] (,"a" " b c" ,"d") ``` I just want the record to show that this question is morally reprehensible. [Answer] # Perl, 23 bytes 22 bytes code + 1 bytes command line Hopefully not too cheeky to assume the numeric input can be given via the -i parameter! Ensure to replace \t in the below code with the actual tab character. ``` s/\G\t/$"x$^I/ge;y/\t/ / ``` Usage example: ``` printf "a\n\t\tb\tc\nd" | perl -p entry.pl -i4 ``` Or for convenience: ``` printf "a\n\t\tb\tc\nd" | perl -pe 's/\G\t/$"x$^I/ge;y/\t/ /' -i4 ``` ### Explanation: Using the `-p` argument will execute the program for every line in the input, then print the result at the end. In the above example, the regex substitution replaces `\G\t` with `" "x4` (a space repeated four times). `\G` is a little-known regex construct which matches either the position of first match if the first iteration, or from the position of the previous match if not the first iteration, meaning it will only replace all tabs at the start of the string, and will do so one-by-one. The `y/\t/ /` simply replaces all remaining tabs with spaces. [Answer] # CJam, ~~30~~ ~~24~~ 23 bytes ``` q{_9=NA=Seasi*' ?@?:N}/ ``` I usually refuse to post malicious code on the internet… This is a full program that reads the string from STDIN and the number as a command-line argument. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=l%3AE%3B%20e%23%20Implement%20%60ea'%20(command-line%20arguments)%20as%20%60Ea'.%0A%0Aq%7B_9%3DNA%3DSEasi*'%20%3F%40%3F%3AN%7D%2F&input=4%0Aa%0A%09%09b%09c%0Ad). ### How it works ``` q Read all input from STDIN. { }/ For each character C in the input: _9= Push 1 if C is a tab and 0 otherwise. NA= See below. Seasi* Push a string of W spaces, where W is the integer from the command-line arguments. ' Push a spaces character. ? Select the string if NA= pushed a truthy value, the single space otherwise. @ Rotate C on top of the stack. ? Select the string of spaces or the single space if _9= pushed 1, the character C otherwise. :N Save the result in N. ``` What `NA=` does: * For the first character, `N` will contain its default value, i.e., the string `"\n"`. For all subsequent characters, `N` will contain the result of the last iteration, i.e., the last character from input, a space character or a string of one or more spaces. * If `N` is a string, `NA=` selects the element at index 10 of N (wrapping around). The result will be a space or a linefeed character. Both are truthy. If N is a character, `NA=` pushes 1 for a linefeed and 0 otherwise. * Because of the above, `NA=` will push a truthy value for the first character, a character preceded by a linefeed or a character preceded by a string of spaces (indentation that has already been replaced). In all other cases (including a tabulator that has been replace by a space *character*), `NA=` will push a falsy value. [Answer] # Julia, ~~69~~ 59 bytes ``` f(s,n)=(r=replace)(r(s,r"^\t*"m,i->" "^endof(i)n),"\t"," ") ``` Ungolfed: ``` function f(s::String, n::Int) # Replace the leading indentation tabs r1 = replace(s, r"^\t*"m, i -> " "^endof(i)n) # Replace any remaining tabs between words r2 = replace(r1, r"\t", " ") # Return r2 end ``` Saved 10 bytes and fixed an issue thanks to Glen O! [Answer] # Haskell, 82 bytes ``` n!('\t':x)=([1..n]>>" ")++n!x n!x=f<$>x f '\t'=' ' f x=x g n=unlines.map(n!).lines ``` Then `g 3 "a\n\t\tb\tc\nd"` does the thing. [Answer] # Mathematica, ~~42~~ 37 bytes Thanks to @LegionMammal978 for multiple code-saving suggestions. The first parameter, `#` is for the input text, the second parameter, `#2`, for the number of spaces per tab. ``` StringReplace[#,"\t"->" "~Table~{#2}]& ``` [Answer] # Ruby 49 bytes ``` def r s,t;s.gsub! /^\t/,' '*t;s.gsub!"\t",' ';end ``` [Answer] # JavaScript (ES6), 70 Using template strings, the newline is significant and counted ``` (s,n,r=n)=>[...s].map(c=>c<` `?` `.repeat(r):(r=c<` `?n:1,c)).join`` ``` Test running the snippet below in Firefox. ``` F=(s,n,r=n)=>[...s].map(c=>c<` `?` `.repeat(r):(r=c<` `?n:1,c)).join`` // TEST out=x=>O.innerHTML+=x+'\n\n' out('Input: "A\\n\\t\\tB\\tC\\nD" 4\nOutput:\n'+F('A\n\t\tB\tC\nD',4)) out('Input: "\\tA\\t\\tB" 4\nOutput:\n'+F('\tA\t\tB', 4)) ``` ``` <pre id=O></pre> ``` [Answer] # CoffeeScript, 72 bytes ``` (s,n)->s.replace(/^\t+/mg,(m)->" ".repeat(m.length*n)).replace /\t/g," " ``` (Trying to golf it at least 2 more bites, so it will beat the ES6 solution... Help appreciated :D) Usage: ``` f=(s,n)->s.replace(/^\t+/mg,(m)->" ".repeat(m.length*n)).replace /\t/g," " str=""" My nice\tString \tIndent <-- \t\tDouble """ #\t is recognized as tab by CS alert(f(str,4)) ``` [Answer] # Retina, 42 bytes All occurrences of `.` are spaces, all `\t` are literal tabs (1 byte), and `<empty>` represents a blank file. It's just for readability. I'm also not entirely sure that I'm doing the loop correctly, but I think so. Each line should be placed in its own file. I've added 1 byte for each additional file. Input is assumed to be in Unary on its own line at the end of the input. ``` (1*)$ _$1 m+`(?<!^|\t)\t . (`1$ <empty> )`\t \t. \t|_ <empty> ``` ### Explanation I add a `_` before the Unary input to delimit it during replacement, so that I don't remove any trailing ones from the input string. Then, I replace all tabs not at the beginning of a line with a single space. Then, I loop, removing a single `1` and adding a single space after each tab, until I run out of input. Finally, I clean up by removing the tabs and underscore. [Answer] # Python, ~~72~~ 68 bytes Tabs are literal tabs (1 byte), so `r'...'` is not needed. Unfortunately, Python requires "fixed-width" look-behinds / look-aheads, so I can't use `(?<!^|\t)`. Uses pretty much the same method as my Retina solution. ``` import re lambda s,n:re.sub('\t',' '*n,re.sub('(?<!^)(?<!\t)\t',' ',s)) ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 20 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ÜR╧█╧╫≡eX,)~σOÜ¢G╩N‼ ``` [Run and debug it](https://staxlang.xyz/#p=9a52cfdbcfd7f065582c297ee54f9a9b47ca4e13&i=4+%0Aa%0A%09%09b%09c%0Ad%0A%0A4%0A%09a%09%09b&a=1&m=1) This program reads the first line as the indent width, and the rest of the input as the program. [Answer] # Japt v2.0a0, 17 bytes ``` r/^\t+/m_çVçÃr\tS ``` [Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=ci9eXHQrL21f51bnw3JcdFM=&input=ImEKCQliCWMKZCIKNA==) [Answer] # [Haskell](https://www.haskell.org/), 75 bytes ``` s#m|let('\t':r)#n=(' '<$[1..n])++r#n;(x:r)#n=x:r#(m^sum[1|x<' ']);e#_=e=s#m ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v1g5tyYntURDPaZE3apIUznPVkNdQd1GJdpQTy8vVlNbu0g5z1qjAiIFpJQ1cuOKS3OjDWsqbIAKYzWtU5XjbVNtgeb8z03MzFOwVcjMK0ktSkwuUdBQNtH8n8jFyZnEmcyVwsWZCGQBAA "Haskell – Try It Online") This assumes the input contains only printable chars as well as tabs and newlines, as allowed by OP in the comments. **Explanation:** The outer `#` function takes a string `s` and a number `m` and calls the inner locally defined `#` function with the same arguments. This is done to keep track of the original `m` value, as the inner `#` function changes the number: * `('\t':r)#n=(' '<$[1..n])++r#n` If you encounter a tab, replace it by `n` spaces and leave `n` unchanged. * `(x:r)#n=x:r#(m^sum[1|x<' '])` If some `x` which is not a tab is encountered, keep it as is but set `n` to the original number `m` if `x` is a newline and to `1` otherwise. This is done by `m^sum[1|x<' ']`: `m` is taken to the power of `sum[1|x<' ']` which evaluates to `1` when `x` is smaller than a space (i.e. a newline), so we get `m^1 = m`. Otherwise it's `0` and we have `m^0 = 1`. [Answer] # Java 11, 134 bytes ``` n->s->{var r="";for(var p:s.split("\n")){for(;p.charAt(0)==9;p=p.substring(1))r+=" ".repeat(n);r+=p+"\n";}return r.replace('\t',' ');} ``` [Try it online.](https://tio.run/##fVCxbsMgEN3zFScWg@qgVOrSUlvqUqlDp4whA7FxSupgBOdUUeRvd6FG7daJe9zde/feSV3U@tR@zk2vQoB3ZextBRBQoWngFLt8RNPzbrQNmsHy11w8v1nUR@3Lf4e26I09lrC8dQ0dVLNd12Fd3y7Kg68IEd3gaQLuKfDgeoOUSEsYu6WGcLz5UP4F6YZV1aNwleNhPIQfQnrPmL@rvHZaxS0gpWUifri7xCAmr3H0FjyPE71qNC0kFmUBBRPTLFbRqBsPfTSa/V4G08I5ZkCXg3d7UCzlAbC9BtRnPozIXWwh7bhyrr/SB5YLIlFJK1HiQWIjbZuASriNZkRkmVZ/0S4CkE/PKLoqIZKDOg@jxSydXVj9lbdoKlMqu2Vuz34NErkhZaTJetP8DQ) NOTE: Java 11 isn't on TIO yet, so `" ".repeat(n)` has been emulated as `repeat(" ",n)` instead (with the same byte-count). **Explanation:** ``` n->s->{ // Method with integer & String parameters and String return-type var r=""; // Result-String, starting empty for(var p:s.split("\n")){ // Loop over the rows (split by new-lines) for(;p.charAt(0)==9;// Inner loop as long as the current row starts with a tab p=p.substring(1))// After every iteration: remove the first character (tab) r+=" ".repeat(n); // Append `n` amount of spaces to the result-String r+=p+"\n";} // Append the rest of the row with a newline to the result return r.replace('\t',' ');} // Replace any remaining tabs with a space, and return the result ``` ]
[Question] [ The boardgame [Terra Mystica](https://boardgamegeek.com/boardgame/120677/terra-mystica) has some very interesting mechanics for one of the primary resources, power. Instead of gaining and spending units of power from a bank, each player starts the game with exactly 12 units of power which are distributed over three "bowls", which are labelled I, II and III. Gaining and spending power then simply shifts power between these bowls: * To spend a unit of power, move it from bowl III to bowl I (provided you have a unit in bowl III). * When you gain a unit of power, if there is a unit in bowl I, move it to bowl II. If there are no units in bowl I, but there is a unit in bowl II, move it to bowl III. If all units are already in bowl III, nothing happens. * When you gain or spend multiple units at once, they are processed one unit at a time. Here is an example. Say, a player starts with the following power distribution (given in order `I | II | III`): ``` 5 | 7 | 0 ``` Their power changes as follows if they gain and spend power a few times: ``` 5 | 7 | 0 Gain 3 ==> 2 | 10 | 0 Gain 6 ==> 0 | 8 | 4 (move 2 power from I to II, then the remaining 4 from II to III) Gain 7 ==> 0 | 1 | 11 Spend 4 ==> 4 | 1 | 7 Gain 1 ==> 3 | 2 | 7 Spend 7 ==> 10 | 2 | 0 Gain 12 ==> 0 | 10 | 2 (move 10 power from I to II, then the remaining 2 from II to III) Gain 12 ==> 0 | 0 | 12 (the two excess units go to waste) ``` Your task is to compute the result of one such gaining or spending event. ## The Challenge You are given four integers as input. The first three, `I`, `II`, `III`, represent the amount of power in each of the three bowls. They will be non-negative, and they will sum to 12. The fourth number, `P`, is the amount of power gained or spent, and will be in the inclusive range `[-III, 24]` (so you may assume that the player will never try to spend more power than they currently can, but they might be gaining more power than they need to move all power into bowl III). You may take these numbers in any consistent order, as separate arguments, as a list of integers, or as a string containing these integers. You can also take `P` as one argument, as `I`, `II`, `III` as a separate list argument. You should output three integers `I'`, `II'`, `III'` which represent the amount of power in each bowl *after* `P` units were gained or spent, following the rules explained above. You may write a [program or a function](http://meta.codegolf.stackexchange.com/q/2419) and use any of the our [standard methods](http://meta.codegolf.stackexchange.com/q/2447) of receiving input and providing output. You may use any [programming language](http://meta.codegolf.stackexchange.com/q/2028), but note that [these loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer – measured in *bytes* – wins. ## Test Cases ``` I II III P => I' II' III' 5 7 0 3 => 2 10 0 2 10 0 6 => 0 8 4 0 8 4 7 => 0 1 11 0 1 11 -4 => 4 1 7 4 1 7 0 => 4 1 7 4 1 7 1 => 3 2 7 3 2 7 -7 => 10 2 0 10 2 0 12 => 0 10 2 0 10 2 12 => 0 0 12 ``` [Answer] ## Mathematica, 52 bytes ``` {x=#-#4~Min~#,y=Max[#2+#-Abs[#4~Max~0-#],0],12-x-y}& ``` This is an unnamed function that takes a list `{I, II, III, P}` as input and returns a list `{I', II', III'}`. A closed-form solution. It doesn't really feel optimal yet... [Answer] # C, ~~97~~ 94 bytes ``` f(i,j,k,n){for(;n;n-=n/abs(n))n<0?k?++i+--k:0:i?++j+--i:j?++k+--j:0;printf("%d %d %d",i,j,k);} ``` In ungolfed form: ``` f(i, j, k, n) { while (n) { if (n < 0) { if (k) { ++i; --k; } ++n; } else { if (i) { ++j; --i; } else if (j) { ++k; --j; } --n; } } printf("%d %d %d", i, j, k); } ``` [Answer] # Python 2, 104 bytes ``` def f(i,d,t,g): x=min(i,g);i-=x;q=g>0;g-=x if q:d+=x;x=min(d,g);g-=x;d-=x;t+=x else:t+=x print i,d,t ``` [**Try it online**](https://tio.run/nexus/python2#NYxLDsMgDET3OYWXoBgJCP0oiJ6Gj5DaqGmyyO2pTVrJGL/xeFpMGbKoGHHHIucBjvCqCwlF@qrC4ddQHtoXGgeoGdY5jqSersguXvnIbR/ZlJ5bms/x/anLDj28ZXFBuCFohEkOWVgEozteGem/Iziy/MhQ0VOO2XWma8M0IdhOqps5xvYkY//Hp0Tcvg) **Ungolfed:** ``` def f(i,d,t,g): if g>0: x=min(i,g) g-=x i-=x d+=x x=min(d,g) g-=x d-=x t+=x else: x=min(i,g) g-=x i-=x t+=x print(i,d,t) ``` [Answer] ## Haskell, 58 bytes ``` f(a,b,c)d|m<-min a d,z<-min(c+d-max 0 m)12=(a-m,b+c+m-z,z) ``` The intermediate value `m` denotes the amount of power going from (or to, if negative) the first bowl, `z` denotes the amount of power in the third bowl after the action. A last minute one byte optimization changed the old expression for the second bowl from `12-a+m-z` using the identity `a+b+c=12`. The natural result type is a triple for the bowls, so the input also takes the bowls as a triple and the power change as a second argument. This allows to handle all test cases with one application of `scanl`: ``` *Main> scanl f (5,7,0) [3,6,7,-4,0,1,-7,12,12] [(5,7,0),(2,10,0),(0,8,4),(0,1,11),(4,1,7),(4,1,7),(3,2,7),(10,2,0),(0,10,2),(0,0,12)] ``` [Answer] # [Röda](http://github.com/fergusq/roda), ~~100~~ 94 bytes ``` f a,b,c,p{{c+=p;a-=p}if[p<0]else{{a--;b++;p--}while[p*a>0];{b--;c++;p--}while[p*b>0]};[a,b,c]} ``` Ungolfed: ``` f a,b,c,p { if [ p < 0 ] do c += p a -= p else { a-=1; b+=1; p-=1 } while [ p > 0 and a > 0 ] { b-=1; c+=1; p-=1 } while [ p > 0 and b > 0 ] done return a, b, c } ``` [Answer] # JavaScript, ~~61~~ 59 bytes ``` (a,b,c,d)=>[r=a-d>0?a-d:0,s=r?b:b-d+2*a>0?b-d+2*a:0,12-r-s] ``` [Try it online!](https://tio.run/nexus/javascript-node#S7P9r5Gok6STrJOiaWsXXWSbqJtiZ2APJK0MdIpti@yTrJJ0U7SNtBKBolAWUMbQSLdItzj2f3J@XnF@TqpeTn66RpqGoQ4QGujoGhpoanKhSpnrGOsY6VhgiJsBtZjqYNEANctEU/M/AA) [Answer] # [GNU sed](https://www.gnu.org/software/sed/), 66 bytes Includes +1 for `-r` ``` /-/!{: s/1,(.* )1/,1\1/ t} s/(.*)(1+) -\2/\2\1/ s/(,,1{12}).*/\1/ ``` Uses unary (see [this consensus](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary?answertab=votes#tab-top)). [Try it online!](https://tio.run/nexus/sed#XY07EsMgDER7TqF0xhHWLGXOwgXSxJnYncdXD5Eg@KeCYd@utFmC3JaHmwTcDT15CCNB3LwqU@I73D2FFCVF4wqZsSCufuhFSc6wYdRh0sftuiGjGyufPzV8CIMC6gWLNeMiqQDeW@pSC24lrfnaX8yzdxR83vuO7/k5vqYcPj8 "sed – TIO Nexus") ``` /-/!{ # If there is not a '-' : # start loop s/1,(.* )1/,1\1/ # move a 1 from before a ',' to after the ',' for every 1 after the space # sed reads left to right, so this takes everything from the first bowl before starting on the second t # loop if something changed } # end if s/(.*)(1+) -\2/\2\1/ # take all of the 1s from after a '-' and move them to the begining. # at the same time, remove that many 1s from the 3rd bowl s/(,,1{12}).*/\1/ # remove everything after 12 1s in the third bowl ``` [Answer] # [Retina](https://github.com/m-ender/retina),  46  41 39 38 bytes *Thanks to* [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender) *for multiple helpful suggestions!* ``` +`1,(.*¶)1 ,1$1 (.*)(1+)¶-\2$ $2$1 G`, ``` Takes input in unary. The first line contains the amounts of power in the three bowls, comma separated, the second line the amount of power to cycle. [Test suite](https://tio.run/nexus/retina#LYsxDsIwEAT7fYcj2ckaeS@BUNFSUaVN4YI3@gH@mLlIVDN32pnike1VifO7IMxjqWK8zb0lgQqCHylqSb3l0wKC@e9dOQ5vpk8VegPHnTsLVxhVXB4ofHLj7hQl5g2bm4/@FFaaM@/wwryRXePLZT8) - Takes all inputs on a single line and converts from decimal to unary and vice-versa for convenience of use. ### Explanation ``` +`1,(.*¶)1 ,1$1 ``` Positive case: we repeatedly remove the leading `1` from the second line, and move a `1` from the first non-empty bowl to the following one, as long as this operation is possible (i.e. the number of power to cycle is non-zero and not all power is in the third bowl). The `s` modifier means `single-line`, allowing `.` to match also the newline. ``` (.*)(1+)¶-\2$ $2$1 ``` Negative case: done all in one step, moving the amount of power indicated by the last input from the third to the first bowl. This will also remove the line containing the negative amount of power to move. ``` G`, ``` Keep (grep) only lines containing a comma. This will get rid of the eventual remains of the first line. [Answer] # Python 2, 91 bytes Based on [this answer](https://codegolf.stackexchange.com/a/112181/66485) ``` def f(i,d,t,g): x=min(i,g);i-=x if g>0:y=min(d+x,g-x);d+=x-y;t+=y else:t+=x print i,d,t ``` [**Try it online**](https://tio.run/nexus/python2#NYzbCgMhDETf/Yo8rmwEde2FFfs1XhDapbQ@uF@/jWkLCckZZuaIKUOeKkZsWOQqoIdH3Ugo0lcVuoCaodz0urMe545FdenjHLrafZvDLiDd32mll9zPV90acN@RpxPCBUEjLFLkySIYzXgeSPeK4MjyI0NDq9xgx0xpM2hBsEyKzaPGcpOx//BXIj4@) **Ungolfed:** ``` def f(i,d,t,g): if g>0: x=min(i,g) y=min(d+x,g-x) i-=x d+=x-y t+=y else: x=min(i,g) i-=x t+=x print(i,d,t) ``` [Answer] ## Batch, 87 bytes ``` @set/a"i=%4-%1,j=%4*(-%4>>5)-%2-2*i*(-i>>5),i*=i>>5,j*=j>>5,k=12-i-j @echo %i% %j% %k% ``` Use the following formulae: ``` I' = min(I - P, 0) II' = min(II + min(P, 0) - 2 * min(P - I, 0), 0) III' = 12 - I' - II' ``` Since Batch doesn't have a less than operator, I calculate `i = min(-i, 0)` using `i*=i>>5`. [Answer] # [Perl 6](http://perl6.org/), 99 bytes ``` ->\a,\b,\c,\d{d>0??[»+»] (a,b,c),|(|((-1,1,0)xx a),|((0,-1,1)xx a+b),|(0 xx*))[^d]!!(a- d,b,c+d)} ``` Let `a`, `b`, and `c` be the number of starting tokens in bowls I, II, and III respectively. Then, for the adding power case, a list is created that contains `a` copies of the triplet `(-1, 1, 0)`, followed by `a + b` copies of the triplet `(0, -1, 1)`, followed by infinite copies of `0`. The first `d` elements of this list, `d` being the amount of power to add, are added elementwise to the starting power distribution. For subtracting power (negative `d`), a simple closed form is used: `(a - d, b, c + d)`. [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 134 bytes ``` (d f(q((x y z p)(i p(i(l p 0)(f(s x p)y(a z p)0)(i x(f(s x 1)(a y 1)z(s p 1))(i y(f x(s y 1)(a z 1)(s p 1))(f x y z 0))))(c x(c y(c z( ``` Defines a function `f` that takes four arguments, the three bowls (`x y z`) and the amount of power transacted (`p`), and returns a list of the three bowls after the transaction. Here's a properly spaced version with all test cases: [Try it online!](https://tio.run/nexus/tinylisp#VY9NDoMgEIX3nuItZ3agtvQ6jcbEpAuaboDL2zeDNikJeT98jnDIim2AvGUApKCiIav5HZliKi9kBCsZN/mgEKnydPTqdxQ3FxGVQKU0xkzV83hH7Y4kCg9rZ5vJH@qA3yio9lIWfrKgcjfRcx3kbkgImHSgHxEDw91DwAMz0ukjYgT/EjCrVzOrZI/7@eh@4pTUydRJzhxtwniNssx0fAE "tinylisp – TIO Nexus") ``` (d f Define f to be (q( a quoted two-item list (which acts as a function): (x y z p) Arglist: the three bowls x y z and power p (i p If p is nonzero (i (l p 0) then if p is negative (spending power) (f(s x p)y(a z p)0) then take -p from z, add -p to x, and recurse with p=0 (i x else (gaining power), if x is nonzero (f(s x 1)(a y 1)z(s p 1)) then take 1 from x, add to y, decrement p and recurse (i y else if y is nonzero (f x(s y 1)(a z 1)(s p 1)) then take 1 from y, add to z, decrement p and recurse (f x y z 0)))) else no moves possible; recurse with p=0 (c x(c y(c z()))))))) else (p=0), cons x y z into a list and return it ``` ]
[Question] [ When we publish some software, we assign a version number to it. And users may want to update to the latest version of some software. So, it is the time to find out which version should be newer. ### Input Input two version numbers as strings. In the context of this challenge, we only support version numbers which are some digits joined by dots. * A version number is a non-empty string which may only contain digits (`0` ~ `9`) and dots (`.`). * Dots would not be the first / last character of a version number. * There must be some digits between dots. No two dots may appear continuously. * All numbers in a version number would be less than 216. ### Output Compare the inputted version numbers and output whether first one is greater than / equals to / less than the second one. You are allowed to choose one of the following presentations: * Use positive number / zero / negative number, while zero means equal; * Use three constant distinct values; ### Comparing You are not required to implement the algorithm described in this section. Your submission is valid as long as it result the same output with this algorithm. * Version numbers are some decimal numbers joined by dots. We first split the two version numbers to arrays of numbers; * Padding the ending of arrays with zeros to make them have same length; * Compare from the first item to the last one: + If the two array items different, the greater number means greater version number + If they are the same, continue to compare the following items; + If all items in the array are equal, the two versions are equal. ### Testcases ``` version1 version2 result 2 1 > 1.0.0 1 = 1.0 1.0.0 = 1.2.42 1.2.41 > 1.1.56789 1.2.0 < 1.10 1.2 > 1.20 1.150 < 18.04 18.4 = 7.010 7.8 > 1.0.0.1.0 1.00.00.2 < 00.00.01 0.0.0.1 > 0.0.1 0.1 < 42.0 4.2.0 > 999.999 999.999.1 < 2018.08.1 2018.08 > ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~84~~ ~~79~~ 76 bytes ``` lambda*l:cmp(*map(lambda v:map(int,v.split('.')+[0]*len(`l`))[:len(`l`)],l)) ``` [Try it online!](https://tio.run/##fZDhasMgFIX/7ymE/biahYtKupjQ7kXaQtOtZQWTSRsKffpMo7FJsy4Y8Fw/z/Uec2u/fxrZHVebTlf1/qtKdPlZG5rUlaG@Qq6lE6emTa94MfrUUkBgb2u@TfShoTu9Y2xdDtttqhnrzNny5EhBAglfSkBEwV4JfMBLxARy5PAntppicHeLd@aYxKzv3GNW9JbzpgIX77kqIGB3t@UUC109Bs9GkGNMLJ64KeRZnFSh389GyJGLGEiOCv7JDV0sPhDuloTHpr7ObQoW4/4OzN2GOvGYGDUdu2VDUg7LJrmN3YqiQPtDjwVhPR/dJHeRKHtisSCGt3W/ "Python 2 – Try It Online") Outputs `-1,0,1` for `<,=,>` [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ ~~14~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` '.¡0ζε`.S}0K¬ ``` Outputs `-1 [] 1` for `< = >` respectively. -1 byte thanks to *@Emigna*. [Try it online](https://tio.run/##MzBNTDJM/f9fXe/QQoNz285tTdALrjXwPrTm//9odUM9Az1DIDRQ11EAcQz0jIDsWAA) or [verify all test cases](https://tio.run/##VY5BCsIwEEX3nqJ0M5syzITEJqtuRBCXLktBBY/h1gN4A/fd6gF6gB7Ci0STmViEBP5/@T98cqczXyK77W7T1dX7dq/qLgJOD5pf8/OIhyvtpzE2sQcDTQUMw6oHRkL6s9lkKsCglXxSJcXo1q0PhZcsa9uUrnp2mvBINiOPNpMWSUot@mUQLjsoHflPNHF6IYkJzypDAdZI3f6mhRDwexNUqVFDaZPXX9XB8AE). **Explanation:** ``` '.¡ # Split on dots # i.e. ['1.0.1.1.0','1.00.2.0'] # → [['1','0','1','1','0'],['1','00','2','0']] 0ζ # Zip, swapping rows and columns, using '0' as filler # i.e. [['1','0','1','1','0'],['1','00','2','0']] # → [['1','1'],['0','00'],['1','2'],['1','0'],['0','0']] ε } # Map each: ` # Push both values to the stack .S # And calculate the signum (1 if a>b; -1 if a<b; 0 if a==b) # i.e. [['1','1'],['0','00'],['1','2'],['1','0'],['0','0']] # → [0,0,-1,1,0] 0K # Remove all zeros # i.e. [0,0,-1,1,0] → [-1,1] ¬ # Then take the head as result # i.e. [-1,1] → -1 ``` [Answer] # [R](https://www.r-project.org/), 32 bytes ``` rank(numeric_version(scan(,""))) ``` [Try it online!](https://tio.run/##bZLbaoQwEEDf/YoheVGwQxLcqtDdx/5EKUVEW2kbi7r7@3ZyMeq6wcBkPDkzDg4zf73qeup6Xf3ArRlGiqDtB5iacer0JzzB9NXAm3yHboT@z5FRe4bW34tvyVDp71hff5uhqz@8hNIJp2vzw5djXek4ZSxJkpkpIQsUBUoGS8yiiAMokEDLtHMxZ4knu33ubHNEueNLBFEb1zFTLAUmyQ2HxUlkGYkCBUsfYZzEC2MIS95RG0ZhpixGwc62qUVNP@dF6bGNjVPXC@OKqUNDG49yjDzdN7R6aHqZgQrMDozvOUdhi@VYHL9rOx8MExDm8a2FWi4rJCHC4UEXPC5tAHms5T2ZsmWy/Wj2nrIskTZhPlp9wbP@R2n4jwJzmf8B "R – Try It Online") Using an R builtin Outputs `1 2`, `1.5 1.5`, `2 1` for less, equal, greater. --- Best so far, without builtin : ### [R](https://www.r-project.org/), ~~151 142 125~~ 107 bytes ``` function(v,L=strsplit(v,'\\.'))Find(c,sign(Reduce('-',Map(as.double,Map(c,L,Map(rep,0,rev(lengths(L)))))))) ``` [Try it online!](https://tio.run/##bZDLioMwFIb3PkXQhRHSQxJsVRgL3czKmcWsu@lo7Aii4qWvb2OSeqkTFE/C5/efnHbM4zEfqrQv6go/SBJ3fds1ZdHLjXu9gut5n0WV4ZR0xb3CPyIbUoHdg0u@bg2@dZDVw28p1C4lifq2oiGUtOKBS1Hd@78OJ55Zo4MQQ3ndorPloO@LKmNZHvTph4WsHKfY5jZBNrM9D@2WI/9VDAMK1Cb/YY6UvpiJUOQbtWI4@FxhstjYVlkMjqcgjAy2sjmy6xejw/iuoZWHa4Yd3xtaPCFQf4JC8HeM6TkAqsICCPf3Ws8H5gnQ6TGtzVn6lDKJUI3PutmjjyeA7bOMx@cqxt@OZuuJogjkKzFTLb7Zw@l0@1DlmXphzuMT "R – Try It Online") Unrolled code with explanation : ``` function(v){ # character vector of 2 elements as function arg; L=strsplit(v,'\\.') # obtain a list of two character vectors # with the separated version numbers; R=rev(lengths(L)) # store in vector R the lengths of the 2 vectors and reverse it; M1=Map(rep,0,R) # create a list of 2 vector containing zeros # repeated R[1] and R[2] times; M2=Map(c,L,M1) # append to the vectors in list L the zeros in M1; M3=Map(as.double,M2) # convert the character vectors in M2 to double; w=sign(Reduce('-',M3) # compute the sign of element by element difference M[[1]] - M[[2]]); Find(c,w) # returns the first non zero element in w, if none return NULL; } # N.B. as.double is necessary because "0XX" is interpreted as octal by strtoi unless # we use strtoi(x,10) which is exactly the same length of as.double(x) ``` Outputs `-1`, `NULL`, `1` for less, equal, greater. --- Original concept, golfed down using `sapply`, `[<-` and `%*%`: ### [R](https://www.r-project.org/), 129 bytes ``` function(x,y=strsplit(x,"\\."),w=sign(sapply(y,function(x)strtoi("[<-"(rep(0,max(lengths(y))),seq(x),x),10))%*%c(1,-1)))w[!!w][1] ``` [Try it online!](https://tio.run/##VZDRioMwEEXf9yvSLIXJkg5JSFeF9S/2zfZBRFvBVde4WL/eTaLUFBKYe@6d0cmwVOlS/bXFWHctPPicmnEwfVOPVtDLBSnjU2rqWwsm7/tmhpnvcWbDY1cDzb5OFIayB8F/8gc0ZXsb7wZmxhg35a9NcnukYOz4cSxA8pO01pQdDtM1k9elggKoopxQSRl781KiQEH5K3Ha850p1MpjW4RZiefPKE42K@yQ6xgVDlmRPAe5GIV2NEb9hBEK3x1hbBkh7@T7XpKhzE3XkqobyPYiuVs22AOf/y7c2T@9aiGtKdbgbnnl@M608nP0y0ZJkqC9lm9V0KCE2yP2g7baess/ "R – Try It Online\"Split on `.` Make both the same length (which pads with `NA`). Convert `NA` to 0 and coerce to integers with `strtoi`. (And the base has to be included or things like `\"010\"` are treated as octal.") Now you have a list of two equal-length vectors of integers. Calculate the pairwise differences using `Reduce` and output the first non-zero element using the tricky little `w[!!w][1]` form at the end. Outputs `-1`, `NA`, `1` for less, equal, greater. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~18~~ 17 bytes *1 byte saved thanks to @Adám for using `⍤1` instead of `∘↑(...)¨` and by changing the input format from a nested array to a matrix* ``` (⍋-⍒)(⍎¨∊∘⎕D⊆⊢)⍤1 ``` [Try it online!](https://tio.run/##ZU5LCsIwEF17kjZghySkNtl7kYLUTUG3XqCUSsUKgmtx0XP0KHORmDafRoRMeJ@ZxyvPdXa4lPXpqHWFzT3F/pph/yAG3KYR2w7bF96ee@wa7N4E@w/TGpuhMmYzTGOabhOeEPOzhJDNTBlQoH@SFazlRQ7C3c4w2maQ7wqpghfdMJ/EoxyvsXzdlECFlSUIrxZAXUAB8qcwRB3p/EK@pZQtLrW7wbNkQUEU3EWJuLpSCswshsPrCadzX@myHDPmFw "APL (Dyalog Unicode) – Try It Online") Takes the input as a matrix of chars as the right argument, where each version string is on its own row. Outputs `¯1 1`, `0 0`, `1 ¯1` for `<`, `=`, `>` respectively. `(⍎¨∊∘⎕D⊆⊢)⍤1` on each row * `∊∘⎕D⊆⊢` group all occurrences of digits, that is, split on `.` * `⍎¨` and convert each of these occurrences to a number `↑` convert to a matrix, where the first input is on the top row and the second one in the bottom, padding with `0`s where necessary `(⍋-⍒)` and * `-` subtract + `⍒` the indices into the rows which would sort them in descending order + `⍋` same as the top but for ascending order [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~63 47~~ 22 bytes ``` {"v$^a cmp v$^b".EVAL} ``` [Try it online!](https://tio.run/##XY/RaoMwFIbv8xQHGUPZOD0JaY2oZbvY3e4Gu7EObFEY1FWqDIrYV3dJY8K2YODjy5/jn64@Hzdze4H7BvJ5DL7vPio4tB1o2Af48v78Os0p04Gnoe6HHnI4fn7VPbZVF454OLX7cLV7e1hFU5Qy1pzOLjgygL66QBNiQeUjFryMrsFuCK5YiDJl0yzALe5pyzgS0j@bG@uy/txYgVJYq4m7CRzXm1glN2uzmbHkJohffxPe8rXPKiRprULpOsRIy4gY1d@@aPrpTeYTeoIl0o3Int@yjox1r8uYdCVB@r5bliQJ6q15IX0jY4JMN6V5IZP9AQ "Perl 6 – Try It Online") Turns out that Perl 6 has a [version type](https://docs.perl6.org/type/Version) that pretty much fits the description. This is an anonymous code block that takes a list of two version strings and returns either `More`,`Same` or `Less`. ### Explanation: ``` { } # Anonymous code block " " # Create a string of code v$^a cmp v$^b # Comparing the two versions .EVAL # And EVAL it ``` ## Or, without built-in types for 47 bytes: ``` {first +*,[Z<=>] map *.split('.')[^@_.ords],@_} ``` [Try it online!](https://tio.run/##XY/dioMwEIXv8xRDL1ptZZoEWxV/8B32bq1bursKglYx3ixiX91Nqgm7DRk4fHNmctIVfX2emx/YlhDPY1n1YoDD3sneozjJobl1sEfR1dVg7XBnZx/pFdv@W@ROep3UXDoUYhAQQ13dC4FywBrxq20@rePl7XC0Jzsk4qZ9ISFl2@uhkQCoXmlhRnMHMGO5/dhchs0DM56HZJo56MOMSghDivSFxopqr@krytHlC5WK6Q0MT2fPD5508UaKUr2B/3mNG8pOxusjdRfqo6szeEjXFR76//OiyieLqsvlhkVRmYgu/adXK0X17yLi6pDgmrwJCYIAZUm9KjkREU5VNl/qVSnvLw "Perl 6 – Try It Online") Anonymous code block that takes two strings and returns `More` if the second is greater, `Less` if the second is smaller and `Nil` if they are equal. ### Explanation: ``` { } # Anonymous code block map *.split('.') ,@_ # Split both strings by '.' [^@_.ords] # Pad the lists by a lot [Z<=>] # Zip the strings with the <=> operator first +*, # Get the first value that when coerced to an int, is not 0 ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~49~~ 40 bytes ``` +0|{~c[H,".",T]hị;T|ị;0|0}ᵐz{h-0&t↰₀|h-} ``` ...It's still rather unimpressively lengthy. Expects a list of two strings. Uses `positive number / zero / negative number` as `> / = / <`. [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/X9ugprouOdpDR0lPSSckNuPh7m7rkBoQaVBjUPtw64Sq6gxdA7WSR20bHjU11GTo1v7/H61kYKAHQoZKOkpACggNlWL/BwEA "Brachylog – Try It Online") ## Explanation **Splitting the inputs** Given an input that does not unify with `[0, 0]`, such as `["1.02.0", "1.2.0.1.0"]`, the below segment outputs, e.g., `[[1, "02.0"], [1, "2.0.1.0"]]`. ``` # unify the input with... +0 # : a list whose sum = 0 (output is 0) |{ }ᵐ # : OR a list that when mapped... ~c # : : if the input string unifies with a list of the form... [H,".",T] # : : : e.g. "1.02.0", H = "1", T = "02.0" hị # : : : coerce the head to an integer ;T # : : : append the string T # : : : "1.02.0" -> [1, "02.0"] |ị # : : OR it unifies with an integer ;0 # : : : append 0 # : : : "1" -> [1, 0] |0 # : : OR it unifies with 0 # : : : 0 -> [0] ``` **Comparing the inputs** Given, e.g., `[[1, "02.0"], [1, "2.0.1.0"]]`, zips the sublists into `[[1, 1], ["02.0", "2.0.1.0"]]` and compares the values in the head (`[1,1]`). Recur on the second sublist. Note that the zip predicate `z` cycles through shorter lists so that zipping with `[0,0]` is equivalent to zipping with `[0]`, hence the previous step unifies `0` with `0` without further values appended. ``` z # zip the sublists { } # unify the result (r) with... h # : take the head of the result - # : : subtract the second value from the first 0 # : : if the difference unifies with 0... &t↰₀ # : : recur on the tail of r |h- # : OR unify with the difference of the elements of the head # : (equivalent to returning early) ``` [Answer] # JavaScript (ES6), ~~73~~ 68 bytes *Saved 5 bytes thanks to @redundancy* Takes input as `(a)(b)`. Returns \$0\$ for *equal*, a positive integer for *greater than* or a negative integer for *less than*. ``` a=>b=>(a+[...b].fill`.`).split`.`.some((x,i)=>d=~b.split`.`[i]-~x)*d ``` [Try it online!](https://tio.run/##hZDRboIwFIbv9xTkXLXbPLZNHZCsvIgxEQRMF2bNMItXvjprKYJTqwSSnvTr35/vK//N282P3h9mO1NWXa26XGWFykj@tkTEYoW1bpo1rim2@0Yf7Apb810RcnzXVGWlOhXjzlKvZqcjfS27jdm1pqmwMVtSExAQDQ8lwKeBRvN5lL1c0RwZMgjQ6g4NU/Z0NEQLlH0dOgz9BcEmHBcfcZLCQF9mf96hhyqehid/KS5pvnicnSCTo5MEJTxyEiPjo8EYE3juG51Hb5C5V0Cgid9mVpulmT8KwezzduRp/q/JTbY8G3a0vPJ9k52mKdoPenoY7A2BbMGcw8QB4zD17v4A "JavaScript (Node.js) – Try It Online") [Answer] # [Java (JDK 10)](http://jdk.java.net/), ~~201~~ ~~96~~ 89 bytes ``` java.util.Comparator.comparing(java.lang.module.ModuleDescriptor.Version::parse)::compare ``` [Try it online!](https://tio.run/##bVNNa@MwEL33VwyGELukg2zSxnGaXnavPRX2UnLQOnKqrL@QZMNS8tuz@nKd2gsWHs1782YGzZxpTx/Oxz9XXrWNUHDWd@wUL7Ho6lzxpsb73V3b/S55DnlJpYRXymv4vAPgtWKioDmDX0xITf3RVC0VXDYOtwzIrZOFb0rw@gQlK9QK/EXw04eKdpp70cdnkYoq/esbfoRK5/KR7weg4iQjLz1P2c88@@vYjnNT1Qh0FWnJ0MIlrU9YNceuZPhqfz@ZzAVvDdenyTIdIVmUZb6d685WMZSmi1NMKgl7Xx7AJwRJsIIgDuCyGn0xEiTOP3Fbp0UnAQmunZKxZnIxPj5t0u1AmEXHXjiZyXogfpzGpEjWFktx/R3aIHF6G0z/0xeObRDzTXI6J4kNhTj@hGBdFp0g68Qpr@ctbrdb1Meg3pwGJ8S0lDppfwnsyOnBcw9ZNGKcM/OUmXvQ6Os93/5KxSpsOoWt5qkiDBYxkbDIYfGgjUWt1U3MOzms/NSbKQxnc4nDSnyxrREfomg0XVkXvxp@J/IPKm6lzX71Q4m8gLCHZyARCKY6UcPyebm7gV5uoRcPDff90q3h5foP "Java (JDK 10) – Try It Online") Returns a negative number if the first version is smaller than the second one, a positive one if the first version is greater than the second one and `0` if they're equal. Yep, that's some heavy work to "just" call a built-in! ## Credits * -14 bytes, thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) [Answer] # [Python 2](https://docs.python.org/2/), 87 bytes ``` lambda*p:cmp(*zip(*map(lambda x,y:(x or 0,y or 0),*[map(int,u.split('.'))for u in p]))) ``` [Try it online!](https://tio.run/##XZHbboMwDIavt6fIXRIUWSFKR0CjL8K4YKvQIhUatbQqe3mWExlMysmf/Tu2bObp@zKKpa8/lnM3fJ66zFRfgyHZj7bH0BkSMHqyuSJPdLkizmZ/UZY1LkCPE7vDzZz1RDBgSnvrvSM9ItNSShdn3tjEHg41DRaYIZy744hbhhqcAweeYJ2gR6svYQEyZHCvfZocDm@FKlev170nZ8wndhIRaX7YRSvg0jsUyM3vBfCQpgD1vwH4q5i7JTb5AuG@Wh6CN/JkxyuKZOxArq3E8LIswW5H4nMnE9xVrwKLRlS31euLudp5@XkQXB8x9Ho8kQdlPbHMTmv5BQ "Python 2 – Try It Online") Outputs -1,0,1 for <,=,>, respectively. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 54 bytes ``` \d+ $* +`^(.)(.*=)\1 $2 (.*=|^=.*)1.* < .*1.*=.* > \. ``` [Try it online!](https://tio.run/##LU3RCsIwDHzPXwgKXQchKZ1ridOf8HGMCfPBFxHx/2vSDpLcJXdcvs/f6/0oJ3dfcftoT2Xeejh66NfFYefQT93McAywuNuBO93RM3q4QEXd4AozQilBGBgJqaFUrixgVMnA7ozDeUy5HkxlMwazGeFBbwkpis4II5LqI6YWjHssWQVoSCzURKhTjEUNl1hf5JxRW3ZUMZC9SGrd2R8 "Retina 0.8.2 – Try It Online") Link includes test cases. Uses the separator value as the equality output, so for convenience the header converts the input separator to `=` but it could be anything not in `[.\d]`. Explanation: ``` \d+ $* ``` Convert to unary. ``` +`^(.)(.*=)\1 $2 ``` Repeatedly delete the first character from each side until they differ or one side runs out. This is much faster than trying to match prefixes, although possibly not golfier. At this point, the strings are in one of several forms, which need to be decoded to a comparison result. 1. If neither string contains a `1` then the result is `=` 2. If the left string starts with a `1` then the result is `>` 3. If the right string starts with a `1` then the result is `<` 4. If the left string is empty then the result is `<` 5. At this point the right string is empty so the result is `>` Another way of thinking about this is that if one string contains a `1` and the other does not start with a `1` then that string is greater, however that turns out to be a byte longer. ``` (.*=|^=.*)1.* < ``` Check for case 3, or case 4 without case 1. ``` .*1.*=.* > ``` If the left string still contains a `1` at this point then it is greater. ``` \. ``` Otherwise delete any left over `.`s. # Firefox Browser Console REPL, 19 bytes ``` Services.vc.compare ``` I believe this internal function performs the required comparison. It returns -1, 0, or 1. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~140~~ 134 bytes This code outputs a negative, `0` or a positive for `<`,`=` or `>` respectively. ``` i;n;p;q;g(char*s){for(i=n=0;*s&&++n&&*s-46;i=i*10+*s++-48);i=i;}f(char*a,char*b){for(p=q=0;*a+*b&&p==q;b+=n)p=g(a),a+=n,q=g(b);a=p-q;} ``` [Try it online!](https://tio.run/##bVLLboMwELznKyykUIzBshFJiBznJ3pMORhUUgvF4ZGeIr6d@kFoSItAuzuzM9jaLeNzWY6jZIo1rGXnoPwSXdjDe3XtAskVJyzsfR8h5fthH6dbJrkMKUFhj1CcZtDUbKicTkQ2FE7e8NbIBQoL3284b1mBuIINPwcCRkLnUavzAjLBm7hlw2jUoLxemnd5VoFUNyAhuK@AfmQVyAOBAHSft@9OgbfDG5sJzjXzIPgTcXxWHDUxrFbG9iKkCh7W9sxAnPJTkgM@gQDcvcSLPOoN0QxQTDD5BzSQpRZwglPrYJIXBcWb7S7bT@yLjjq/5MXNoXSz7M4wSQ2R4fQZ32FibXY4@3MBPJ@YmHfxHwcRqnniehesBQy1gNPEGqavV9nv91h/mpqypSwh5vSZdQRT8eAHN0M3SD2w2tVmrWq9VPWBbhhCNZyn5drM7ugRVoE41fmJ5JGNNIdsbms63VgF3pqSHqxLYOKH8iLwkPwuoEngRMwew2oYfwA "C (gcc) – Try It Online") # Edits: * Saved 6 bytes thanks to ceilingcat ! [Answer] # [Ruby](https://www.ruby-lang.org/), 75 bytes ``` ->a,b{c=d=0;c,d=[a,b].map{|f|f.slice!(/\d*./).to_i}while''<a+b&&c==d;c<=>d} ``` [Try it online!](https://tio.run/##XZHhaoMwFIX/@xSujNpu7jYJ6YyY@CJdGZpUJlgqtmOM6rO7G2NkmyRw/O7J9cTbfZbfY6XGl7yIy7tWRpFMx0Yd8PUI56K991VfwbWp9elhs3szT7Dbwu3yXg9fH3VziiJZPJfrtVbKZFqq3AzjioX@oYvKAwoEyD@qLPXepW4pA84cRUV9Bwr710SkE3VeaSnxHdivr7GF0v3iFUC4owK4z5AAmVskIP7mBZsPN7GLYQenCCYirj55vbLU304G3IcM@ZI3D9I0BdyoZ4UnZMCIzSZQz8p6V3Btm/q2ecR/Ps2i63EusVbdXIjCaJu14UHH1TSx4zD@AA "Ruby – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~105~~ ~~88~~ 80 bytes *-17 bytes from @redundancy. Wow!* *-8 bytes removing Math.sign. Thanks @tsh* Returns a negative, zero or positive value ``` f=(a,b,r=/(\d*).?(.*)/)=>a+b&&+((a=r.exec(a))[1]-(b=r.exec(b))[1]||f(a[2],b[2])) ``` [Try it online!](https://tio.run/##jZHfboMgFMav3VMYLxpo9QiETrxwe4Q9QNcLsNpsaWpj22UXfXcnf5olQmwTIEB@3zkfH9/yR57r/ut0yY7drhmGtkIyVWlf5ehzt8TwjmCJc1y9yZVaLFYIyaqH5repkcR4Q7cZUvcLZS5utxbJDdumalwwHurueO4ODRy6PWpRwpI0TmiCcRxFUZ7HH9fT9RLTlwlGgQAJoiSAGtAoHsMMuPWgd676nA8K69dClHcJmSiykMQZYk88kzmWrp@oLIBwgwvgIz370gKI9VGAmLDhtOE/SKKHdj/nxlKEag2xBR6laSHDe//qN@DMGuKB2D24LEsYp@bd1rPjd2BERyqsJ3eYNhr@AA "JavaScript (Node.js) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~16~~ 11 bytes *-5 bytes from @Shaggy* Outputs: * negative number for `<` * (`null` or `0`) for `=` * positive number for `>` --- ``` N®q.Ãy_r-Ãf ``` [Try it online!](https://tio.run/##y0osKPn/3@/QukK9w82V8UW6h5vT/v9XMtQz0jMxVOKCMIyUuHTTAQ "Japt – Try It Online") [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~116~~ 111 bytes ``` import StdEnv,Text ?s=map toInt(split"."s) $a b= @(?a)(?b) @[h:t][u:v]|h==u= @t v=h-u @l[]=sum l @[]l= ~(sum l) ``` [Try it online!](https://tio.run/##JYrBCoJAFEX38xUPa6GQUi2Dhy5qIbQIaicuXqYpzIzivBkKok9v0uJuzj33VrIm7VV/s7IGRZ32nRr6keHMt4N2q0v9YJEaVDQA97nm0Ayy4yAJTCSWBFeELEwpCtNrJLKi3XFZ2J0rXy2inTYGh21sRSaLEo1VIKdXKRHe4a9F/sw0sliA2wBCsEnWc4JZbH9ixkZPuBQ4w/RzW/@pGkl34@P86PdPTaqr/uUkiZt@VF8 "Clean – Try It Online") Outputs a negative number when the first argument is less than the second one, zero when they're equivalent, and a positive number when it is more than the second one. [Answer] # [Swift 4](https://developer.apple.com/swift/), 155 bytes ### Header (not counted: the code is non-recursive): ``` let f:(String,String)->Bool? = ``` ### Code ``` {let x:(String)->[Int]={$0.split{$0=="."}.map{Int($0)!}.reversed().drop{$0==0}.reversed()},a=x($0),b=x($1) return a==b ?nil:a.lexicographicallyPrecedes(b)} ``` [Try it online!](https://tio.run/##ZVLPa4MwFL73r8hCDwbcaxS7allaGOyw22DH0kNqYytkKtFtHeLf7hKj1naiJF@@H@89SfmTJlXQSlGhZO18VCrNTq5dyOPmJc/lFjHU1kZwGQSa2b1l1Z7VcwplIdNKbxjDgBv45EWtOWdOyUMDSnwLVYqjQ@Co8qKT0elx43J2MWL3YFaPzJSovlSGOGMHtM1SueYgxSWN85PixTmNuZS/70rE4ihK50CadjdzsI9dNDzYw8RdLEa80bwHFGivueeZ5ceEXjxqLO9D0Bex4Bpi8z1YPq3CSEs6fuJ/tvxYwPDTDqzfn/Le8t4fAg3G/kMIJgGmvxXQsYAG4f98PRLYKQ2g5u27MPn2gHomAlMrHjKM3x70@RNu6C/wrz8QB7fzG38URaC/TjKAIcX4fWomDLsaA7jW388gydUrj8@oRoW@geZ6uWjuabE2JD0iBDXtHw "Swift 4 – Try It Online") ### Explanations * We trim trailing .0. * We compare components numerically. ### Returned constants * nil for = * true for < * false for > [Answer] # JavaScript 64 bytes ``` a=>b=>(e=i=>(g=v=>v.split`.`[i]||0)(a)-g(b)||!a[i]-1&&e(i+1))(0) ``` [Try it online!](https://tio.run/##fZLRboMgFIbv9xSMiwayeALGTs2GyZ5jWVLbUsNiqhPnle/uENSqrTNqOJyP/5zzh@@0SfWpUmXtXYuz7C6iS0VyFAmRQpl/JhqRNKDLXNUHOHyqr7ZllKTUy8iRtu1zarY8vttJol44pYTRLtVaVjUSqJI/v6qSBLsdTN@e3IpcCPYxReNDMMfjmqIEsQXJgQEb6CUphLhnJ93x5DbrQzC0MURW/FEHHPavYRQb2JGj6vs9OTVgSbw9lb8g@X5TMwIW3OaPIMCb84fA@M2rECL8r6vg/LIR69/ejnV9l2G8lzWRO4cfabrMWN1Rj2cKfJhNH8wcXWvGcQzms/AU2SprTZ/1TkU2N0WzPk/FVRe5hLzICP7Ic1RLXWtU9gpnczm7Pw "JavaScript (Node.js) – Try It Online") With comments: ``` a=>b=>( // Main function takes arguments like ("1.2.42")("1.2.41") e=i=> // e(i) compares the ith number, returns >0, <0 or =0. ( g=v=>v.split`.`[i]||0 // g() returns the ith string or 0 )(a) // call g(a) -g(b) // subtracting g(b) from g(a) casts strings to integer || // If they are not equal return result now !a[i]-1 && // recursion limited to a.length, always sufficient e(i+1) // next i )(0) // Start with i = 0 ``` [Answer] # [Perl 5](https://www.perl.org/), 55 bytes ``` sub c{@_<2?sprintf"%9d"x9,split/\./,pop:-(c(pop)cmp c(pop))} ``` [Try it online!](https://tio.run/##xY/fboIwFMbv@xQnDBOalFoaVFDAmex6u9mlCVHsnPEfsxhdCM/OWqDE7QXW0PLrd76efs3F5TCq5XUNWV0@pxGfy/yyOxUf1iDcWPeQyPywK4ZLOiT5OZ@6TuaoP86OObSEq/rpcj1BIWQhIVtJIdHtc3cQTvSyeF8kuEQAx2/HXhF7TWxB7C2Om6YzVXA6wSm/bk4ErgcxMEjAw5WblLaoSNaexFjbTTR3LGHghhK6VdxzkRVio7ZcbbfnoqHlySLqhji2t3PrbW9NrVdVOe8tTB7izFCF0lSHTVP4t4F4j15PCfIoo@yPGmvVePu6Vjn1easq8kwHj47GkyBs1NYbaZWZDvzhNt6r3qj3BpT5rRpQ32SYUNa1mNDgd16q86nJ9MdVh5aYSsTaeuM1pFXzugj5JiT4fd4EhWFI1VTckToRIc50tkBxR423/gE "Perl 5 – Try It Online") [Answer] ## Burlesque - 17 bytes ``` wd{'.;;)ri}m[^pcm blsq ) "2018.08.1 2018.08"wd{'.;;)ri}m[^pcm 1 blsq ) "0.0.1 0.1"wd{'.;;)ri}m[^pcm -1 blsq ) "1.1.56789 1.2.0"wd{'.;;)ri}m[^pcm -1 ``` If you want output in '><=' then add `?i"<=>"j!!Q`. [Answer] # Powershell, 88 bytes Returns `0` for equal, a `positive integer` for greater than or a `negative integer` for less than. ``` param($a,$b)+(($x=$a-split'\.')+($y=$b-split'\.')|%{$x[+$i]-$y[$i++]}|?{$_}|Select -f 1) ``` Less golfed test script: ``` $f = { param($a,$b) $x=$a-split'\.' $y=$b-split'\.' $z=$x+$y|%{ $x[+$i]-$y[$i++] }|?{$_}|Select -first 1 +$z # convert $null to 0 } @( ,("2" ,"1" , 1) ,("1.0.0" ,"1" , 0) ,("1.0" ,"1.0.0" , 0) ,("1.2.42" ,"1.2.41" , 1) ,("1.1.56789" ,"1.2.0" ,-1) ,("1.10" ,"1.2" , 1) ,("1.20" ,"1.150" ,-1) ,("18.04" ,"18.4" , 0) ,("7.010" ,"7.8" , 1) ,("1.0.0.1.0" ,"1.00.00.2" ,-1) ,("00.00.01" ,"0.0.0.1" , 1) ,("0.0.1" ,"0.1" ,-1) ,("42.0" ,"4.2.0" , 1) ,("999.999" ,"999.999.1" ,-1) ,("2018.08.1" ,"2018.08" , 1) ) | % { $v1,$v2,$expected = $_ $result = &$f $v1 $v2 "$([Math]::Sign($result)-eq$expected): $result" } ``` Output: ``` True: 1 True: 0 True: 0 True: 1 True: -1 True: 8 True: -130 True: 0 True: 2 True: -1 True: 1 True: -1 True: 38 True: -1 True: 1 ``` [Answer] # [Dart](https://www.dartlang.org/), ~~277~~ 231 bytes ``` F(s,{t}){t=s.split('.').map(int.parse).toList();while(t.last<1)t.removeLast();return t;}f(a,b,{d,e,f,g,h,i=0}){d=F(b);e=F(a);g=d.length;h=e.length;f=h>g?g:h;for(;i<f;i++)if(e[i]!=d[i])return e[i]>d[i]?1:-1;return h>g?1:(h<g?-1:0);} ``` [Try it online!](https://tio.run/##dVPJboMwEL33K1ypkm3VGdmINiQOyak99Q8QB7cYsJRNYNoD4ttTs5SQJkEwzPJm3vBkElXY0@mdlKy2Da1tWEJ53BpLMGAKO3UkZm/hqIpSU7CHD1NaQuVPbraaWNiq0q4EtVDo3eFbf6iuWmhbFXtkZZMSxT5ZnTDNUpaxnJmQO5YkfCefVGr3UlRmYQJbvc9sLvNQ/7lpmK@zTbZ03qEg0qxSaZ6fqUmJjkz8GCbO0oGpzazbxEYsZ@KPv@0XS5Kvss1MLDmVzWmnzJ7Q@gGhb1Ugi0IUOR@hCHsYDRdDWIxBH8VsQAngwPFNFL9A4XP32HKF8sDvaDuUCwS@xSjg5XUeLPCAOs@aXcLOBQfDd9b3pijxcmdYANwfdwnAx7e@cg5cjFrMIcD3FYNWkV4L3t5uvX@UfZ6LrsD7Hnw1bEz3KDGhnA7zpyr5F5pNUIvFAtyDu/wQgLjazOOtHIGruMIQnDdzoFg@OGvBHdM39ZUTUnUHDKFj4X4dgp/qlFQRj1kViZg2KFyjp7qKvLjBVDpg42xz@gU "Dart – Try It Online") * -44 bytes by using variables to store length and using ternary in loop * -2 bytes by removing the for brackets [Answer] # [Swift 4+Foundation](https://developer.apple.com/swift/), ~~160 bytes (142+18)~~, 155 bytes (142+13) ### Import (13 bytes, including `;` to separate from the code): This will import Foundation, but is 5 bytes shorter than `import Foundation`. ``` import UIKit; ``` ### Header (not counted: the code is non-recursive): ``` let f:(String,String)->ComparisonResult = ``` ### Code (142 bytes): ``` {var x={($0 as String).split{$0=="."}.count},a=$0,b=$1 while x(a)<x(b){a+=".0"} while x(b)<x(a){b+=".0"} return a.compare(b,options:.numeric)} ``` [Try it online!](https://tio.run/##bVLdaoMwGL33KULwwrAsjWJXLbU3Y3uA7XLsIna6BqxKjGtBfHaXNCZ1P6LIyfn5zid2Z17KeOKnthESPDd9/cEkb2qvKiQot8GrFLz@xOaF7vePzallgndN/VJ0fSVBBqbhiwlwyYbAp4B1YNaSrq24HHyaZZDAkRxUthwxy3yK88wPvfORVwW4BAztLkGOBnanhBSOjsg1wdCQW0IUshc1YCpLtyiCHDetbtttSd2fCsEPaJzevABGEAN7wRAivFo5vFd8SKhKxP/ymeFdwix2GsNHJJ6HGHALMfkhWT9sklRJrvzCvzO8G6D5ZQPjj5Z8uP7tTwiNXf@ExIsA3W9DqBugQPI3X61EzJYaUH3PLXS@OaChjoDUiG2G9puDOX/B2X5xdPuAMP65v/anaUrUc5VYYFO0P6J6w@Q6w4Lb/HePlI14YocjGECr/japfj0M/FCJlaGcEUJgnL4B "Swift 4 – Try It Online") ### Explanations 1. We append some trailing .0 for same number of components. 2. We compare components numerically. ### Returned constants * ComparisonResult.orderedSame for = * ComparisonResult.orderedAscending for < * ComparisonResult.orderedDescending for > [Answer] # [Zsh](https://www.zsh.org/), ~~54~~ 50 bytes ***-4 bytes** by using `$@` instead of `$1\ $2`* ``` eval {autoload,}' is-at-least $'{@,2\ $1}';<<<$?;' ``` ~~[Try it online!](https://tio.run/##qyrO@P8/tSwxR6E6sbQkPyc/MUWnVl0hs1g3sUQ3JzWxuERBRb3aMEZBxUjHCEga1qpb29jYqNhbq////99QzwAIgSSIZQBCRgA "Zsh – Try It Online")~~ [Try it online!](https://tio.run/##XY/NaoQwFIXX5ikugxCFMSTBqb@l3ZRuCt111U1sIjMgE1DbRcVnt9GYTJlLAifHLyfH3@G8tFEcLepHdDCJ71F3WsjjjOEyJGJMOiWGEUI8PR/5J4RsxlVd1@FThZcYoVb3IKABCREKOLhhXr2igBFK6J39stmO9sBmc5JyaxvFfAgjp4csLzbb0m@bTV0I//8k9zY73eic0NTaOUl9k4zQPSUj@V1vstY0m66LryFWUlOMWsDSTq62@09Dp64spL63oYuiIGabw67MHUNzulbMzWFXGx1XIDUK1NdZw@FD9cNFX4cSwinqS0bLWMw33cwHR773UvUmwJDSmThxg1HQQiggbNynRzcYSX1Vyx8 "Zsh – Try It Online") This `eval`s to the following eight statements: ``` autoload is-at-least $@ # loads the "is-at-least" function <<<$? # success, prints 0 autoload is-at-least $2 $1 # redundant <<<$? # success, prints 0 is-at-least $@ # exits 1 if $1 < $2 <<<$? is-at-least $2 $1 # exits 1 if $2 < $1 <<<$? ``` So the three unique values are: ``` cmp | value -----+------------------------------------------ = | 0<newline>0<newline>0<newline>0<newline> < | 0<newline>0<newline>1<newline>0<newline> > | 0<newline>0<newline>0<newline>1<newline> ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ṣ€”.Vz0I¬ÞḢ ``` [Try it online!](https://tio.run/##XY@xCsIwEIb3PoWDi8txCdGm0HYXnH0DF3Fw1UldHNwUxEFFdHVUsXSr6HukLxIvpglqyMHPd/9d/vR7g8FIa5Wdytm5nOygO8Z2cX7s1f2oVX4prkk5vdWfq2FdZevOa/6Yq@yg8kU52cZpQhON51JlG615zR3mVRowQMA/mhjqvL5vKAfBLSXF3AYGzVYoow@13thQdBv412vcU9b0XgkoLJUgXIYQsFoRgvzNCyYfFZrLaYNVSInQ9j9epwx1v4sD4ULWhM@bBlEUARXpStFEHHA02STpShnvGw "Jelly – Try It Online") May be stretching the rules a little, but going by [this](https://codegolf.meta.stackexchange.com/a/11884/66833) I/O default, it's allowed. This uses the output presentation: > > Use positive number / zero / negative number, while zero means equal; > > > but the output is wrapped as a singleton array ## How it works ``` ṣ€”.Vz0I¬ÞḢ - Main link. Takes a pair of versions [a, b] on the left € - Over each: ṣ ”. - Split on "." V - Evaluate each numeric string to a number z0 - Transpose, filling with 0s I - Take the differences of each pair ¬Þ - Sort by logical NOT This shuffles 0 to the end and preserves the order of everything else Ḣ - Take the first element ``` [Answer] # [Perl 5](https://www.perl.org/) `-plF\.`, 50 bytes ``` @b=<>=~/\d+/g;1while@F+@b&&!($_=shift@F<=>shift@b) ``` [Try it online!](https://tio.run/##K0gtyjH9/98hydbGzrZOPyZFWz/d2rA8IzMn1cFN2yFJTU1RQyXetjgjM63Ewc3G1g7CStL8/99Qz0APiLmg9L/8gpLM/Lzi/7oFOW4xegA "Perl 5 – Try It Online") Takes input on two lines. | Output | Meaning | | --- | --- | | 1 | First version is greater | | 0 | Versions are equal | | -1 | Second version is greater | ]
[Question] [ *This is a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge the Robbers' Thread can be found [here](https://codegolf.stackexchange.com/questions/111191/anagram-quines-robbers-thread)* Your challenge is to write a program that outputs an anagram of its source code but not the original source code itself. For example the following Python program, ``` print`'print*2``'*2` ``` prints ``` 'print*2``print*2``' ``` which has all of the same characters as its original source but in a different order. Once you have found such a program, include the output of the program as an answer omitting the program that generates it. As you might have guessed, robbers will seek to discover the program you have hidden, or any program that fits the specifications. Your goal is to make the shortest program that the robbers cannot crack. ## Rules * As with most [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenges, if your answer remains uncracked for a week you may add the intended solution to your answer and mark it as **Safe**. Once safe an answer cannot be cracked by robbers. * You do not need to include the language of the intended solution, however if you do not include the language robbers can crack it in any language predating the challenge, while if you specify the language they may only crack it in the one provided. * Standard rules for Quines apply. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 231 bytes [Cracked by Wheat Wizard](https://codegolf.stackexchange.com/a/111590/57100) ``` }{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{][][][][][][][)()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()( ``` The original program uses the `-A` argument. Here are the counts: ``` ( -> 74 ) -> 74 { -> 34 } -> 34 [ -> 7 ] -> 7 ``` [Answer] # Python 2, 96 bytes, [cracked by math\_junkie](https://codegolf.stackexchange.com/a/112046/21512) Output: ``` B97.off]xo) wnd[ri0'of{r1({r6-{r{rri) {r1(xo0'sjD;0'0'qhF=1({r{r2)4+}twnri2)wnlcof) yp) ) xomd2) ``` First time code golfing! Hope it's not too easy. [Answer] # Haskell, 107 bytes, [Cracked by nimi](https://codegolf.stackexchange.com/a/111238/56433) ``` "$$$$'''''''',,----....::<<<<<<<<========>>>>[[[[[[[[]]]]]]]]aaddddddddddddiiiiiiiiiiiimmnnnnpprrtt||||||" ``` There is an additional trailing newline. --- **Original solution:** ``` main=print$id=<<[[id|i<-"main=print$id=<<[[id|i<-,i==d]>>d:[d]|d<-['$'..'|']]",i==d]>>d:[d]|d<-['$'..'|']] ``` [Try it online!](https://tio.run/nexus/haskell#@8@Vm5iZZ1tQlJlXopKZYmtjEx2dmVKTaaOrhEtCJ9PWNiXWzi7FKjoltibFRjdaXUVdT0@9Rj02Vgmf5P//AA "Haskell – TIO Nexus") My main idea was to write a quine which sorts its own source code before outputting it without using a library `sort` function. Only after an initial cracking try by [nimi](https://codegolf.stackexchange.com/users/34531/nimi) it occurred to me that the program code could be manually sorted, hard coded into the program and then printed out while doubling each letter. However the limited available characters make this approach more cumbersome and nimi's successful crack is quite similar to my original program. **Explanation:** ``` main=print$ -- full program which prints the following string id=<<[[id|i<-"...",i==d]>>d:[d]|d<-['$'..'|']] |d<-['$'..'|'] -- for each char d in "$%&'()*+,-./012 ... xyz{|" [id|i<-"...",i==d] -- build a list with as many elements as d is contained in the string >>d:[d] -- replicate the string "dd" as often as the previous list is long id=<<[ ] -- concatenate the resulting list of srings to one single string ``` [Answer] # Unspecified langauge, 124 bytes, In the theme of DJMcMayhem's answer this is the first 32 ASCII characters (aside from `0x00`) printed four times each. Since none of these are visible, I have not included the actual code in my answer. Here is the hexdump: ``` 00000000: 0101 0101 0202 0202 0303 0303 0404 0404 ................ 00000010: 0505 0505 0606 0606 0707 0707 0808 0808 ................ 00000020: 0909 0909 0a0a 0a0a 0b0b 0b0b 0c0c 0c0c ................ 00000030: 0d0d 0d0d 0e0e 0e0e 0f0f 0f0f 1010 1010 ................ 00000040: 1111 1111 1212 1212 1313 1313 1414 1414 ................ 00000050: 1515 1515 1616 1616 1717 1717 1818 1818 ................ 00000060: 1919 1919 1a1a 1a1a 1b1b 1b1b 1c1c 1c1c ................ 00000070: 1d1d 1d1d 1e1e 1e1e 1f1f 1f1f ............ ``` Here however is some Python that prints it (and a newline) if you would like: ``` print"".join(chr(x)*4for x in range(1,32)) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 32 bytes, [Cracked by math\_junkie](https://codegolf.stackexchange.com/a/111860/47120) ``` J+J=JJ 1-2#pTN%"J+J=JJ 1-2#pTN%" ``` Original solution ``` J2#p+"J+J=JJ 1-2#pTN%"N=J-J1 %TJ ``` [Try it online!](https://tio.run/nexus/pyth#@@9lpFygreSl7WXr5aVgqAvkhfipKvnZeul6GSqohnj9/w8A "Pyth – TIO Nexus") ``` J2 # Assign 2 to the variable J # # Infinite loop, break on error +"J+J=JJ 1-2#pTN%"N # appending a '"' to the string 'J+J=JJ 1-2#pTN%' p # print the string above =J-J1 # subtract 1 from J and assign back to J %TJ # calculated 10%J, with a blank space before to supress output, # on the 3rd iteration this will be 10%0 that will generate an # erro and will break out the loop ``` [Answer] # CJam, 46 bytes, [cracked by math\_junkie](https://codegolf.stackexchange.com/a/111951/53880) ``` 3658:93]93]]]95_959599c101101$::]]]]]]____ccee ``` [Answer] # [V](https://github.com/DJMcMayhem/V), 21 bytes (Safe!) ``` "&./124ipq|ÍÓÚîñòÿ ``` Note the leading newline. Since this contains unprintables, here is a hexdump: ``` 00000000: 0a16 1b22 262e 2f31 3234 6970 717c cdd3 ..."&./124ipq|.. 00000010: daee f1f2 ff ..... ``` To help people out some, here is a link to the [Standard extensible V quine](https://codegolf.stackexchange.com/a/100426/31716) --- Here is the original version: ``` ñi241"qp|Ó./ò& ÚÍîÿ ``` [Try it online!](https://tio.run/nexus/v#AR8A4P//w7FpFjI0MRsicXB8w5MuL8OyJgrDmsONw67Dv/// "V – TIO Nexus") The readable version is: ``` ñi<C-v>241<esc>"qp|Ó./ò& ÚÍîÿ ``` The way this works is by embedding *sort* into the default extensible quine. As I was thinking about V-quines because of this answer, I realized that the standard extensible quine can be shortedn by three bytes, so this solution could have been: ``` ñiéÑ~"qp|Ó./ò& ÚÍîÿ ``` Explanation: ``` ñi<C-v>241<esc>"qp " Standard V-quine. Everything after this is recorded into register 'q' " so we can do whatever we want without ruining it's "quine-ness" | " Go the first character on the line (I just realized now that this is pointless) Ó./ò& " Put every character on a newline Ú " Sort every line Íî " Join all lines together ÿ " Necessary for V-quines ``` [Answer] # Unspecified language, 254 bytes [Cracked by @Dennis!](https://codegolf.stackexchange.com/a/111207/31716) I doubt this will win for brevity, but it'll be a pain to crack, so it's still worth making. Due to a bug, the order of `0x0b, 0x0c, 0x0a` got a little bit mixed up, but this is definitely the real output. I figured I wouldn't specify the language just so I could see what different languages this is possible in. Since the output is mostly non-ASCII, here is a hexdump of the output: ``` 00000000: 0102 0304 0506 0708 090b 0c0a 0e0f 1011 ................ 00000010: 1213 1415 1617 1819 1a1b 1c1d 1e1f 2021 .............. ! 00000020: 2223 2425 2627 2829 2a2b 2c2d 2e2f 3031 "#$%&'()*+,-./01 00000030: 3233 3435 3637 3839 3a3b 3c3d 3e3f 4041 23456789:;<=>?@A 00000040: 4243 4445 4647 4849 4a4b 4c4d 4e4f 5051 BCDEFGHIJKLMNOPQ 00000050: 5253 5455 5657 5859 5a5b 5c5d 5e5f 6061 RSTUVWXYZ[\]^_`a 00000060: 6263 6465 6667 6869 6a6b 6c6d 6e6f 7071 bcdefghijklmnopq 00000070: 7273 7475 7677 7879 7a7b 7c7d 7e7f 8081 rstuvwxyz{|}~... 00000080: 8283 8485 8687 8889 8a8b 8c8d 8e8f 9091 ................ 00000090: 9293 9495 9697 9899 9a9b 9c9d 9e9f a0a1 ................ 000000a0: a2a3 a4a5 a6a7 a8a9 aaab acad aeaf b0b1 ................ 000000b0: b2b3 b4b5 b6b7 b8b9 babb bcbd bebf c0c1 ................ 000000c0: c2c3 c4c5 c6c7 c8c9 cacb cccd cecf d0d1 ................ 000000d0: d2d3 d4d5 d6d7 d8d9 dadb dcdd dedf e0e1 ................ 000000e0: e2e3 e4e5 e6e7 e8e9 eaeb eced eeef f0f1 ................ 000000f0: f2f3 f4f5 f6f7 f8f9 fafb fcfd feff .............. ``` That is every single ASCII character except for `0x00` and `0x0D` because they both caused strange behavior on TIO. Have fun cracking! >:D --- The original code was in V. [Try it online](https://tio.run/nexus/v#BcGHNxQAAAfgF6HoJSEilAgVUrJnU8koqezQLnvvcfusc9s6@87eh7sz3vv9/rDr@@zccnC86OTscumy25Wr7tc8rnt6ed/w8b3p538rIDDo9p3guyGh98LCI@4/eBgZFf0o5vGT2Kdx8QmJSckpqWnpGZnPnr94@ep11pu32e9ycvPy33/4WPjp85ei4pLSsvKKr5VV1d@@//j56/efv/9qauvqGxqbmlta29o7Oru6e3r70I8BDEIAIUQQQwIpZJBjCMMYwSjGoMA4lFBBDQ200EGPCUxiCtOYgQGzmMM8FrCIJSzDCBNWsIo1rGMTW9jGDnaxh30cwIxDHOEYFlhhwwlOcYZz9nOAgxRQSBHFlFBKGeUc4jBHOMoxKjhOJVVUU0MtddRzgpOc4jRnaOAs5zjPBS5yics00sQVrnKN69zgJre5w13ucZ8HNPOQRzymhVbaeMJTnvHctQAbF@z2/w) Hexdump: ``` 00000000: ee02 0304 0506 0708 090b 0c0e 0f10 1112 ................ 00000010: 1314 1516 1718 191a 1b1c 1d1e 1f20 2122 ............. !" 00000020: 2324 2526 2728 292a 2b2c 2d2e 2f30 3132 #$%&'()*+,-./012 00000030: 3334 3536 3738 393a 3b3c 3d3e 3f40 4142 3456789:;<=>?@AB 00000040: 4344 4546 4748 494a 4b4c 4d4e 4f50 5152 CDEFGHIJKLMNOPQR 00000050: 5455 5657 5859 5a5b 5c5d 5e5f 6061 6263 TUVWXYZ[\]^_`abc 00000060: 6465 6667 6869 6a6b 6c6d 6e6f 7071 7273 defghijklmnopqrs 00000070: 7475 7677 7879 7a7b 7c7d 7e7f 8081 8283 tuvwxyz{|}~..... 00000080: 8485 8687 8889 8a8b 8c8d 8e8f 9091 9293 ................ 00000090: 9495 9697 9899 9a9b 9c9d 9e9f a0a1 a2a3 ................ 000000a0: a4a5 a6a7 a8a9 aaab adae afb0 b1b2 b3b4 ................ 000000b0: b5b6 b7b8 b9ba bbbc bdbe bfc0 c1c2 c3c4 ................ 000000c0: c5c6 c7c8 c9ca cbcc cdce cfd0 d1d2 d3d4 ................ 000000d0: d5d6 d7d8 d9da dbdc ddde dfe0 e1e2 e3e4 ................ 000000e0: e5e6 e7e8 e9ea ebec edef f0f1 f2f3 f4f5 ................ 000000f0: f6f7 f8f9 fafb fcfd feff 0a53 ac01 ...........S.. ``` Basically, everything up to the `S` just inserts garbage into the buffer. The `0xEE` at the beginning is just to insure that everything after the newline doesn't happen in part of a loop or macro. Then, we do ``` ¬<C-a> "Insert every character in the range 0x01-0xFF ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 91 bytes ``` a=['111111111123666667eeegggkkknnszEEGn};:;:']; ''''''''''(),,,,,-[[[]]]aaaddip;;=ds1010]); ``` [Answer] # PHP, 130 Bytes (Safe) ``` $$$$$$''''(((((((()))))))),,22;;;;;;<<==??\\\\____aaccddeeeeeeeehhhhiiiillllmmoooooopppppppppprrrrrrrrssssssssttttttttttvvvvvv ``` ## Original Solution I could not understand that it was not cracked ``` <?php $v=str_split(str_repeat('<?php\ $v=str_split(str_repeat(\'\',2));sort($v);echo\ implode($v);',2));sort($v);echo implode($v); ``` [Answer] # Guess, 43 bytes ``` {4"2)4q):)u(4o'{4t:q(e)(",(t22(u()o)?,?'2e ``` It was a tough call whether or not to share what language it was, but I think this option is better. Note that there's a trailing newline. ]
[Question] [ Consider an eight bit number in which an even position bit will never be 1 if one of its neighbors is 0 (considering MSB and LSB as neighbors). There are fewer than 64 such numbers, so there is at least some reversible mapping of them to 6 bit numbers. Your task is to write a pair of functions (or code blocks or your language equivalent), one of which takes an 8-bit number and returns a 6-bit number, the other which reverses the process. "Numbers" here can be literal numbers or a list of booleans or even a string of Xs and Os. Put another way, the following bit patterns will never occur: ``` ......01 .....10. ....01.. ...10... ..01.... .10..... 01...... 0......1 ``` PS: I'd really love to see an answer in Lua :) PPS: Bonus imaginary internet points if you can pack the 47 valid values into a 6-bit number with a maximum of value of 47 [Answer] # [Python](https://docs.python.org/2/), 60 bytes ``` l=[n^170for n in range(256)if n&n*2<1] l.index,l.__getitem__ ``` [Try it online!](https://tio.run/##dZFNboMwEIX3nGJWFW6tKPgPiMpJEEVUAWLJcSKgFT09nUcXUaV24c8z4/fssX3/Wi63qLYtVHV8y/LjcJsoko80dXHsU2Wd8APFp/isXrMmGeRYhYOP536V4dC2Y7/4pb@27fbZBX9u48d1porqoyQlqZCUcZQZSZpTzbPh3HBsnCSLwRrHeaYg1lDrDHDAXiuxAyRGMxwku8PtKSQ5ajlsuQEso0BUYJciZ5SQlCxRygAO4AWFxhQ6U9oCBcBHKoPI4iIWNguJtU1yn3xcKPQxfVxZJEk3z/20UBdCWg/pKh5v6IwgPOuK0sPTiF@eMYVLVNX6j/iP6umnl3cf8VEvq6j1qdm@AQ "Python 2 – Try It Online") `l.index` compresses and `l.__getitem__` decompresses. We just make a list `l` of all valid patterns as 8-bit numbers, except we ignore wrapping around, which still leaves 55 options which fits in 6 bits. A useful idea is that if we flip the bits at even positions, which `^170` does, then the condition just becomes "no two 1's are (cyclically) adjacent". This is easy to check without wrapping around using the bit condition `n&(n*2)==0`, or shorter, `n&n*2<1`. **Fibonacci numbers** Binary strings with no adjacent ones have interesting connections to Fibonacci numbers. The number of such 8-bit numbers is 55, a Fibonacci number, [following the general result](https://math.stackexchange.com/questions/2476409/determining-the-number-of-bit-strings-of-length-n-that-contains-no-adjacent-0s). Moreover, [Zeckendorf's Theorem](https://en.wikipedia.org/wiki/Zeckendorf%27s_theorem) tell us that each number can be uniquely expressed in the Fibonacci base without using a pair of adjacent ones, that is as a sum of distinct Fibonacci numbers without two consecutive ones, as these can be merged into the next Fibonacci number. Perhaps a base conversion to the Zeckendorf Representation can be used for a less brute-force answer than the one here. We've had challenges to convert [from](https://codegolf.stackexchange.com/q/173601/20260) and [to](https://codegolf.stackexchange.com/questions/2677/the-minimum-fibonacci-challenge?rq=1) the Zeckendorf representation, which could be used as the basis of a decoder-encoder pair. **Bonus: 64 bytes** For imaginary internet points, we can tweak the algorithm to accounts for cyclically adjacent ones, so as to limit the compression to 48 valid bit patterns from 55. We do this by modifying the bit check to `n&n*2%255<1`, at the cost of 4 extra bytes. *64 bytes* ``` l=[n^170for n in range(256)if n&n*2%255<1] l.index,l.__getitem__ ``` [Try it online!](https://tio.run/##dZFNboMwEIX3nGI2rXBrRcF/kKicBFFEFSCWHCcitKKnp/PoglZqF3yeGb83Hpvb53S@RrUsoazia5bv@@tIkXyksY1DlyrrhO8pPsYn9aCsfcnqpJdDGXY@nrpZhl3TDN3kp@7SNMtHG/ypie@XO5VU7SUpSYWkjKPMSNKcal4N54Zj4yRZfKxxnGcKYg21zgAHrLUDOkBiNMNBsjrcmkKSo5bDlhvAMgpEBboUOeMAyYElShnAAbyhMJjCZEpboAD4SGUQWVzEwmYhsbZObqOPE4UuptuVxY9qEEnS3u/dOFEbQlr16Sy2R3VGEN55RmlrUItfniGFS5Tl/I/4j@rxe4Q3H/HnnmdR6WO9fAE "Python 2 – Try It Online") The modulo 255 changes the bit-shift `n*2` to a cyclic shift ``` abcdefgh -> bcdefgha ``` by moving the post-doubling place value of `256*a` to just `a`. This is, except for `n=255`, which where `n*2%255` is zero, giving a false positive at `255^170=85`. But, since the bonus for imaginary internet points gives use one spare slot, with 48 slots for 47 values, we can just live with this hole. [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), 25 bytes (or 23 without imaginary internet points) ``` a:&&/1_|':9#2!(!8)+!8#2 a? ``` [Try it online!](https://tio.run/##y9bNS8/7/z/RSk1N3zC@Rt3KUtlIUUPRQlNb0ULZ6H@ivaG5oYJ@al5yfkoqV6KCkZmCgn5KKoj3HwA "K (ngn/k) – Try It Online") `8#2` is the list `2 2 2 2 2 2 2 2` `!8#2` generates an 8x256 matrix whose columns represent the bits of 0,1,..,255 `!8` is `0 1 2 3 4 5 6 7` `(!8)+` we add these to the corresponding rows in the matrix `2!` mod 2 `9#` reshape to 9 rows, i.e. copy the first row after the last to ensure wrap-around (for internet points!) `|':` boolean or each row with the row above it; with implicit 0 before the first `1_` drop the first `&/` boolean and-reduce over the rows - the result is a boolean mask of the encodable numbers `&` where are the 1s in this mask - return list of ints `a:` assign to `a`. the k language makes no distinction between function calls and list indexing, so `a` can act as the decompress function like this: `a 26` -> `171` `a?` is a function that looks up the position of its argument in `a`. this is our compress function: `a?171` -> `26` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~131~~ 68 bytes The most trivial answer, which generates all valid numbers (and a few extra values that aren't used) and finding the correct index. Huge bytesaves thanks to GB, and also realizing I'm allowed to store the numbers list as a separate variable (?) ``` a=(0..255).select{|i|i.to_s(4)!~/1|30/} d=->n{a[n]} c=->n{a.index n} ``` [Try it online!](https://tio.run/##bczRCsIgGIbhc6/izzHQYM5Wwk62GxkrnAoJw0VuUDi7dVvUYWfvBx/PfRmeKcmGcMYqISjzZjRqDqtdLZuniycnunuVh/XIy4h0U7QuyM71EalvM@u0eYCL6Q@Bc14POCf2XAu6rzaIbwwzUl1BT7A9ENyW2QPOgo1QtJAF1dn@l7r7jD5iZJxObw "Ruby – Try It Online") ### Imaginary bonus points, 72 bytes ``` a=(0..255).select{|i|"%08b"%(i^85)*2!~/00/} d=->n{a[n]} c=->n{a.index n} ``` [Try it online!](https://tio.run/##LczRCoIwFIDh@z3FaSKo4BzSyBt9kbFAt10cqBVtgjHXq6@i7r7/5n@syzPneaw4Y70QNfP2YnWIO@605MNCywrPg6ib/vDqOO8SMWM7uThLpxLRPzN0xm7gUj6eWMCr9WBu8FkQuK/BAy0iJmgnKKKRqP7U8hsqUWKdyW8 "Ruby – Try It Online") [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 16 bytes ### [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes Port of [xnor's Python answer](https://codegolf.stackexchange.com/a/199106/6484). -1 byte on legacy thanks to Kevin Cruijssen. Compression: ``` ÝƵζ^x&㢠``` Decompression: ``` µNƵζ^x&_ ``` Modern 05AB1E uses the same compression code, but needs an additional `D` in the decompression: ``` µNDƵζ^x&_ ``` TIO links: * [legacy compression](https://tio.run/##MzBNTDJM/f//8NxjW89ti6tQO9J@aNH//yZGAA "05AB1E (legacy) – Try It Online") * [modern compression](https://tio.run/##yy9OTMpM/f//8NxjW89ti6tQO9J@aNH//yZGAA "05AB1E – Try It Online") * [legacy decompression](https://tio.run/##MzBNTDJM/f//0Fa/Y1vPbYurUIv//9/QCAA "05AB1E (legacy) – Try It Online") * [modern decompression](https://tio.run/##yy9OTMpM/f//0FY/l2Nbz22Lq1CL///f0AgA "05AB1E – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~89 85~~ 74 bytes ``` a,b='14-7',"8abef" f=->n{("%o"%n).tr(a,b).hex} g=->n{("%x"%n).tr(b,a).oct} ``` [Try it online!](https://tio.run/##NY9NjsIwDEb3nCKKhKAjt5okzk8XcJHSRTuisBlATJEygp69@KvEIi92/Owk90f/P88d9buN4TJuSKeuPw56NezK/eW51eurXl@KarxvRSqq8zFPq9Onlj@1nrqiuv6M09x8k7KkEikjkWFSTlInO0vOEnMg5bHECZIbC9nBdgYIwHJWYwIUdoIAZekISwol4iyiLTLgBQlRwpQUBTWUWhRrGQiAFCweZvEy6zyQALnSMiKPj3i0eSjet9Vvd3u@8uv2GP9Uk@nU5JaGBlvbfmlV7g@jnuY3 "Ruby – Try It Online") Not going for the bonus points. ### How: Encode and decode using an octal-hexadecimal conversion: since some patterns cannot occur, the only allowed hex digits are `[0,2,3,8,a,b,e,f]`. So, if we take the hex digits and translate them to their index in the array, we get a 1- or 2-digits octal number, that is in the range 0-63. We can invert the process to decode the number. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~25~~ 17 bytes ``` ⁹Ḷ&Ḥ$Ðḟ^170 ị¢ Ñi ``` [Try it online!](https://tio.run/##y0rNyan8//9R486HO7apPdyxROXwhIc75scZmhtwPdzdfWgR1@GJmf8Nj@znetQw59DSQ8trTu4JqTvWdWjD4em5RzZEPNzdG3loebaJUtSh5YdWAnmnmh5tXPdw185DKw8tPNz2cOcC18MTDq2zi1B6uGOx4sOds442ABmH9z1q3Fumfrjd4VHDzCSg5YeWHN0NxHuMj@x/1LRGRQdCP9y56OgeI4jQsa4sIAVCDXMUdO0UHjXMBbKcgdglNRnIsYZI5ecWFKUWF1sBRQ4tCQeKHVpirRQJpLMeNe47tO3Qtv8A "Jelly – Try It Online") A set of links. The first link is shared and builds the list of possible valid 8-bit integers. The second link is the decompression link and the third handles compression. The footer compresses all the valid integers and then decompresses all the possible compressed values. Saved 8 bytes by porting [xnor’s Python answer](https://codegolf.stackexchange.com/a/199106/42248) with thanks! [Answer] # JavaScript (ES6), 58 bytes (with bonus: 65 bytes) I couldn't find anything shorter than a port of [xnor's answer](https://codegolf.stackexchange.com/a/199106/58563) with recursive functions. ### Encoder (30 bytes) ``` E=n=>n&&E(n-1)+!((n^=170)&2*n) ``` ### Decoder (28 bytes) ``` D=(n,k=n)=>E(k)^n?D(n,k+1):k ``` [Try it online!](https://tio.run/##bZBNT8MwDIbv@xXmsiS0q5Y0abuhdEJakRBIHHZETKrWMsYmd@oq/n6xc4Ahcehbfzx@4@Sz/qovu/5wHmbYNe04Vh59idNpJXGmVXQjJW69zudqam5RTdZeYnz0qHxZyaPa4mrNhUir5XG8e53HYGIoYtAUaRtDSmlKf0u5pdhmMTj@iMko14bhlOlUs2QsobZgB0ZsSpIxEiaykDKScy3nsdyyOJKCo4JdipxkwciCEGMsS8ZCDcOLGd7MpI6lYKEjjeXI8UUcjzlGnHtL3ru@qncfEsGXE4Bdh5fu1Canbi8pBcBk6DZDf8C9VMm5bipspFUQgfAlCIgCJFvwQE@r1C9tAr4Z6n6QtJ6YizAFkoag/cfVhL6Ca9@GfNeyvfb9s8UP5QFhBeLlScASxMP947NQ1FQTNX4D "JavaScript (Node.js) – Try It Online") ### Bonus-compliant version, 65 bytes With 7 more bytes in the encoder, we can output a value in \$[0..46]\$: ``` E=n=>n&&E(n-1)+!((n^=170)&2*n|n&n>>7) ``` [Try it online!](https://tio.run/##bZBNT4NAEIbv/RXjhd0VSrrLLtCapTEpJo0mHno0NiEFa20zNJR48r/jDAetiQde5uOZd2f3o/qsLrvucO6n2NbNMJQefYFBUEqcahXeSIlbr7OZCswtfmGARZGpycpLjI4elS9KeVRbXK64EGq1OA53L7MITAR5BJoibSNIKE3obym3FNs0AscfMSnl2jCcMJ1olpRlrM3ZgRGbkKSMjBPpmDKScS3jscyyOJKco5xd8oxkzsicEGMsS8pCDcOLGd7MJI4lZ6EjjeXI8UUcjzlGnHuN39qurHbvEsEXE4Bdi5f21MSndi8pBcC4bzd9d8C9VPG5qkuspVUQgvAFCAhHSDbggV5YqV/ajPimr7pe0npiJsYpkDQEzT@uZuwruPatyXclm2vfP1v8UB4QliCeHwUsQDzcr5@EoqaaqOEb "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 68 bytes Another version with recursive functions. The encoder is just as long, but the decoder is 10 bytes longer. ### Encoder (30 bytes) ``` E=n=>n&&n%16*17%61%9+8*E(n>>4) ``` ### Decoder (38 bytes) ``` D=n=>n&&596357088>>n%8*4&15|16*D(n>>3) ``` [Try it online!](https://tio.run/##bZBPS8NAEMXv/RRzSXe3jaH7NxslK0IjFAUPPYqH0MRaKZuSBk9@9zgTRCt4yMvMzu@9neS9/qjPu/5wGq5i17TjWJWxDHE@j4l0C5knTibF0i8qHkMwYrb@HtvCaZuvvA8hJn5h5tJ@omFNmBbjzfMqBZWCT0FiJU0KGluNb4O9wdq4FCw9yDjspSJYE60liSOZzgpKIMRoFEfI5HBTS0hOZznZckNiUTxVnlJ8jlIQUiCilCFxJDhQtJiizZS2JJ4Er1SGKksfYslmCbH2JXvt@qrevfEIZZgB7Lp47o5tduz2HFuAmA3ddugPcc9FdqqbKjbcCFgCKwMwWE4Qb6EE/KtC/NJqwrdD3Q8c12MrNrmAownaf1LVNBdwmdtg7pq3l7l/tvihSohwC@zpgcE1sPu7zSMTOBQzMX4B "JavaScript (Node.js) – Try It Online") ### How? As already [pointed out by G B](https://codegolf.stackexchange.com/a/199126/58563), there are only 8 valid nibbles for the input. We apply the following formula to map each of them to a unique value in \$[0..7]\$: $$f(n)=((n\times17)\bmod61)\bmod9$$ Which gives: ``` bin | hex | dec | *17 | mod 61 | mod 9 ------+-----+-----+-----+--------+------- 0000 | 0 | 0 | 0 | 0 | 0 0010 | 2 | 2 | 34 | 34 | 7 0011 | 3 | 3 | 51 | 51 | 6 1000 | 8 | 8 | 136 | 14 | 5 1010 | A | 10 | 170 | 48 | 3 1011 | B | 11 | 187 | 4 | 4 1110 | E | 14 | 238 | 55 | 1 1111 | F | 15 | 255 | 11 | 2 ``` Therefore, the input \$N\$ can be encoded as: $$f(N\bmod 16) + 8\times f(\lfloor N/16\rfloor)$$ which gives a unique value in \$[0..63]\$. The decoder retrieves the original nibbles by using the number `0x238BAFE0` (in decimal: \$596357088\$) as a lookup table. The conversion could also be done with this code: ``` (n&&n<3?n+9:44/n|4)^4 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/OT@vOD8nVS8nP12DS0Eh2kDHUMdIx1jHRMdUx0zHPFYvN7FAI0/B1g4oqaCgkaemlmdjbJ@nbWllYqKfV2OiGWcClNHk0vz/HwA "JavaScript (Node.js) – Try It Online") But this is even longer. [Answer] # [C++ (gcc)](https://gcc.gnu.org/), ~~187~~ \$\cdots\$ ~~138~~ 128 bytes Saved 22 bytes thanks to [S.S.Anne](https://codegolf.stackexchange.com/users/89298/s-s-anne)!!! Saved 5 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` struct F{int i,j,v[55];F(){for(i=j=0;j<55;++i)i&i*2?:v[j++]=i^170;}int c(int n){for(i=55;v[--i]-n;);n=i;}int d(int n){n=v[n];}}; ``` [Try it online!](https://tio.run/##XZFNboMwEIX3nGLUShUUiIKxgWCgu1yC0ioyoTJKTJQAm4iz0xlQWrULPubnPTMe1OXifyk1z7f@Oqge9ndtetBe642lEJXc28696a62ztt8K9tMCOm62tEv@pW9pWPZum6V648g3sqJnMommocJ5WPp@7ryjXSkyfWqqh8qk4@lqeQ0yflZG3Ua6mOmO5zleDgX1k9pPKq@uxYWuc4HbXAoC259naZrJ8NGAePhpOtPM5xvkMN96wHzIPEgwCjgHoSYhvjmmHOMeeSBoAc1EeYBI3FI6jAgRISltqMTSMJDRESSxREtKUliqsVkizlBIBKKEjoliRE7kuxQwhgnRARsMBqM0WQsFISEgJ9knCJBFxFkEyQRYpIW7KFBLjumRaa/V3cAVwPLT8QtNBtlGwel67ZUN/SQZWAIT@AXCIz037TZ4P9x/teUvdbXxrt5kmDBZE3zNw "C++ (gcc) – Try It Online") Is a `class` `F` with member functions `c` and `d` for compression and decompression. Uses [xnor's algorithm](https://codegolf.stackexchange.com/a/199106/58563). [Answer] # [Lua 5.3](https://www.lua.org/), ~~124~~ ~~122~~ 121 bytes ``` s,l=string,""for n=0,255 do l=n&n*2<1 and l..s.char(n~170)or l end f=function(n)return l:find(s.char(n),1,1),l:byte(n)end ``` [Try it online!](https://www.jdoodle.com/embed/v0/1QZq) Algorithm from [xnor](https://codegolf.stackexchange.com/a/199106/6484), ported to the requested language of Lua. This will only work on 5.3+, but you can get 5.2 compatibility for 24 extra bytes: ``` s,l=string,""for n=0,255 do l=bit32.band(n,n*2)<1 and l..s.char(bit32.bxor(n,170))or l end f=function(n)return l:find(s.char(n),1,1),l:byte(n)end ``` `f()` does both encoding and decoding; the first return value is for encoding and the second is for decoding. If you want separate functions for both, you can use this instead of the second line (+23 bytes): ``` e,d=function(n)return l:find(s.char(n),1,1)end,function(n)return l:byte(n)end ``` This version of the algorithm varies slightly from the original by using a string to store the map rather than a list, which allows using `string.find` to search for the item. `string.char`/`string.byte` also make it easy to switch between number and string formats. [Answer] # [Ruby](https://www.ruby-lang.org/), 88 bytes **(with imaginary bonus points)** ``` a=[170]+(6..51).map{|i|"UJEBA@D"[i/8].ord*257>>i%8&255^170} f=->n{a[n]} g=->n{a.index n} ``` 76 bytes if it is OK to check the array `a` directly instead of using `f` to do it. [Try it online!](https://tio.run/##KypNqvz/P9E22tDcIFZbw0xPz9RQUy83saC6JrNGKdTL1cnRwUUpOlPfIlYvvyhFy8jU3M4uU9VCzcjUNA6op5YrzVbXLq86MTovtpYrHcLWy8xLSa1QyKv9b2KuV5KZm1pcXZNVU6AQnaWjpGpgkaSkmhadFaujkB4NomNja/8DAA "Ruby – Try It Online") I can't beat GB's excellent answer, but this is the shortest Ruby answer claiming the imaginary bonus points so far. The question asks for all bytes where the even bits are less or equal to than the adjacent odd bits. An equivalent definition is all bytes where the odd bits are greater than or equal to the adjacent even bits, so overall the set is symmetrical. There is only one possible byte where all even bits are strictly less than the adjacent odd bits, this is `10101010`, decimal 170. The other 46 bytes where the even bits are less than or equal to the adjacent odd bits can be found by `XOR`ing this number with all possible bytes with no adjacent `1`'s. These comprise 7 distinct patterns and their bitwise rotations as listed below. We build an array of the 47 bytes by `XOR`ing `10101010` with the patterns below, then use lookup and index functions to carry out the conversion. ``` Pattern ASCII number of rotations 01010101 U 2 01001010 J 8 01000101 E 8 01000010 B 8 01000001 A 8 01000000 @ 8 01000100 D 4 Total 46 (plus 00000000) ``` [Answer] **Haskell** (85 bytes) The silly version that maps to at most 54: ``` import Foreign p y=2*y.&.y<1 d=filter(p.xor 170)[0..255] f x=sum[1|y<-d,y<x] g=(d!!) ``` `f` encodes a byte and `g` decodes. The next version should be much faster, consists of a bit of bit manipulation, but covers the range from 0 to 63 and requires 92 bytes: ``` (#)=div (&)=mod (k%j)e x=k*e(x#j)&k+e(x&j)&k f=8%16$(#128).(453*) g=16%8$(737715168#).(16^) ``` Here is the expanded, hopefully more comprehensible version: ``` module Compress8to6Bit where import Data.Bits (xor, shiftL, shiftR, (.|.), (.&.)) import Data.Word (Word8) import qualified Test.QuickCheck as QC {- > map compressNibble [0,2,3,8,10,11,14,15] [0,7,2,4,3,6,1,5] -} compressNibble :: Int -> Int compressNibble x = shiftR (453*x) 7 .&. 7 compress :: Int -> Int compress x = shiftL (compressNibble (shiftR x 4)) 3 .|. compressNibble (x .&. 15) decompressNibble :: Int -> Int decompressNibble x = shiftR 0x2BF8A3E0 (x*4) .&. 15 decompress :: Int -> Int decompress x = shiftL (decompressNibble (shiftR x 3)) 4 .|. decompressNibble (x .&. 7) inverseProp :: Word8 -> QC.Property inverseProp byte = let k = fromIntegral byte kx = xor 0xAA k in kx .&. shiftL kx 1 == 0 QC.==> k == decompress (compress k) ``` **How?** I found the multiplication trick of [Arnauld](https://codegolf.stackexchange.com/questions/199102/compress-8-bits-to-6-when-certain-bit-patterns-will-never-occur/199132#199132) interesting and found that you can do without modulo but simple shift and masking when using the factor 453. But after all you could also encode dictionaries for compression and decompression (on a 32-bit machine you need to use Int64 instead of Int): ``` compressNibble :: Int -> Int compressNibble x = shiftR 0o7600540300002100 (x*3) .&. 7 decompressNibble :: Int -> Int decompressNibble x = shiftR 0xFEBA8320 (x*4) .&. 15 ``` This one only needs 16 bit for the dictionary but requires `popCount`: ``` compressNibble :: Int -> Int compressNibble x = popCount (0x6686 .&. (shiftL 1 x - 1) :: Int) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 54 bytes ``` F²⁵⁶F¬&ι⊗ι⊞υ⁻|ι¹⁷⁰&ι¹⁷⁰I⌕υN ``` [Try the encoder online!](https://tio.run/##S85ILErOT8z5/z8tv0hBw8jUTFMBzPLLL9FwyiwpzyxOdcxL0cjUUXDJL03KSQUyNYFAIaC0OEOjVEfBNzOvtBim0r8IpNDQ3EBTRwFVM0hMU9OaK6AoM69EwzmxuETDLRMoBTTBM6@gtMSvNDcptUgDZLT1//8G/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. ``` F²⁵⁶F¬&ι⊗ι⊞υ⁻|ι¹⁷⁰&ι¹⁷⁰I§υN ``` [Try the decoder online!](https://tio.run/##S85ILErOT8z5/z8tv0hBw8jUTFMBzPLLL9FwyiwpzyxOdcxL0cjUUXDJL03KSQUyNYFAIaC0OEOjVEfBNzOvtBim0r8IpNDQ3EBTRwFVM0hMU9OaK6AoM69EwzmxuETDscQzLyW1AmSIZ15BaYlfaW5SapEGyHTr//9NTf7rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Just the usual table-driven lookup approach. Explanation: ``` F²⁵⁶ ``` Loop over the 256 binary values. ``` F¬&ι⊗ι ``` Check that no two adjacent bits are set. ``` ⊞υ⁻|ι¹⁷⁰&ι¹⁷⁰ ``` Flip the odd bits and save the result to the lookup table. ``` I⌕υN ``` Look up the index of the input in the table. ``` I§υN ``` Look up the input index in the table. Rather than create a table of Fibbinary numbers by filtering out invalid numbers, I attempted a mathematical approach which calculates successive Fibbinary numbers, but the encoder was 48 bytes and the decoder was 40 bytes: ``` ≔⁰η≔⁰ζW⁻⁻|η¹⁷⁰&η¹⁷⁰θ«≦⊕ζ≔⊕|η÷η²ι≧&±ιι≔×ι⊕÷ηιη»Iζ ≔⁰ηFN«≔⊕|η÷η²ι≧&±ιι≔×ι⊕÷ηιη»I⁻|η¹⁷⁰&η¹⁷⁰ ``` Explanation: ``` ≔⁰η ``` Initialise the Fibbinary number `h` to `0`. ``` ≔⁰ζW⁻⁻|η¹⁷⁰&η¹⁷⁰θ«≦⊕ζ ``` (Encoder) Initialise the encoding index to `0`. Repeat until the desired Fibbinary number is found. Increment the encoding index... ``` FN« ``` (Decoder) Repeat the desired number of times. ``` ≔⊕|η÷η²ι≧&±ιι≔×ι⊕÷ηιη» ``` Find the lowest value of `k` where `h&3<<k` is zero. Clear the bottom `k` bits of `h` and increment the next bit, which gives the next Fibbinary number. ``` Iζ ``` (Encoder) Output the number of loops taken. ``` I⁻|η¹⁷⁰&η¹⁷⁰ ``` (Decoder) Output the XOR of the Fibbinary number with 170. ]
[Question] [ Each natural number (including 0) can be written as a sum of distinct powers of integers (with a minimum exponent of 2). Your task is to output the smallest power required to represent \$n\$. For example: ``` 2 = 1^2 + 1^3 // Output 3 9 = 1^2 + 2^3 = 3^2 // Output 2 15 = 2^2 + 2^3 + 1^4 + 1^5 + 1^6 // Output 6 20 = 2^2 + 0^3 + 2^4 // Output 4 ``` Ungolfed slow reference implementation (js): ``` function f(x){ for (let maxPower = 2; true; maxPower++){ let bases = Array(maxPower - 1).fill(0); let sum = 0; while (sum != x && bases[0] ** 2 <= x){ sum = bases.reduce((a, c, i) => a + c ** (i + 2), 0); let nextIncr = bases.length - 1; do { if (nextIncr < bases.length - 1) bases[nextIncr + 1] = 0; bases[nextIncr]++; } while (nextIncr && bases[nextIncr] ** (nextIncr--) > x) } if (sum == x) return maxPower; } } ``` This is a [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenge. The sequence is naturally 0-indexed, so you may **not** 1-index it. You may... * Take a positive integer \$n\$ and output the first \$n\$ values. * Take a positive integer \$n\$ and output the value for \$n\$. * Take no input and output values indefinitely. The sequence starts: `2,2,3,4,2,3,4,5,3,2,3,4,3,4,5,6,2,3,4,5` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. -- Honestly, I'm surprised this isn't on the OEIS. I'm also uncertain whether there's any number above 6 in the sequence - not that I've searched that far. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 63 bytes ``` f=(n,m=2,i=0,p=n-i**m)=>p<0?f(n,m+1):!p||i&&f(p)<m?m:f(n,m,i+1) ``` [Try it online!](https://tio.run/##HclLCoMwEADQq6QbmbExpC7FUXqOUkqwpkwxyRClUPDu6edt39O93Dpllq2J6T6X4gmiDtRqJquFYsN1HZAG6e3of3U8YXeQfeeq8iDYhzF0/9D8rTKluKZlNkt6wMUYc87ZvaG1eDXBCcBNK0ZFg/LAiFg@ "JavaScript (Node.js) – Try It Online") Time out for not so large n as its terrible recursion design. It could be fast if we apply memorize to it (70 bytes). ``` f=(n,m=2,i=0,p=n-i**m)=>f[n]??=p<0?f(n,m+1):!p||i&&f(p)<m?m:f(n,m,i+1) o.value = [...Array(50000)].map((_, i) => i).filter(v => f(v) > 5).join(', ') ``` ``` <a href="https://oeis.org/A111151">A111151</a>: <output id=o></output> ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), 109 bytes This could probably be a bit shorter, but I tried to make it fast. Prints the sequence indefinitely. ``` a=[i:=1] k=2 while[print(k),k:=2]: while all(k<=a[i-b**k]for b in range(1,1+int(i**(1/k)))):k+=1 a+=k,;i+=1 ``` [Try it online!](https://tio.run/##HYtBCsMgEADvvmKPRg1l00ux2ZeIBwNps6wYkUDp603aOQ0DU7/Htpf7o7beEwX2hFEJTeqzcV5DbVwOLYMTT1P0Cv4ZUs5aZkqBx8UYia@9wQJcoKXyXjU6tL@PjdF4k@HCiyVUkCyJe/LlvZ8 "Python 3.8 (pre-release) – Try It Online") [Answer] # JavaScript (ES7), 79 bytes Returns the n-th term (0-indexed). ``` f=(n,q=2)=>(g=(k,t=n,i=0)=>t?i>t|k<2||g(k-1,t-i**k)*g(k,t,i+1):0)(q)?f(n,q+1):q ``` [Try it online!](https://tio.run/##FYxBDoMgEEWvwsLFjGIDLltHr6KxSihmqEq6Ec9OZfdf8t7/jL/xmHb7DTX795zSQsByowapA0PgZCCWltTNobddiK5tYjTgai1DbcvSYWmyJm2l8akQNuyX/JFxS4vfgQUJ9RIsWhJa5VVVKCbPh1/nx@oNDCMUJ194i8V513gNmP4 "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is the outer recursive function taking: n, // n = input q = 2 // q = upper bound for the exponent ) => // ( // g = ( // g is the inner recursive function taking: k, // k = exponent t = n, // t = remainder i = 0 // i = base ) => // t ? // if t is not equal to 0: i > t | // abort if i is greater than t // (this is slower but shorter than i ** k > t) k < 2 || // or k = 1 g( // otherwise, do a recursive call: k - 1, // decrement k t - i ** k // subtract i ** k from t ) * // end of recursive call g( // do another recursive call: k, // leave k unchanged t, // leave t unchanged i + 1 // increment i ) // end of recursive call : // else: 0 // success: return 0 )(q) // initial call with k = q ? // if it failed: f(n, q + 1) // try again with q + 1 : // else: q // success: return q ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes Very inefficient brute force approach. Prints \$a(n)\$ given \$n\$. ``` ∞>.ΔIÝy<ãεā>mO}Iå ``` [Try it online!](https://tio.run/##ASUA2v9vc2FiaWX//@KInj4uzpRJw515PMOjzrXEgT5tT31Jw6X//zE1 "05AB1E – Try It Online") A more efficient recursive version that is similar to my Python answer is 23 bytes long: ``` λNU∞>.ΔXyzmLymXα₅ß›]Y0ǝ ``` [Try it online!](https://tio.run/##ASwA0/9vc2FiaWX//867TlXiiJ4@Ls6UWHl6bUx5bVjOseKChcOf4oC6XVkwx53//w "05AB1E – Try It Online") **Commented**: ``` ∞>.ΔIÝy<ãεā>mO}Iå -- Takes input n and prints a(n) ∞> -- infinite list [2, 3, 4, ...] .Δ -- find the first value y in this list with: IÝ -- range from 0 to the input n y<ã -- cartesian power [0 .. n] ^ (y-1) ε } -- map over each (y-1)-tuple: ā> -- range [2 .. length+1] = [2 .. y] m -- exponentiation O -- sum the values Iå -- is the input in this list? λNU∞>.ΔXyzmLymXα₅ß›]Y0ǝ -- takes no input and prints the infinite sequence λ -- start recursive environment with a(0)=1 -- for each N in [1, 2, ...], calculate a(N) by: NU -- store N in variable X ∞>.Δ -- find y in [2, 3, 4, ...] with: yz -- 1/y X m -- X ^ (1/y) L -- [1..floor(X^(1/y))] ym -- [1..floor(X^(1/y))]^y Xα -- abs([1..floor(X^(1/y))]^y - X) ₅ -- a(abs([1..floor(X^(1/y))]^y - X)) ß› -- y > min(a(abs([1..floor(X^(1/y))]^y - X))) Y0ǝ -- Set the value at index 0 to 2 ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 18 bytes ``` λ›⁰ʀnÞẊƛż›e∑;?c;ṅ› ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLOu+KAuuKBsMqAbsOe4bqKxpvFvOKAumXiiJE7P2M74bmF4oC6IiwiIiwiMjAiXQ==) Vyxal has become bugless at last. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~84~~ 74 bytes ``` ->n,*r{(2..n**n).find{|x|a=0;r=1;x/=n while x>0&&a+=(x%n)**r+=1;a==n}?r:2} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5PR6uoWsNITy9PSytPUy8tMy@luqaiJtHWwLrI1tC6Qt82T6E8IzMnVaHCzkBNLVHbVqNCNU9TS6tIGyidaGubV2tfZGVU@79AIS3aMJYLRBlBKEsIZWgKFTWI/Q8A "Ruby – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 30 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Åœ¬_æÙδì€`é.Δā>zδmœ€Å\1%_Pà}g> ``` Outputs the value for a *positive* input \$n\$. [Try it online](https://tio.run/##AT4Awf9vc2FiaWX//8OFxZPCrF/Ot8KvxaHOtMOs4oKsYMOpLs6UxIE@es60bcWT4oKsw4VcMSVfUMOgfWc@//8yMA) or [verify the values in the range \$[1,25]\$](https://tio.run/##AUsAtP9vc2FiaWX/MjVFTj8iIOKGkiAiP07/w4XFk8KsX863wq/Foc60w6zigqxgw6kuzpTEgT56zrRtxZPigqzDhVwxJV9Qw6B9Zz7/LP8) (with `æÙ` replaced with `η¯š` to speed it up). **Explanation:** ``` Åœ # Get all possible sum-lists that equal the (implicit) input # Because these sums lack 0s, we add those as well: ¬ # Head (without popping), which are an input amount of 1s _ # Convert each to a 0 æ # Get the powerset of this Ù # Uniquify this list η¯š # Sped-up alternative: η # Get the prefixes of this list ¯š # And prepend an additional empty list δ # Apply double-vectorized: ì # Prepend-merge the lists €` # Flatten the list of lists one level down # (we've now added [0,input] amount of 0s to each sum of `Åœ`) é # Sort this list of lists by length .Δ # Find the first/shortest which is truthy for: ā # Push a list in the range [1,length] (without popping) > # Increase each by 1 to make the range [2,length+1] z # Calculate 1/n for each: [1/2,1/3,...,1/(length+1)] δ # Apply double-vectorized: m # Exponentiation # Check if at least one of these lists uses each exponent in # the range [2,length+1]: œ # Get all permutations of this list of lists € # Map each permutation-matrix to: Å\ # Pop and leave its main diagonal 1% # Modulo-1 on each _ # And check if its decimals are 0 (thus it's an integer) P # Product to check if this is truthy for all à # Max to check if this is truthy for any main diagonal }g> # When we've found our result: pop and push its length + 1 # (after which it is output implicitly as result) ``` [See this for a step-by-step output with added debug-lines.](https://tio.run/##VVJNa9tAEL3nVwyCnmq1UY6FxoSSQA8FQ45pSMfWWFqy2hX74cSGHlrIL2h/QHssGHoJ6d1Orv4R/SPqzMppnIukZd578/Y9WY9jRV2XvTdtDG8gG75d3Q33siOtobVeBTUjUCZQRc5DqDGAjw0Ey9/K82TLWt88fNsyyxLO9gdpcg7Y2GgC2Cnse2ERTmpREM5qebH5s/r98HNzu17@/br81AucWhdgPAdNpgp1Ev/VT06UKXkvwVQ5H@CqVizGLoKLoZ7D1Lokezd8tfm@lwGcxibXipG8eFLT5DLdTyaj6GtASENlkqZDUxGcHQz6vS@Lc0HffzlMhHfWzIh9Jf8sV7yeoY4kkEUCHF@31pAJGJQ1UNo41pTPaBKsUwsqBbi5bfrl5JrYA70kk5JMVvggby9ozlPAH5D9lQora1ALIDlonyQEy@Gtbz72RuWe22jQPXUnsOLFxQ5GbTc/CxCQi@eNaPhpyCU/wh09Z6KZwxU@MlNJP1JJn7MTbrwERz7qnR9qZFsmldBK8ip4eIx5sNOj1PCfVx0Ouq4oujw3Nte4mP8D) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~40~~ 39 bytes ``` FN⊞υ⊗¬ιF…²χF⮌⌕Aυ⁰F⊙υΣ✂…υ⊕⁻κXμι±¹§≔υκιIυ ``` [Try it online!](https://tio.run/##LY7NCsIwEITvPkWOG4iggidPpSL0YCn2CWK6tsF0I/lR@/QxUY/7zczOqEk6ZaVJ6WYdg4YeMbRxvqIDzlkX/QRRsKONV4MDtDaA5pwfVl/3RdKIsBNsu8nmH8InOo9w0jRUxpRw1v5iRUsBfZyhN1oh1IsyWE/2UXBDyuGMFHLRWVP0cBess688ZRas1HLBWhxlQNiWi7PKez1SFRoa8F1@3IvxsOqcpgC19AFiXpvSbp/WT/MB "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` values. Explanation: ``` FN⊞υ⊗¬ι ``` Start with `0` having been found to have a value of `2` but none of the other values having been found yet. ``` F…²χ ``` Try from squares up to ninth powers. ``` F⮌⌕Aυ⁰ ``` Loop over all of the values that haven't yet been found in reverse order, so the highest index is tested first. ``` F⊙υΣ✂…υ⊕⁻κXμι±¹ ``` Subtract the powers of all the integers up to `n` from the current index and see if any of those values had previously been found. This is harder than it sounds as it's necessary to defeat Charcoal's cyclic indexing. ``` §≔υκι ``` If so then mark this value with the necessary power. ``` Iυ ``` Output all of the values. [Answer] # [R](https://www.r-project.org/), ~~91~~ 88 bytes ``` f=function(n,m=2,o=n+3,a=n-(0:n)^m)`if`(m<o&&all(a),min(sapply(a[a>0],f,m+1,o)),m/(m<o)) ``` [Try it online!](https://tio.run/##VY3RCsIwDAD/ZiQsYqdvw/gjoi7ICoUmKetE/Po6wRef745bWlXJea7rvfhrXrhFjk97rMkNjJQP5Gz9kYRtB2E0vClOKU6gJ@@6LQVB0mRQpZT8BrnIOVwpkvYDOW5s/1UR208I4xDof4rtAw "R – Try It Online") Outputs the value for `n`. Very slow for even moderate `n`. ``` f=function(n, # recursive function with argument n m=2, # m=power to use in this iteration o=n+3, # o=maximum power: stop when m reaches this a=n-(0:n)^m # a=array of values by subtracting 0..n raised to m-th power from n ) `if`(m<o,...,Inf) # if m is too big, stop `if`(all(a),...,m) # if there are any zero values in a, then we've got n: stop and return m # otherwise: min( # return the lowest value of sapply(a[a>0],f,m+1,o) # recursive calls to f with all positive values of a, using power m+1 ) ``` --- # [R](https://www.r-project.org/), 79\* bytes (\* assuming that there are no values above 6 in the sequence, as conjectured in the comment to A111151) ``` f=function(n,m=2,a=n-(0:n)^m)`if`(m<7&all(a),min(sapply(a[a>0],f,m+1)),m/(m<7)) ``` [Try it online!](https://tio.run/##VY3RCoMwDAD/ZiSYsSqMgaz@iGwahoVCE0uriF/fOdiLz3fHpZKFQ5jyMsR5m5ItzrpVP4ufFZTENsRWr2Baxbfg6N0I8nxcjgYYSbxC5hjDDtxzZ17kSKoaD3L7eYjlj017N3R@YfkC "R – Try It Online") Also outputs the value for `n`, but somewhat more efficiently than the 91-byte code, as the recursion can stop much sooner. [Answer] # Haskell, 73 bytes ``` f n=head(filter((!)n)[2..]) n!m=n==0||(m>1&&any(\k->(n-k^m)!(m-1))[0..n]) ``` [Try it Online!](https://tio.run/##FcqxCsMgEADQvV9xLuFuUEx28xMdEwtCFYPeNSSWUsi/W/rml8NZYq29JxCXY3hi2mqLB6IioWUyxtNNFDtxzl4X8jwOQ5AvrkXPKLo8mBSyHokWa4x46hw2AQf7u93bAXjm1weQww4J/mWynqj/AA) f(n) returns the nth value in the sequence (0-indexed). n!m calculates whether n can be expressed as the sum of m (or fewer) powers. ]
[Question] [ ## Background The greatest common divisor (*gcd* for short) is a convenient mathematical function, since it has many useful properties. One of them is [Bézout's identity](https://en.wikipedia.org/wiki/B%C3%A9zout's_identity): if `d = gcd(a, b)`, then there exist integers `x` and `y` such that `d = x*a + y*b`. In this challenge, your task is to visualize this property with simple ASCII art. ## Input Your inputs are two positive integers `a` and `b`, given in any reasonable format. You may also take unary inputs (repetitions of a single printable ASCII character of your choice), but you must be consistent and use the same format for both inputs. The inputs may be in any order, and they may be equal. ## Output Your output is a string `s` of length `lcm(a, b) + 1` (*lcm* stands for lowest common multiple). The characters of `s` represent integers from `0` to `lcm(a, b)`. The character `s[i]` is a lowercase `o` if `i` is a multiple of `a` or `b`, and a period `.` otherwise. Note that zero is a multiple of every number. Now, because of Bézout's identity, there will be at least one pair of characters `o` in `s` whose distance is exactly `gcd(a, b)`. The leftmost such pair is to be replaced by uppercase `O`s; this is the final output. ## Example Consider the inputs `a = 4` and `b = 6`. Then we have `gcd(a, b) = 2` and `lcm(a, b) = 12`, so the length of `s` will be `13`. The multiples of `a` and `b` are highlighted as follows: ``` 0 1 2 3 4 5 6 7 8 9 10 11 12 o . . . o . o . o . . . o ``` There are two pairs of `o`s with distance two, but we will only replace the leftmost ones with `O`s, so the final output is ``` o...O.O.o...o ``` ## Rules and scoring You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed. ## Test cases ``` 1 1 -> OO 2 2 -> O.O 1 3 -> OOoo 4 1 -> OOooo 2 6 -> O.O.o.o 2 3 -> o.OOo.o 10 2 -> O.O.o.o.o.o 4 5 -> o...OO..o.o.o..oo...o 8 6 -> o.....O.O...o...o.o.....o 12 15 -> o...........O..O........o.....o.....o........o..o...........o 19 15 -> o..............o...o..........o.......o......o...........o..o..............OO.............o....o.........o........o.....o............o.o..............o.o............o.....o........o.........o....o.............oo..............o..o...........o......o.......o..........o...o..............o ``` [Answer] # Julia, ~~111~~ ~~110~~ ~~107~~ ~~103~~ 96 bytes ``` f(a,b)=replace(join([i%a*(i%b)<1?"o":"."for i=0:lcm(a,b)]),"o$(d="."^(gcd(a,b)-1))o","O$(d)O",1) ``` This is a function that accepts two integers and returns a string. Ungolfed: ``` function f(a::Int, b::Int) # Construct an array of dots and o's x = [i % a * (i % b) < 1 ? "o" : "." for i = 0:lcm(a, b)] # Join it into a string j = join(x) # Replace the first pair with distance gcd(a, b) - 1 replace(j, "o$(d = "."^(gcd(a, b) - 1))o", "O$(d)O", 1) end ``` Saved a byte thanks to nimi! [Answer] ## [Retina](https://github.com/mbuettner/retina), ~~112~~ ~~109~~ ~~99~~ ~~94~~ 91 bytes ``` ^ . +r`(?<!^\1+). (.+) $'$0 .(?=.* (.+) (.+))(?=\1* |\2* ) o o(\.*)o((\1\.*o)*) .* O$1O$2 ``` Not very competitive, I think, but number theory in Retina is always quite fun. :) Takes input as unary numbers using `.` as the unary digit. [Try it online.](http://retina.tryitonline.net/#code=XgouIAorcmAoPzwhXlwxKykuICguKykgCiQnJDAKLig_PS4qICguKykgKC4rKSkoPz1cMSogfFwyKiApCm8KbyhcLiopbygoXDFcLipvKSpcLiopIC4qCk8kMU8kMg&input=Li4uLi4uLi4uLi4uIC4uLi4uLi4uLi4uLi4uLg) ### Explanation ``` ^ . ``` This inserts a `.` and a space in front of the input. This will ultimately become the output. ``` +r`(?<!^\1+). (.+) $'$0 ``` This prepends the LCM of `a` and `b` to the string. Since we already have a `.` there, we'll end up with `lcm(a,b)+1`. This is accomplished by repeatedly prepending `b` as long as `a` does not divide this new prefix. We capture `a` into a group one and then check if we can reach the beginning of the string by matching that capture at least once. `b` is then inserted into the string via the rarely used `$'` which inserts everything *after* the match into the substitution. ``` .(?=.* (.+) (.+))(?=\1* |\2* ) o ``` This one matches characters at positions which are divided by `a` or `b`. It makes use of the fact that the result is symmetric: since `lcm(a,b)` is divided by both `a` and `b` going left by subtracting instances of `a` or `b` yields the same pattern as going right from `0` by adding them. The first lookahead simply captures `a` and `b`. The second lookahead checks that there is a multiple of each `a` or `b` characters before the first space. ``` o(\.*)o((\1\.*o)*) .* O$1O$2 ``` As stated on Wikipedia, in addition to Bézout's identity it is also true that > > The greatest common divisor `d` is the smallest positive integer that can be written as `ax + by`. > > > This implies that the GCD will correspond to the shortest gap between two `o`s in the output. So we don't have to bother finding the GCD at all. Instead we just look for first instance of the shortest gap. `o(\.*)o` matches a candidate gap and captures its width into group 1. Then we try to reach the first space by alternating between a backreference to group 1 and `o`s (with optional additional `.`s). If there is a shorter gap further to the right, this will fail to match, because we cannot get past that gap with the backreference. As soon as all further gaps are at least as wide as the current one, this matches. We capture the end of the LCM-string into group 2 and match the remainder of the string with `.*`. We write back the uppercase `O`s (with the gap in between) as well as the remainder of the LCM string, but discard everything starting from the space, to remove `a` and `b` from final result. [Answer] # Jolf, 52 bytes ``` on*'.wm9jJΡR m*Yhm8jJDN?<*%Sj%SJ1'o'.}"'o%o"n"O%O"n ``` I will split this code up into two parts. ``` on*'.wm9jJ on set n *'. to a dot repeated m9jJ the gcd of two numeric inputs ΡR m*Yhm8jJDN?<*%Sj%SJ1'o'.}"'o%o"n"O%O"n *Y multiply (repeat) Y (Y = []) hm8jJ by the lcm of two inputs + 1 _m DN } and map the array of that length ?<*%Sj%SJ1'o'. "choose o if i%a*(i%b)<1; otherwise choose ." R "' join by empty string Ρ 'o%o"n replace once (capital Rho, 2 bytes): "o"+n+"o" "O%O"n with "O"+n+"O" implicit printing ``` [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=b24qJy53bTlqSs6hUiBtKllobThqSkROPzwqJVNqJVNKMSdvJy59IidvJW8ibiJPJU8ibg&input=NAoKNg) [Answer] # 𝔼𝕊𝕄𝕚𝕟, 50 chars / 90 bytes ``` ⩥Мū⁽îí+1)ⓜ$%î⅋$%í?⍘.:⍘o)⨝ċɼ(`o⦃⍘.ĘМũ⁽îí-1)}o”,↪$ú⬮ ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=true&input=%5B4%2C6%5D&code=%E2%A9%A5%D0%9C%C5%AB%E2%81%BD%C3%AE%C3%AD%2B1%29%E2%93%9C%24%25%C3%AE%E2%85%8B%24%25%C3%AD%3F%E2%8D%98.%3A%E2%8D%98o%29%E2%A8%9D%C4%8B%C9%BC%28%60o%E2%A6%83%E2%8D%98.%C4%98%D0%9C%C5%A9%E2%81%BD%C3%AE%C3%AD-1%29%7Do%E2%80%9D%2C%E2%86%AA%24%C3%BA%E2%AC%AE)` There must be a way to golf this further! # Explanation This is a basic two-phase algorithm. It's actually quite simple. ### Phase 1 ``` ⩥Мū⁽îí+1)ⓜ$%î⅋$%í?⍘.:⍘o)⨝ ``` First, we create a range from 0 to the LCM+1. Then we map over it, checking if either of the inputs is a factor of the current item in the range. If so, we replace that item with an `o`; otherwise, we replace it with a `.` . Joining it gives us a series of o's and dots that we can pass to phase two. ### Phase 2 ``` ċɼ(`o⦃⍘.ĘМũ⁽îí-1)}o”,↪$ú⬮ ``` This is just one big replace function. A regex is created as `o[dots]o`, where the amount of dots is determined by the GCD-1. Since this regex is not global, it will only match the first occurrence. After, the match is replaced by `O[dots]O` using a toUpperCase function. [Answer] # [MATL](https://esolangs.org/wiki/MATL), 72 bytes Uses [version 6.0.0](https://github.com/lmendo/MATL/releases/tag/6.0.0), which is earlier than this challenge. The code runs in Matlab and in Octave. ``` 2$tZm1+:1-bbvtbw\A~otbZ}ZdXK1+ltb(3X53$X+1K2$lh*t2=f1)tK+hwg1+Ib('.oO'w) ``` ### Example ``` >> matl > 2$tZm1+:1-bbvtbw\A~otbZ}ZdXK1+ltb(3X53$X+1K2$lh*t2=f1)tK+hwg1+Ib('.oO'w) > > 1 > 1 OO >> matl > 2$tZm1+:1-bbvtbw\A~otbZ}ZdXK1+ltb(3X53$X+1K2$lh*t2=f1)tK+hwg1+Ib('.oO'w) > > 2 > 3 o.OOo.o >> matl > 2$tZm1+:1-bbvtbw\A~otbZ}ZdXK1+ltb(3X53$X+1K2$lh*t2=f1)tK+hwg1+Ib('.oO'w) > > 12 > 15 o...........O..O........o.....o.....o........o..o...........o ``` ### Explanation I have [no idea](https://i.stack.imgur.com/6x5av.jpg) how it works. I just typed characters randomly. I think there is some convolution involved. **Edit: [Try it online!](http://matl.tryitonline.net/#code=MiR0Wm0xKzoxLWJiJnZ0YndcQX50Ylp9WmRYSzErbHRiKDNYNTMkWSsxSzIkbGgqdDI9ZjEpdEsraHdnMStJYignLm9PJ3cp&input=MTIKMTU)** The code in the link has been slightly modified to conform to changes in the language (as of June 2, 2016). [Answer] ## [Japt](http://ethproductions.github.io/japt/), 83 bytes ``` '.pD=U*V/(C=(G=@Y?G$($YX%Y :X} $($UV)+1 £Y%U©Y%V?".:o"} $.replace($E=`o{'.pC-1}o`Eu ``` Not fully golfed yet... And doesn't want to be golfed :/ [Answer] ## Javascript, ~~170~~ ~~164~~ ~~161~~ ~~153~~ ~~145~~ ~~141~~ 136 bytes ``` (a,b)=>[...Array(a*b/(c=(g=(a,b)=>b?g(b,a%b):a)(a,b))+1)].map((x,i)=>i%a&&i%b?'.':'o').join``.replace(`o${e='.'.repeat(c-1)}o`,`O${e}O`) ``` That's quite lonnnggggg.... [Demo](http://www.es6fiddle.net/iix3s7ty/), explicitly defined variables because the interpreter uses strict mode. [Answer] # Python 2, ~~217~~ ~~200~~ 191 bytes This is a little blunt, but it works. Any golfing tips are appreciated, ~~especially if you know how to fix that `s[i] = s[v] = "o"` problem I encountered, where that would overwrite "O"s~~ Got it! ``` g=lambda a,b:b and g(b,a%b)or a def f(a,b): h=g(a,b);x=1+a*b/h;s=["."]*x;v=k=0 for i in range(x): if(i%a)*(i%b)<1: if k:s[i]="o" else:k=i==h+v;s[i]=s[v]="oO"[k] v=i return''.join(s) ``` **Ungolfed:** ``` def gcd(a,b): # recursive gcd function if b: return g(b,a%b) else: return a def f(a,b): h = gcd(a,b) x = 1 + a*b/h # 1 + lcm(a,b) s = ["."] * x v = 0 k = 0 for i in range(x): if i%a == 0 and i % b == 0: if k == 0: k = (i == h+v) # correct distance apart? if k: # if "O" just found s[i] = s[v] = "O" else: s[i] = s[v] = "o" else: s[i] = "o" # if "O" already found, always "o" v = i # If we found an "o" or an "O", i is the new v return ''.join(s) ``` ]
[Question] [ # My Alarm Clock I'm American, and so is my (digital) alarm clock. To set the alarm, it starts at the time it was previously. Hitting the hour button moves it up one hour, and hitting the minute button moves it up one minute. Hitting both buttons at the same time resets it to midnight (12:00 am), and counts as two button presses. When the hours exceed their cap (12), it resets to 1 and toggles the AM/PM light. When the minutes exceed their cap (59), they reset to 0, without affecting the hours. # The Task Your task is, given a starting time and a target time, to output the optimal number of buttons presses needed to set my alarm to the target time. You may take input in whatever format suits you best. The only data your program should need is hours and minutes, for both inputs. That means that you, for example, may take data as milliseconds since epoch, and extract the hours and minutes, but you may not encode *anything* into the year, month, second, etc. Note that while you may, for example, input using "military time" (or regular time for most of the world), but that doesn't change how my clock works. # Examples ``` 1:15 pm -> 2:30 am ``` You could push down both buttons to reset to 12:00 am, then increment to 2:30 am, which would be `2+2+30 = 34` button presses. You could also increment to 2:30 am, which would be `13+15 = 28` button presses. Therefore, your output is `28`. ``` 3:58 am -> 4:02 am ``` You could reset and increment, which would be `2+4+2 = 8` button presses. You could also increment, which would be `1+4 = 5` button presses. Therefore, your output is `5`. ``` 10:55 pm -> 1:00 am ``` You could reset and increment, which would be `2+1 = 3` button presses. You could also increment, which would be `3+5=8` button presses. Therefore, your output is `3`. ``` 1:00 am -> 1:59 pm ``` You could reset and increment, but that would be three more presses than just incrementing. Therefore, your output is `12+59 =` `71`. # Test Cases ``` Current Target = Output 1:15pm 2:30am = 28 3:58am 4:02am = 5 10:55pm 1:00am = 3 1:00am 1:59pm = 71 12:00am 12:00am = 0 6:51pm 12:00am = 2 2:01pm 11:00pm = 25 2:01pm 11:01pm = 9 12:59am 12:01am = 2 11:50am 12:00pm = 11 ``` [Answer] # JavaScript (ES6), ~~73~~ ~~56~~ ~~54~~ ~~52~~ 50 bytes Uses 24 hour format. Takes input as 4 integers representing the hours & minutes of each time. ``` (g,l,h,m)=>Math.min(2+h+m,(h-g+24)%24+(m-l+60)%60) ``` * 2 bytes saved thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld). --- ## Try it Enter the times in 24-hour format, with the `:` separator. ``` o.innerText=(f= (g,l,h,m)=>Math.min(2+h+m,(h-g+24)%24+(m-l+60)%60) )(+(x=(i.value="01:00").split`:`)[0],+x[1],+(y=(j.value="13:59").split`:`)[0],+y[1]);oninput=_=>o.innerText=f(+(x=i.value.split`:`)[0],+x[1],+(y=j.value.split`:`)[0],+y[1]) ``` ``` label,input{font-family:sans-serif;font-size:14px;height:20px;line-height:20px;vertical-align:middle}input{margin:0 5px 0 0;width:100px;} ``` ``` <label for=i>Current: </label><input id=i type=time><label for=j>Target: </label><input id=j type=time><pre id=o> ``` --- ## Explanation (To be updated shortly.) ``` (g,l,h,m)=> ``` Anonymous function taking the integers as arguments via parameters `g`, `l`, `h` & `m`, where `g` & `l` are, respectively, the hours & minutes of the current time and `h` & `m` are the hours & minutes of the target time. ``` 2+h+m ``` First, we calculate how many button presses are needed if we just reset the clock, which is simply 2 (for the reset) plus the target hour and the target minute. ``` h-g+24*(h<g) ``` Next we calculate how many button presses are needed to reach the target hour. We do this by subtracting the current hour from target hour. However, if the current hour is less than the target, this will give us a negative number so we rectify that by adding 24 multiplied by checking if `h<g` (which returns a boolean but is implicitly cast to integer `1`, if true, or `0` if false by the mathematical operations. ``` +m-l+60*(m<l) ``` We use a similar formula to calculate the number of presses to get from the current minute to the target minute and add that to the hour presses. ``` Math.min() ``` Finally, we get the minimum of the 2 numbers to give us our result. [Answer] # [Pyth](https://pyth.readthedocs.io), 29 bytes This challenge obviously doesn't advantage golfing languages, that's why it's so long. On the other hand, this is improved by the fact that Pyth is Python-based, so we can abuse its negative modulus. ``` hS,+%-eQ@Q1 60%-@Q2hQ24+2s>Q2 ``` **[Test Suite.](http://pyth.herokuapp.com/?code=hS%2C%2B%25-eQ%40Q1+60%25-%40Q2hQ24%2B2s%3EQ2&input=13+15+02+30%0A03+58+04+02%0A22+55+01+00%0A01+00+13+59%0A00+00+00+00%0A18+51+00+00%0A14+01+23+00%0A14+01+23+01%0A00+59+00+01%0A11+50+12+00&test_suite=1&test_suite_input=%5B13%2C+15%2C+2%2C+30%5D%0A%5B3%2C+58%2C+4%2C+2%5D%0A%5B22%2C+55%2C+1%2C+0%5D%0A%5B1%2C+0%2C+13%2C+59%5D%0A%5B0%2C+0%2C+0%2C+0%5D%0A%5B18%2C+51%2C+0%2C+0%5D%0A%5B14%2C+1%2C+23%2C+0%5D%0A%5B14%2C+1%2C+23%2C+1%5D%0A%5B0%2C+59%2C+0%2C+1%5D%0A%5B11%2C+50%2C+12%2C+0%5D&debug=0)** Numbers in Pyth do not support leading zeros. [Answer] # [Husk](https://github.com/barbuz/Husk), 16 bytes ``` §▼ṁ→(Σz%e24 60z- ``` [Try it online!](https://tio.run/##AS8A0P9odXNr///Cp@KWvOG5geKGkijOo3olZTI0IDYwei3///9bMjIsNTVd/1sxLDAwXQ "Husk – Try It Online") Takes arguments as two lists [hours,minutes], for start and end time, in 24h format. I'm quite happy about how much I was able to golf this one, I find interesting how arguments are managed in this composition of functions. The function which calculates how many key presses we need if reset is not allowed is the following: ``` Σz%e24 60z- z- elementwise subtract the two times z%e24 60 take the hours difference modulo 24 and the minutes difference modulo 60 Σ sum the two resulting numbers ``` The interesting part is that since the rest of this solution can work only with a single list as argument, this one gets partially applied to the first argument of the whole program, "eating" it and leaving only the second argument visible both for itself and the rest of the program. Next, we compute how many key presses we need if we reset the time to 0:00 ``` ṁ→ take the sum of each element of the list increased by 1 ``` As said before, this operates only on the second argument (the final time), and computes `hours+minutes+2`, just in a golfier way. Finally, `§▼` is the part that passes the second argument to both functions, and returns the lesser of the two results. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` _⁵%24µ+⁴_⁶%60µ«³+⁴¤ ``` [Try it online!](https://tio.run/##y0rNyan8/z/@UeNWVSOTQ1u1HzVuAXK2qZoZHNp6aPWhzSCBQ0v@//9v9N/Y4L@h8X9DUwA "Jelly – Try It Online") Input as 4 integers (end-hour, end-minute, start-hour, start-minute) [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 56 bytes ``` (H,M,h,m)=>Math.Min(((h+24-H)%24)+((m+60-M)%60),(2+h+m)) ``` [Try it online!](https://tio.run/##XY2xCoMwFEX3fEUW4T0SxYq4WIVSKA7N1KFzSEMNmERMLBTpt9s6FEo53LNdjgqp8pNe52DcnV6eIWpbEyetDqNUmrqFqEGGQMeFhCijUfQ0O7U3LvK/tdSP0Vg5HAY5Wdqs0HHBe26xaYWMfSaMA4CeFWXaYVKUyAAsq/JUYFLlyKFgPbOIa/1NPby5USE/P1zI0bvgB51dJxP12TgNvz3YFTznmxBr8tpY3w "C# (.NET Core) – Try It Online") Very similar to the Javascript answer. Bools in C# don't convert easily to numbers, so instead of `[diff]+24*(H<h)` I did `([diff]+24)%24` which effectively does the same thing. [Answer] # Haskell, 41 bytes ``` (a#b)c d=min(a+b+2)$mod(a-c)24+mod(b-d)60 ``` Pretty straightforward. Takes input as four arguments using 24-hour time: end hour, end minute, start hour, start minute. [Answer] # [Python 3](https://docs.python.org/3/), 43 bytes ``` lambda a,b,c,d:min((c-a)%24+(d-b)%60,2+c+d) ``` [Try it online!](https://tio.run/##VYzNDoIwDMfP7il6IelkmHVjBkh8Ey8DRJfAXBAPPj0WEw42Tf8f@aXpszye0a7D5bqOfmp7D161qlN9M4WI2BVeZqbMsS9amZ21MnmX93IdnjMECBFmH@83JC0bcUhziAsOeBzDa8HJJ@SsmErvBeXplcbAus1KFsiBNmC10BZcBbrkKIwBxz2B5n67wKSrBZt9BVXgaPflBhv772njXf1jSBCB4z@G4xc "Python 3 – Try It Online") Input as 4 integers (start-hour, start-minute, end-hour, end-minute) [Answer] # Java 8, ~~54~~ 50 bytes ``` (h,m,H,M)->Math.min((H-h+24)%24+(M-m+60)%60,H+M+2) ``` Port of [*@KamilDrakari*'s C# answer](https://codegolf.stackexchange.com/a/138293/52210) (after I golfed ~~2~~ 6 bytes). **Explanation:** [Try it here.](https://tio.run/##jZKxasMwEIb3PsUtAQnLjiRbaUxoZy/OkrF0UB23dhrLJlYCpeTZ3ZPtQOggAroDSff995/QQV902HalOey/h@Ko@x5yXZvfJ4Da2PL0qYsStm47HkBBXK6Yy82YszHndIM1VwxcvdW2LmALBl5gIBVrWMZyGr7m2lZRUxtCsrAKZEIXMglIHjbBitPFirMsyANJh82k050/jqgzy13aeg8NmiM7e6rN19s7aDo52/30tmyi9myjDq/s0RATFUTEDIRiwCWDmFO6geUS5NqHcETUGpHEYTOifIREceWaCIxbk9jbY6xEa65XOhPPwovwCZliRrh3dhxCiX@E9BLJNISM7wn1MCJmJPUS7rVSnF3eEX5bqK/4TNxsCTH@tuvwBw) ``` (h,m,H,M)-> // Method with four integer parameter and integer return-type Math.min( // Return the lowest of the following two: // The hours: (H-h // Second hours - first hours inputs +24) // +24 so we won't have negative numbers %24 // mod-24 to get the hours + // And add the minutes: (M-m // Second minutes - first minutes inputs +60) // +60 so we won't have negative numbers %60 // mod-60 to get the minutes ,H+M // And compare it to the second hours + second minutes inputs +2) // +2 for the added +24 and +60 to get the positive modulo arguments ``` [Answer] # [Perl 5](https://www.perl.org/), 71 +2 (-ap) = 73 bytes ``` ($w,$x,$y,$z)=@F;$_=($r=2+$y+$z)>($c=($y-$w+24)%24+($z-$x+60)%60)?$c:$r ``` [Try it online!](https://tio.run/##DcixCsIwFAXQX8lwCwkvkZfQOLSkOrn5DSLFQRAbotCmH@8zw1lOfpRXFNFYLTaLarGbdL6MuCWNkgKhUqtJY25RHVYKvelCTxq7w0ZHNl1zwjygiHivIisfFPNvyd/n8v6Iu8YDexZ3z38 "Perl 5 – Try It Online") Takes input in 24 hour format (military time), separated by spaces, start time first, end time second: *HH MM hh mm* [Answer] # [Retina](https://github.com/m-ender/retina), 106 bytes ``` \d+ $* (1*):(1*) 24$*1$1:60$*1$2#11$1$2 (1*):(1* )\1(1{24})? $2 (1*) (1*):\1(1{60})? $2 (1+)#(?!\1) \G1 ``` [Try it online!](https://tio.run/##VYwxDsIwDEV3nyKoQUraxd9pqtZLx14iA0gwsDAgtoqzh6RQJJbv76dnP67P2/2cj2455XTpyLZkHFqvNchIb1tY6MB1SoOyWKHdMD7BYZX@5Wf68s/5xgf@8c43bj4keKK0IGcERTQsGpg4aBwN98pCIhoLh3LhNU0x40TMtW9JGDVi7@UKRsJ/R/XjtDkgQGP5I8V5Aw "Retina – Try It Online") Link includes test cases. Takes input as current and desired times in regular 24 hour time with a space separating the two times. Explanation: ``` \d+ $* ``` Convert to unary. ``` (1*):(1*) 24$*1$1:60$*1$2#11$1$2 ``` This does two things; it adds 24 hours and 60 minutes to the desired hours and minutes, and it also adds 2 to the sum of the original desired hours and minutes, i.e. the the number of button presses to set using a reset. ``` (1*):(1* )\1(1{24})? $2 ``` Subtract the current hours from the desired hours, and subtract the 24 we added on if we can. ``` (1*) (1*):\1(1{60})? $2 ``` Similarly for the minutes. This also adds the two results together. ``` (1+)#(?!\1) ``` If the number of presses to set using the current time is more than the number of presses to set using a reset, delete it. ``` \G1 ``` Convert the first remaining number back to decimal. ]