text
stringlengths
180
608k
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 3 years ago. [Improve this question](/posts/1960/edit) PHP has closures, let's play around with them. I have some arrays similar to, `$wannabelist = array (1, 2, 3, 4, 5, 6)`. I want to do this: `compr( expression($params), $wannabelist, $wannabilist2 ...)`. compr() should do the following: 1. Take all the possible combinations of elements of the arrays given as parameters; 2. Pass each of them to the expression passed as first parameter; 3. Yield the result. A particularly satisfying function will: 1. Avoid changing the value of any variable; 2. Be elegant; 3. Contain an inordinate amount of nested parenthesis/brackets; 4. Avoid foreach() loops. [Answer] First, a few neat things about list comprehensions, from a Haskell perspective: * The list monad in Haskell is set up so any list comprehension can be transformed into do notation rather easily: ``` > [(i,j) | i <- [1..3], j <- [1..3]] [(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)] > do {i <- [1..3]; j <- [1..3]; return (i,j)} [(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)] ``` * Haskell has a `sequence` function that takes a list of "actions" in a monad and returns a list of the results: ``` > sequence [getLine, getLine, getLine] one two three ["one","two","three"] ``` * Consequently, using `sequence` with the list monad gives you combinations for free: ``` > do {i <- [1..3]; j <- [1..3]; return [i,j]} [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]] > sequence [[1..3], [1..3]] [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]] ``` Hence, the `sequence` function is very similar to the `compr` function asked for. It just needs to be wrapped and mapped a bit: ``` function compr() { $args = func_get_args(); $f = $args[0]; $call_f = function($array) use ($f) { return call_user_func_array($f, $array); }; return array_map($call_f, sequence(listMonad(), array_slice($args, 1))); } ``` Now, without further ado, here is a nearly direct translation of the list monad and `sequence` function from Haskell to PHP: ``` # instance Monad [] where # m >>= k = concat (map k m) # return x = [x] # fail s = [] function listMonad() { return (object) array( 'bind' => function($m, $k) { return call_user_func_array('array_merge', array_map($k, $m)); }, 'return' => function($x) { return array($x); }, 'fail' => function($s) { return array(); } ); } # sequence :: Monad m => [m a] -> m [a] # sequence = foldr mcons (return []) # where mcons p q = p >>= \x -> q >>= \y -> return (x:y) function sequence($monad, $list) { $mcons = function($p, $q) use ($monad) { return call_user_func($monad->bind, $p, function($x) use ($monad, $q) { return call_user_func($monad->bind, $q, function($y) use ($monad, $x) { return call_user_func($monad->return, cons($x, $y));});});}; return foldr($mcons, call_user_func($monad->return, array()), $list); } # foldr :: (a -> b -> b) -> b -> [a] -> b # foldr f z [] = z # foldr f z (x:xs) = f x (foldr f z xs) function foldr($f, $z, $xs) { if (empty($xs)) return $z; return call_user_func($f, $xs[0], foldr($f, $z, array_slice($xs, 1))); } function cons($x, $xs) { return array_merge(array($x), $xs); } ``` I believe this meets all four of your criteria, especially the "inordinate amount of nested parenthesis/brackets" part. Test code: ``` function printList($show, $list) { echo showList($show, $list) . "\n"; } function showList($show, $list) { $str = "["; foreach($list as $x) { if ($str !== "[") $str .= ","; $str .= call_user_func($show, $x); } return $str . "]"; } # Count in binary printList('strval', compr(function($a, $b, $c, $d) { return "$a$b$c$d"; }, array(0,1), array(0,1), array(0,1), array(0,1))); # Combinations of items printList(function($a) {return showList('strval', $a);}, compr(function($a, $b, $c) { return array($a, $b, $c); }, array(1, 2), array(3, 4, 5), array(6, 7, 8, 9))); ``` Output: ``` [0000,0001,0010,0011,0100,0101,0110,0111,1000,1001,1010,1011,1100,1101,1110,1111] [[1,3,6],[1,3,7],[1,3,8],[1,3,9],[1,4,6],[1,4,7],[1,4,8],[1,4,9],[1,5,6],[1,5,7],[1,5,8],[1,5,9],[2,3,6],[2,3,7],[2,3,8],[2,3,9],[2,4,6],[2,4,7],[2,4,8],[2,4,9],[2,5,6],[2,5,7],[2,5,8],[2,5,9]] ``` [Answer] Implemented using simple modulus/division. ``` function compr() { $args = func_get_args(); $callback = array_shift($args); $total_length = array_product(array_map(function($arr) { return count($arr); }, $args)); $return = array(); for ($i = 0; $i < $total_length; $i++) { $params = array(); $_i = $i; for ($j = 0; $j < count($args); $j++) { $base = count($args[$j]); $params[] = $args[$j][$_i % $base]; $_i /= $base; } $return [] = call_user_func_array($callback, $params); } return $return; } ``` Test: ``` $array = compr(function($a, $b, $c) { return $a + $b + $c; }, array(1, 2), array(3, 4, 5), array(6, 7, 8, 9)); print_r($array); ``` Output: ``` Array ( [0] => 10 [1] => 11 [2] => 11 [3] => 12 [4] => 12 [5] => 13 [6] => 11 [7] => 12 [8] => 12 [9] => 13 [10] => 13 [11] => 14 [12] => 12 [13] => 13 [14] => 13 [15] => 14 [16] => 14 [17] => 15 [18] => 13 [19] => 14 [20] => 14 [21] => 15 [22] => 15 [23] => 16 ) ``` ]
[Question] [ Code [Python 3](https://docs.python.org/3/), 245 bytes ``` E=print def F(): B,C,A=1,1,1;yield 0 while True:yield B;B,C,A=B+C+A+1,C+A+1,A+1 C=int(input()) D=0 for A in range(C): E(end='*'*(C-(C-A)+1));B=A while 0<B:E(end=' '+chr(42+B)*B);B-=1 E();D+=1 for A in F(): if D==0:E(end=str(A));break D-=1 ``` [Try it online!](https://tio.run/##PY9LDoIwEIbX9BTd0VJIQN0IzqIPPIEXQCnSSAqpEMPpsQQ088hk8v/fZIZ5bHt7XJYSBmfsiGrd4CuhOQpELGMOWeyjmI3uapyi4NOaTuObm3S@7USx6QSTjLMs3rovJMHziLHDNBJKkYIUNb3DHBuLXWWfmsj1TEm0rSGMwojIxCenLKO0EMB/19KLyHcVDtmjdeR0YIJGwqsSyFYELRTz05@/fWAarADS3fweHeGefHe6eqFAeeuynL8 "Python 3 – Try It Online") ## What it does? Takes a number from input, loops from 0 to \$x - 1\$ (let's call iterator \$y\$), prints ASCII 41 ("\*"), \$y\$ times with a space and prints ASCII 42, \$y - 1\$ times with a space and repeat until the \$y - x\$ is \$0\$, print a newline and go to next iteration. If the loop is ended, print the total of the output (not including the output of spaces and newlines). [Answer] # [Python 3](https://docs.python.org/3/), 106 bytes ``` C=int(input()) i=0 while i<C:i+=1;print(*[j*chr(42+j%i)for j in range(i,0,-1)]) print(C*~C*~-~C//6,end='') ``` [Try it online!](https://tio.run/##K6gsycjPM/7/39k2M69EIzOvoLREQ1OTK9PWgKs8IzMnVSHTxtkqU9vW0LqgCKRCKzpLKzmjSMPESDtLNVMzLb9IIUshM0@hKDEvPVUjU8dAR9dQM1aTC6LaWasOiHTrnPX1zXRS81Js1dU1//@3BAA "Python 3 – Try It Online") The grand total can be computed as `C*(C+1)*(C+2)//6` (see [tetrahedral numbers](https://en.wikipedia.org/wiki/Tetrahedral_number)). So you don't need `F` at all! This saves a lot of bytes. This formula can be golfed down to `C*-~C*-~-~C//6`, and then further to `C*~C*~-~C//6` because two of the `-`s cancel out in the product. Then, I just wrote some simpler code to print the ASCII characters. Usually when you want output separated by spaces, `print(*[list comprehension])` is pretty good, so I tried that. The clever thing here is using `j%i` to count like `0, i-1, i-2, ... 1` on each row. Try replacing it with just `j` and compare the output. There are only two print calls now, so `E=print` doesn't save bytes anymore. `print(end=str(num))` is longer than `print(num,end='')`. ## Tiny golfs in your code * `B,C,A=1,1,1` can be `B=C=A=1`. * `while True` can be `while 1`. * `(C-(C-A)+1)` equals `(A+1)` equals `-~A`. * `while 0<B` can be `while B` here. Making a generator and extracting the `D`-th value seems painful. You can "inline" the iterator: delete the definition of `F` and just perform the logic inside `F`, `D` times at the end of your code: ``` E=print C=int(input()) D=0 for A in range(C): E(end='*'*-~A);B=A while B:E(end=' '+chr(42+B)*B);B-=1 E();D+=1 b=c=a=0 while D:b,c,a=b+c+a+1,c+a+1,a+1;D-=1 print(b,end='') ``` If we stare at the assignments long enough, we can figure out that `b,c,a=b+c+a+1,c+a+1,a+1` can be `a+=1;c+=a;b+=c`. Also, we count up from `D=0` to `D=C`, so we can just use `C` instead of `D`: ``` E=print C=int(input()) for A in range(C): E(end='*'*-~A);B=A while B:E(end=' '+chr(42+B)*B);B-=1 E() b=c=a=0 while C:a+=1;c+=a;b+=c;C-=1 print(b,end='') ``` But an even shorter way to just repeat some code `C` times is this: ``` exec("a+=1;c+=a;b+=c;"*C) ``` Of course, the tetrahedral number formula is even shorter than any of this. [Answer] *Make sure to check out Lynn's answer. It contains some great advice too.* # [Python 3](https://docs.python.org/3/), 237 bytes ``` E=print def F(): B=C=A=1;yield 0 while 1:yield B;B,C,A=B+C+A+1,C+A+1,A+1 C=int(input()) D=0 for A in range(C): E(end='*'*(C-(C-A)+1));B=A while 0<B:E(end=' '+chr(42+B)*B);B-=1 E();D+=1 for A in F(): if D<1:E(end=str(A));break D-=1 ``` [Try it online!](https://tio.run/##PY7dDoIwDIXv9xS9Y2OQMH9ugF5sA99DZcgiGWRiDE@PI6BJ25w053ztOE/d4I7LUuPorZtIY1q4UJYTUKhRoihma/oGMgKfzvYGRL4tVKESnUhUXHPJRbLN0ERjAFHrxvdEGSMVZqQdPEiwDvzVPQzVK7@mxjUYxVFMdRpKMi4YKxTK36msVPnugojfO09PB65YrIIrRbEiWFHxoP787XXbQlWKPfuaPJUBfPPm@iRQheSynL8 "Python 3 – Try It Online") My go at this. Will keep golfing later. [Try it online!](https://tio.run/##PY5NDoIwEIX3PcXsaCkk1J8NMIu24Am8gEqRRlJIhRhOjzWoycxkMnnvezMuUze4/brWOHrrJtKYFk6U5QQUapQoisWavoGMwKuzvYGzn02@3VShEp1IVFxzyUWyzdBEY2BR68Z5ooyRCjPSDh4kWAf@4u6G6k9ETY1rMIqjmOo0lGRcMFYolL@0rFT5VwURv3WeHnZcsVgFVYrig2BFxcP252/f2xaqUny9z8lTGcBXby4PAlVwruvxDQ "Python 3 – Try It Online") [Answer] **Python 3, 132 bytes** Here is my approach to this problem. ``` C=int(input()) print(*(' '.join(['*'*(A+1)]+[B*chr(42+B)for B in range(A,0,-1)])for A in range(C)),C*(C+1)*(C+2)//6,sep='\n',end='') ``` Please refer to Lynn's answer for more details and for a much shorter code. For example, my code could be further optimized by replacing `C*(C+1)*(C+2)//6` with `C*~C*~-~C//6`. [Try it online!](https://tio.run/##RYsxEsIgEEV7T0G3u4BGY7SjAI4RLRxFg8XCIBaeHhMbmzfz3/yXP3VKvG/Nm8gVI@d3RaJVLsuUCAI2zxQZR5Ag0aodndXo5HUqOPTK0T0V4URkUS78CGj1Vq/nz8/bv/dE2kv0c7@wp6476lfIBk4MOvDNAFBrhy8 "Python 3 – Try It Online") ]
[Question] [ There is a sentence with many cats: ``` there is a cat house where many cats live. in the cat house, there is a cat called alice and a cat called bob. in this house where all cats live, a cat can be concatenated into a string of cats. The cat called alice likes to purr and the cat called bob likes to drink milk. ``` # The Task Concatenate (`_`) all pairs of neighbouring words in the sentence and place each in between the any such pair if that pair occurs more than once in the sentence. Note that overlapping counts, so `blah blah` occurs twice in `blah blah blah`. For example, if `the cat` occurs more then once, add the concatenated words in between them like this: `the the_cat cat` # Example Output ``` there there_is is is_a a a_cat cat cat_house house where many cats live. in the the_cat cat cat_house house, there there_is is is_a a a_cat cat cat_called called called_alice alice and a a_cat cat cat_called called called_bob bob. the the_cat cat cat_called called called_alice alice likes likes_to to purr and the the_cat cat cat_called called called_bob bob likes likes_to to drink milk. ``` Some more examples: ``` milk milk milk milk milk_milk milk milk_milk milk a bun and a bunny a bun and a bunny milk milk milk. milk milk milk. bun bun bun bun. bun bun_bun bun bun_bun bun bun. ``` # Notes * All `utf-8` characters are allowed. Meaning that punctuations are part of the input. * Punctuation becomes part of the word (e.g., with `in the house, is a cat` the word `house,` includes the comma) [Answer] # [Python 2](https://docs.python.org/2/), ~~99~~ ~~107~~ ~~103~~ 102 bytes ``` def f(s):S=s.split();T=zip(S,S[1:]+[s]);return' '.join(x+(' '+x+'_'+y)*(T.count((x,y))>1)for x,y in T) ``` [Try it online!](https://tio.run/##XVFBboMwELz3FXuzXRBSekxEPwG3KKoMmOLirJFtWujn6UIQhB5sze7M7I7lbgyNxbdpqlQNNffinKU@8Z3RgYtLnv7qjmdxdj2db9HV38TFqdA7ZMCSL6uRDxEnHA0R@2DRKF55npS2x8D5EI9CvJ9EbR0QBo2Qi8mnLDTKKdAeJJQyQGN7r@Bnad4ljnPTg9HfKpk9pN5lMfwzl9IYVYE0ulQgsTq2C1usM8jwvIfofU28mRAKWmaRKoV0KjIHS7QPTuMn2PrhumvTJpCvyQ4ZjG6VBzJ1vXNLonCUUaZdVNHY9jGOvXRUhOUPNshmCraLPTESih7XJxPCkYnpDw "Python 2 – Try It Online") Fixed the `milk milk milk` style edge cases. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~23 22 21~~ 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḳµżj”_$ƝḢKċ@Ị¥?€`K ``` A full program which prints the output. **[Try it online!](https://tio.run/##ZYw9CsIwFICv8gZXvYCDzgbPoKGJ@kryIskrkk0c9QxdBDcnQSjoVNR7tBeJInVy/n5ybUxMqaku9fV5z9ttOeu9yqY6isdh3Nz29WnU7s5zkVKaaoUsGR0BBiDHsHDGuA3SEiRFCDGwtkNA/vHMUWBJDF6vNeM3laQAbTcawP/0E2Wa2HdCHyaoVAHCY1iRtIVnfAM "Jelly – Try It Online")** Or see a [test-suite](https://tio.run/##ZU@xTsMwEN35ilPEGOUDWGDvyoZQcWJDnbh2FTtU2QoLEvwCXZDYmJCIKlExGMp/JD/iXkzUNHQ46/zuvXvvUiZE6Vy9ercfm3XaLJbj499lvXoZ/Tyd1Z@P9vW0uX@7GrnN@vsBuxSrWTzb6sRWSE6buy9b2cq5i8BMWM6AayCQEAMTVWgGcw9OiSxbUIPgtywCLgHZPS2Ef@KECMEoEMETBkTSIRyruNuBgn0fHPc24U4kIUYzJfHHJBZFsVE41ibn8gbUtVdFcN6FGtgLnjENyJ8Vee7DmCEN4/QkihszmHKRRcFRGLQN7J4WIRAXsrsJO1ke0ryyZe2Vx/zBGi8WFGa5ogXGa7HxHxZcbgE "Jelly – Try It Online"). ### How? ``` Ḳµżj”_$ƝḢKċ@Ị¥?€`K - Main Link: list of characters T Ḳ - split (T) at spaces (call this W) µ - start a new monadic chain (i.e. f(W)) Ɲ - for neighbouring pairs: $ - last two links as a monad: j - join with... ”_ - ...underscore character ż - zip (with W) (making pairs of ["left", "left_right"] - plus a trailing ["rightmost"]) ` - use this as both left and right arguments of: € - for each: ? - if... ¥ - ...condition: last two links as a dyad: @ - with swapped arguments: ċ - count occurrences of right in left Ị - is insignificant? (abs(x) <= 1) Ḣ - ...then: head ( ["left", "left_right"] -> "left" - or ["rightmost"] -> "rightmost") K - ...else: join with space (["same", "same_same"] -> "same same_same") K - join with space characters - implicit print ``` [Answer] # [Zsh](https://www.zsh.org/), 103 bytes ``` t=($=1) for b a (${${t:1}:^t})s+=(${a}_$b) for w ($s)((++i,${#s:#$w}-$#s+1))||s[i]= echo ${t:^s} $t[-1] ``` [Try it online!](https://tio.run/##XY5NboMwEIX3nGIkLAULgsQWiVt0FyWVDaZYOHblcYpa4rPTCY1K6cILz/vezxcOS5/xeQlNxpqKJ73zIEFAxmY2h7qK9SVEjjnJs4ivTP4gEwHIsyzPdcHmFOuUTfHIUswrzu93POlzk6h2cPBIuWAEFk7H6rzEpIdDGJRXoJF6WhFgcDdUMK3Hq7CfjyOC0R@qBG2B6A0r4J@5FcaoDoTRrQJhu/1ZOvnMIMPfHpK3muLXZEFSmbP0U5ZeR@bgSMbgtX0D16@uEl6eo3b1Ro8Kgfj3m/frmLDHaM4GdZQ4wlWbsTws3w "Zsh – Try It Online") The key constructs used here are: * `${=1}`: splits the first parameter into words (because there are no other flags, the {braces} are optional) * `${a:^b}`: substitutes array `$a` zipped with array `$b` * `${a:#b}`: substitutes array `$a` with all instances of `b` removed. * `${# }`: the length of the contained expansion. * `echo`: [`<<<` leaves extra spaces](https://tio.run/##qyrO@P8/0VYjUUFdXSFJkys1OSNfQSWRy8bGBkj9/w8A "Zsh – Try It Online") If the input is already split into words, [99 bytes.](https://tio.run/##XY5Ba4QwEIXv/ooBc0jQCu1RWOhP6KG30i2JxjWYTUomu9K6@e12lKXWHsKQN997b76xnzsuprnzARRI4Gxi03P9lOqjDKdrElgcSJPpgymRLdRIDArOi8KUbMqxztmYHliOxaMQtxu@mfdDppvewxJ0xESTv4g8zSnrIPY6aDBIVY2M0PsLahhX8Szd1yIiWHPVFRi30BtW/jc30lrdgrSm0SBdu5eVV/cMMvztofVWU/6aHCgq845@2tFryRw9rTEG407gu9VVwev9qF29NYNGIP7zEsJ6TNxjdM4GtZQ4wNnYoZp/AA "Zsh – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~32~~ 27 bytes ``` ;⁶Ḳṡ2W€jj”_W$Ɗ€ĠL’$ƇẎƊ¦Ṗ€ẎK ``` [Try it online!](https://tio.run/##XY@xTsMwEIb3PMXJ6hgysCLxAjAiVQhVyEkMdeLaKHZA2doulTowIiGBBAtThQQDogwMBeU94hdxL1HUEAZbd7//7/5zwoQonDuws4/q871aP@8P7XyVJHb6eD4clEtsfp@O7fR@UC6qr9tyuXmp1neoYnPk/J@FnX0Tkti3V0QeYO8QkPRQnq9OnTvziBmzjAHXQCGiBsYq1wxuGnFCZVGLGgS/ZgFwCejubD78gyMqBIuBCh4xoDLuy6EK2xkI/M3B5y7G30ESQgxTEjsm8cQIG4XP2mRcXoK6aKgATtqlevGCp0wD@q/yLGuWMX0brtOZYpyYwoSLNCC@R@oCdletUAhz2f4JK1kQb7QF "Jelly – Try It Online") Shorter and more correct! Thanks to @JonathanAllan for highlighting an issue with "milk milk milk"! A monadic link that takes a Jelly string as its argument and returns a processed Jelly string. ## Explanation ``` ;⁶ | Append a space Ḳ | Split at spaces ṡ2 | Sliced of length 2 Ɗ¦ | At the indices indicated by the following: Ġ | - Group indices of equal values Ƈ | - Keep only those where the following is non-zero: L | - Length ’ | - Decrease by 1 Ẏ | - Tighten (join outermost lists together) Ɗ€ | Do the following as a monad: W€ | - Wrap each word in a list j $ | - Join with the following: j”_ | - The two words joined with "_" W | - Wrapped in a list Ṗ€ | Remove last member of each list Ẏ | Tighten (join outermost lists) K | Join with spaces ``` [Answer] # JavaScript (ES6), 94 bytes ``` s=>s.split` `.map((w,i,a)=>a.some((W,j)=>j!=i&W==w&a[j+1]==(p=a[i+1]))?w+` ${w}_`+p:w).join` ` ``` [Try it online!](https://tio.run/##jVDNasMwDL7vKbQyOptkhl0H7l5i0EM3FiVxW6WOHGK3oYw9e6aW0q49jB1sJH1/Qg3uMFY9demJQ@3GpR2jnUUTO0@pgMK02Ck15JSjtjM0MbROqXneSNfcW5rOrR2muGiy5w9rVWdxQVJq/TpkBTx8Dd@fRda9DNo0gVgMxypwDN4ZH1ZqqSZp7XoHFAGhwgTrsI0OhuOwRd4fhhE87ZwBYhD2hZbDjbhC710N6KlygFxfj8tQnjxE8DtH4EtMfhYxlBIWWDrH8moRpyBwTD3xCsLyqDLwdlrqKt7TxkUQfrft@@My6Zom61xItThuoCW/MRMNGTy@86O@uznVAYbz91/eH4YI5ZZPh5KK9xOtxx8 "JavaScript (Node.js) – Try It Online") [Answer] # [J](http://jsoftware.com/), 69 bytes ``` ;:inv@(a:-.~],@,.a:,~(2(,'_'&,)&.>/\])#&.>~1<1#.[:=/~2<\])' '<;._1@,] ``` [Try it online!](https://tio.run/##dUtNC4JAFLz7K4YEn8LzmR5XDSHo1KlriVgkbpmeKk/71zeDEDoI88EMMze7EmqQKxAYa6iJoWB72O9sqnT/KvxahWJKLlhqxcZPfKaKPA482USnMnAnN3EWu3JUeWSSbOoIlKVSxQWXNnCc66Ud0IC64Q3dYxy/@IXz849C8/qhuztmWeoXD4xWk/0A "J – Try It Online") # [J](http://jsoftware.com/), 56 bytes (but breaks on commas) ``` (a:-.~],@,.a:,~(2(,'_'&,)&.>/\])#&.>~1<1#.[:=/~2<\])&.;: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NRKtdPXqYnUcdPQSrXTqNIw0dNTj1dV0NNX07PRjYjWVgXSdoY2hsl60la1@nZENUExNz9rqvyYXV2pyRr5CmoJ6Tn65QmaeQkUFCEE5SaUoWE8drjo3MydbAU7gEtdT/w8A "J – Try It Online") ## explanation for both A bit verbose but the underlying idea is nice, so I'll explain that with pictures: Let's start with this input: ``` low in xx xx low in bun bun bun bun. ``` First we turn it into words: ``` ┌───┬──┬──┬──┬───┬──┬───┬───┬───┬────┐ │low│in│xx│xx│low│in│bun│bun│bun│bun.│ └───┴──┴──┴──┴───┴──┴───┴───┴───┴────┘ ``` And then create the underscore concatenation of *every* pair, plus a blank item at the end: ``` ┌──────┬─────┬─────┬──────┬──────┬──────┬───────┬───────┬────────┬┐ │low_in│in_xx│xx_xx│xx_low│low_in│in_bun│bun_bun│bun_bun│bun_bun.││ └──────┴─────┴─────┴──────┴──────┴──────┴───────┴───────┴────────┴┘ ``` Let's zip these together and see where we're at: ``` ┌────┬────────┐ │low │low_in │ ├────┼────────┤ │in │in_xx │ ├────┼────────┤ │xx │xx_xx │ ├────┼────────┤ │xx │xx_low │ ├────┼────────┤ │low │low_in │ ├────┼────────┤ │in │in_bun │ ├────┼────────┤ │bun │bun_bun │ ├────┼────────┤ │bun │bun_bun │ ├────┼────────┤ │bun │bun_bun.│ ├────┼────────┤ │bun.│ │ └────┴────────┘ ``` We notice that if we could keep just the items we want in the right column, we could flatten the whole thing, unbox, and we'd be done. So we want a filter for the right column. Let's start by treating the consecutive pairs of input words as single units (again, with a blank at the end): ``` ┌────────┬───────┬───────┬────────┬────────┬────────┬─────────┬─────────┬──────────┬┐ │┌───┬──┐│┌──┬──┐│┌──┬──┐│┌──┬───┐│┌───┬──┐│┌──┬───┐│┌───┬───┐│┌───┬───┐│┌───┬────┐││ ││low│in│││in│xx│││xx│xx│││xx│low│││low│in│││in│bun│││bun│bun│││bun│bun│││bun│bun.│││ │└───┴──┘│└──┴──┘│└──┴──┘│└──┴───┘│└───┴──┘│└──┴───┘│└───┴───┘│└───┴───┘│└───┴────┘││ └────────┴───────┴───────┴────────┴────────┴────────┴─────────┴─────────┴──────────┴┘ ``` The filter we seek is simply any element that occurs more than once. To find this we'll create a function table of equality: ``` 1 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 ``` And sum it rowise or colwise (the direction doesn't matter, since it's symmetric): ``` 2 1 1 1 2 1 2 2 1 1 ``` And find all entries greater than 1: ``` 1 0 0 0 1 0 1 1 0 0 ``` This filter is all we need to carry out our plan from above and arrive at the answer. ]
[Question] [ Assume that there is a number `a`. In every conversion of that number, the number can either convert itself to its value plus the value of one of its digits, or convert itself to its value minus the value of one of its digits. In this situation, find the minimum number of conversions one has to make in order to get to the number `b`. If b cannot be reached, output `-1`. ## Input Input one line containing the integers a and b (where 1 <= a, and b <= 10^6). ## Output Output a line containing one integer, which represents the minimum amount that one has to convert the number. ## Example input and output (s) ``` Input: 1 10 Output: 5 ``` Why? ``` 1 -> 1+1=2 -> 2+2=4 -> 4+4=8 -> 8+8=16 -> 16-6=10 => 10 ``` The shortest program wins, as this is a code golf question. [Answer] # JavaScript (ES6), 98 bytes Takes input as `(a)(b)`. Can be very slow if there's no solution, but it should eventually return \$-1\$ (at least in theory). ``` a=>h=(b,k=0)=>(g=(v,n)=>n--?[...v+''].some(x=>g(+x+v,n)|g(v-x,n)):v==b)(a,k)?k:k<a+[b]?h(b,k+1):-1 ``` [Try it online!](https://tio.run/##bYzBDoIwEAXv/gi7KW0AvUDY8iGEQ0EoWmyNmIaD/17LGZJ3mExe5qm8WofP4/3l1t3HMFFQJGeCPjWUIUnQBD61kSznTSuE8CxJOrG61wgbSQ1sY/vhp8HzLQJWnqhHUKnBxlSmVqztu2bekyzHiudhcHZ1yygWp2GCHOPwcpTZmS0PskAoTmwZC7ezwhUx/AE "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~38~~ 37 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 3Ýo*Êß8LIå*i®ë¹¸[DIå#¼Ùvy©v®y+®y-}})}¾ ``` Can definitely be golfed a bit more.. Thanks to [*@tsh* for the condition of the first if-statement](https://codegolf.stackexchange.com/questions/187238/number-conversion/187364#comment448548_187238). [Try it online](https://tio.run/##yy9OTMpM/f/f@PDcfK3DXYfnW/h4Hl6qlXlo3eHVh3Ye2hHtAuQqH9pTVnloZdmhdZXaQKxbW6tZe2jf//@GXJYA) or [verify a few more test cases](https://tio.run/##yy9OTMpM/V9Waa@koGunoGRfmeASVuwS@t/48Nx8rcNdh@db@EQeXqqVeWjd4dURh3ZEuwB5yof2lFUeWll2aF2lNhDr1tZq1h7a979WR@/QVkONQys1Y/5HRxvrGMfqRBvqGBqAKUsgaaRjBKYsdQxNwIJgFSCFsQA). **Explanation:** ``` 3Ý # Push the list [0,1,2,3] o # For each value, take 2 to the power that value: [1,2,4,8] * # Multiply each by the first (implicit) input Êß # Check that the second (implicit) input is NOT in this list 8L # Push the list [1,2,3,4,5,6,7,8] Iå # Check that the second input is in this list *i # If both are truthy: ® # Push -1 ë # Else: ¹¸ # Push the first input again, and wrap it into a list [ # Start an infinite loop: D # Duplicate the list at the top of the stack Iå # If the second input is in this list: # # Stop the infinite loop ¼ # Increase the counter variable by 1 v # Loop over each number `y` in the list: y© # Store the current number `y` in variable `®` (without popping) v # Inner loop over each digit `y2` of `y` ®y+ # Add digit `y2` to integer `®` ®y- # Subtract digit `y2` from integer `®` }} # After the nested loop: ) # Wrap all values on the stack into a list for the next iteration }¾ # After the infinite loop: push the counter variable # (and output the top of the stack implicitly as result) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~33~~ 29 bytes ``` 0ịD;N$+Ɗ;@€)ẎL<¥Ƈȷ7Ʋ=⁴¬ȦƊ¿ẈṪ’ ``` [Try it online!](https://tio.run/##AUYAuf9qZWxsef//MOG7i0Q7TiQrxoo7QOKCrCnhuo5MPMKlxofItzfGsj3igbTCrMimxorCv@G6iOG5quKAmf///1tbOV1d/zIz "Jelly – Try It Online") A full program that takes `[[a]]` as the left argument and `b` as the right argument. [More efficient version (36 bytes)](https://tio.run/##AVMArP9qZWxsef//MOG7i0Q7TiQrxopR4bifwq47ybzhuZskO0Digqwp4bqOTDzCpcaHyLc3xrI94oG0wqzIpsaKwr/huojhuarigJn///9bWzldXf8yMw) [Answer] # [Python 2](https://docs.python.org/2/), ~~104~~ ~~99~~ ~~96~~ ~~93~~ 95 bytes ``` f=lambda a,b,i=0:i*(b in a)-(0<b<9<i)or f({x+int(c+d)for x in a for d in`x`for c in' -'},b,i+1) ``` [Try it online!](https://tio.run/##VcxBCsIwEIXhvaeYXTM2haRBsJKeRIQmDcGApqV0ERHPHiddSN39fMyb@bXep9jm7PuHeVpnwHDLQy8u4cgshAgGGya01Z0OOC3g2TvVIa5srB16grQdQUlHOaSh5EhZQVN9yrdaYp6XMvLsKm8cQArEw49OgkztZTs670W1ZEr87aSgIUn@Ag "Python 2 – Try It Online") This function takes `a` as a list (or set, or any other collection really), which is not ideal, but the Jelly answer does something similar it seems. My original approach with varargs couldn't be used because I needed the `i` parameter, with a default value, to return -1 if no answer can be found. @tsh's prerequisites for there not being an answer are partially used. However, instead of the expensive and highly unpractical (for golfing) second part of that condition, we simply let the recursion run for a little while to see if an answer is found anyway. # Explanation ``` f=lambda a,b, # a and b are as defined in the i=0: # challenge; i is a counter i*(b in a) # Return the counter if b is found -(0<b<9<i) # This is the only code needed for the # existence problem or f( # Recursively call the function {x+int(c+d) # All possible numbers in the next step for x in a # All numbers in this step for d in`x` # All digits of those numbers for c in' -'}, # Either positive or negative (making # good use of the fact that int() # ignores leading whitespace) b,i+1) # Increase the counter ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 217 bytes Correctly returns -1 now if b can't be reached, thanks to @tsh for the formula ``` (a,b)=>{var l=new List<int>(){a};int r=-1,z;if(!(b<9&!(b==a|b==2*a|b==4*a|b==8*a)))for(r=0;!l.Any(x=>x==b);r++)l.ToList().ForEach(x=>(x+"").ToList().ForEach(y=>{z=y-'0';l.Remove(x);l.Add(x+z);l.Add(x-z);}));return r;} ``` [Try it online!](https://tio.run/##bY4/b4NADMX3fopLhsYOf0RohqKLkTI0U6aqUueDHOpJ9JAOkgIpn52atupQMth@@j0/2Xkd5LUZD2eb74xt/N9KRSFoBOVnSOn1opwoyeoPcTR1M@2lgFc1SFbCUbDxe2kKWEC2S@65E6lPbvH6e2x/xuNaIWJROXAUyUUZ7m0HLaUtUYbSeR6W4Us1HQAMD5V7Uvnb5EPrLZc4tzp@rKcuWEUrWYbP@r26aGiR9f504lD/JwOWA/IN3ZydFU4Oo7x7dabRR2M1FLDxxYb9GYtuwOQ/i30Rz2HC8e2N@AOz8Qs "C# (Visual C# Interactive Compiler) – Try It Online") ]
[Question] [ **This question already has answers here**: [There Was an Old Lady](/questions/3697/there-was-an-old-lady) (31 answers) Closed 5 years ago. So, there's a famous children's rhyme... ``` This is the house that Jack built. This is the malt That lay in the house that Jack built. This is the rat That ate the malt That lay in the house that Jack built. This is the cat That killed the rat That ate the malt That lay in the house that Jack built. This is the dog That worried the cat That killed the rat That ate the malt That lay in the house that Jack built. This is the cow with the crumpled horn That tossed the dog That worried the cat That killed the rat That ate the malt That lay in the house that Jack built. This is the maiden all forlorn That milked the cow with the crumpled horn That tossed the dog that worried the cat That killed the rat that ate the malt That lay in the house that Jack built. This is the man all tattered and torn That kissed the maiden all forlorn That milked the cow with the crumpled horn That tossed the dog that worried the cat That killed the rat that ate the malt That lay in the house that Jack built. This is the judge all shaven and shorn That married the man all tattered and torn That kissed the maiden all forlorn That milked the cow with the crumpled horn That tossed the dog That worried the cat That killed the rat That ate the malt That lay in the house that Jack built. This is the rooster that crowed in the morn That woke the judge all shaven and shorn That married the man all tattered and torn That kissed the maiden all forlorn That milked the cow with the crumpled horn That tossed the dog That worried the cat That killed the rat That ate the malt That lay in the house that Jack built. This is the farmer sowing his corn That kept the rooster that crowed in the morn That woke the judge all shaven and shorn That married the man all tattered and torn That kissed the maiden all forlorn That milked the cow with the crumpled horn That tossed the dog That worried the cat That killed the rat That ate the malt That lay in the house that Jack built. This is the horse and the hound and the horn That belonged to the farmer sowing his corn That kept the rooster that crowed in the morn That woke the judge all shaven and shorn That married the man all tattered and torn That kissed the maiden all forlorn That milked the cow with the crumpled horn That tossed the dog That worried the cat That killed the rat That ate the malt That lay in the house that Jack built. ``` Obviously, it's pretty process-based, you could totally write code for this, right? --- * Write some code which outputs the full text of "The house that Jack built". * Standard rules and loopholes and stuff. * Any language you like. * Try to do it in the smallest number of bytes. * I always like to see [TIO](http://tio.run) links. * The case must match the rhyme. * Each line of the rhyme must be on a new line of text. * White-space before and after the line is fine. * No punctuation, except the full stop at the end of each verse. --- Edit: Earlier versions of this question contained an issue with this line This is the rooster that crowed the morn It was inconsistently applied. To be clear; this should be one line on every occurrence, and should be added at once. --- Further edit: It's been declared that this question is a duplicate of: [We're no strangers to code golf, you know the rules, and so do I](https://codegolf.stackexchange.com/questions/6043/were-no-strangers-to-code-golf-you-know-the-rules-and-so-do-i) However, while you could take the same approach, compressing the text as much as possible. There's also a chance to take a procedural approach to this rhyme, following the structure of the rhyme itself. Some of the solutions take this approach, so I'd say it is a similar, but distinct challenge for this reason. [This answer](https://codegolf.stackexchange.com/a/161993/16824) suggests that it's actually better to take the approach to this question which would not work for Rick Astley. It is, however, a duplicate of the old lady song, and the 12 days of Christmas. I've voted to close it. (although, those two were not declared duplicate of each other). [Answer] # JavaScript (ES6), 356 bytes Procedural approach. ``` _=>`house th5 Jack built. |malt6lay in|r565e|c56kill2dog6worri2cow with0crumpled h16toss2maiden3forl16milk2man3t5tered4 t16kiss2judge3shaven4 sh16marri2rooster6crowed in0m16woke|farmer sowing his c16kept|horse40hound40h16belonged to`.replace(/\d/g,n=>` the ,orn,ed|, all , and,at, That `.split`,`[n]).split`|`.map(s=>`This is`+(p=' the '+s+p),p='').join` ` ``` [Try it online!](https://tio.run/##LY/BbsMgEETv@QpusRXqxEnMLf2AnnNrq0JhbYiBtQDHquR/TzdVL7va1cwbzU3dVdbJTeUlooFHf3l8XV6lxTkDK7Zjb0qP7Ht2vjSbNShfhFc/zMU1daKDVXdidN4fDQ5iwZTcUePCFlfsQac5TB4Ms60omPMxKGcgnnpMvhXB@ZE@8VS6AgnMmZWWUCS7zWaAU7bqDvHMMrmDeoITYiap0AkXorp4CC1ljrD2KgVILOPi4sCsy0wTC6ayWkwZzgeqEw2tVnyDxziQvaBsEkxeaaj2H2Y/8Ei9qTIwjilyMCtnyntGMxquCt9crSpMNnnyrkgu3@Nn/X@ssglqqjIRrs94l@Wumi7bP9x2l3dTzenc1s0NXZQb@dAYM3poPA5VX9X14xc "JavaScript (Node.js) – Try It Online") --- # Simple compression, 429 bytes Using [RegPack](https://siorki.github.io/regPack.html). ``` _=>[...'IKLMNOPQRSUVWXYZ[]^_0qxz{}~'].reduce((s,c)=>(l=s.split(c)).join(l.pop()),`TNis_ZOlt }{rQ z^}{cQ Sz^ }KM}]M}xI[I~Z0ZYZLrseULundU{hWbelongV toY~{judgeRshavenU shWmarriV[MP}PZ{ the z ThQ xOidenRforlWmilkV]qworriV{cQS 0{rooster XcrowV in{mWwoke~_Luse XJack built.^QeOlt]{cow with{crumplV hWtossVK[OnRtQterVU tWkissVxZ TNisY{farmer sowing NcWkept0XthQ WornzVedU andSzkillV{rQR all QatPzlay in_O{maNhis Mzqz^L{hoK{dog IXqX^}`) ``` [Try it online!](https://tio.run/##FZDPbqMwGMTveYrvVpC6KC@Q3rOBEEj5ExBQ1zjgYGxim5LFIq@epdfRaOY3c0M/SGFJB/2Hi5q8rrtXtfvIHcd52x9c7@ifgvAcxUl6yfKirLb3x2yW51vhSFKPmFiWesf27sNiO@WogVFtYdt2boJyizmDGCzbfv/6PFJVZT7TsBgZwFwuBgdwnktYDt5SeMtjn@@f2Ta7ZK5UJHJHXkemTb4JE7yJQYvL09zGuiGhatEP4RGoNumRlDTOvdNyygzolsC8@WwDePi0Jjy8CsmSnrIuLu6T@LWupWfYGimE0kRCiqWYYqDc9MkkOvKs3FERSP8i3MH3SJl2yoCs1IXBYoKJ6tZgOfYDi6FNtFAqPuQ@D3WwpsUR6KSjq/bINpvfwRdzRbJfe5SYKG/giJOODHqb6pUxEZLPMakjQLw@zx1lLF6vCQExBgHSp5mhfyta5ZseHVuqwJvvc@maVhxMLRrYp/e0XL7sFxZcCUYcJhrrur79@g8 "JavaScript (Node.js) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~398~~ 397 bytes ``` for i in range(12):print'\nThis is the',''.join(dict(zip('012345','\nThat , the ,orn,ed, all , and'.split(','))).get(c,c)for c in'1'.join('horse51hound51h20belong3 to|farmer sowing his c20kept|rooster that crow3 in1m20woke|judge4shaven5 sh20marri3|man4tatter35 t20kiss3|maiden4forl20milk3|cow with1crumpl3 h20toss3|dog0worri3|cat0kill3|rat0ate|malt0lay in|house that Jack built.'.split('|')[~i:])) ``` [Try it online!](https://tio.run/##PZDBboQgEIZfhRuSGKOil32Ennvb9sAiq7MiY2Cs2Yb01e3YNk1IIDP/fP/PrE@aMLTHcccoQEAQ0YTRFU2rLmuEQPItvE6QBB@anCylrB4IoRjAUvEJayHrptVdz51TaUiUp1CUGEPphlIY77lkwiCrtHqggpVKqWp0VNjSqtPYsrFs/shywphc30y4hYGvtr45j2HUgjDfTVxcFAl3CKM4g9m2nt1KOSIm4hadGWzEXTO0Wdp6x9nlxzaMrkuT@XChF4mhi4kRdF5M6MgQT@peELMgpbMKgwsdZ/OsBD/rbHEXO9DU2Lgtq9eCGYSneMCRTX5o1hATvNc58suQY5Kn2psnh8n8o@R@A74YO4vbBp6q/71kqa5fcHlX6ji@AQ "Python 2 – Try It Online") --- # [Python 2](https://docs.python.org/2/), ~~401~~ 398 bytes ``` for i in range(12):print'\nThis is the',' the '.join('horse and the hound and the horn?belonged to|farmer sowing his corn?kept|rooster that crowed in the morn?woke|judge all shaven and shorn?married|man all tattered and torn?kissed|maiden all forlorn?milked|cow with the crumpled horn?tossed|dog?worried|cat?killed|rat?ate|malt?lay in|house that Jack built.'.split('|')[~i:]).replace('?','\nThat ') ``` [Try it online!](https://tio.run/##RVBNa8MwDP0rvjmBEViPvfS@827bDq6jxmocK8jKQsHsr2eyOxgYLEvvQ37rQwKl03HciA0aTIZdmqB7PfXnlTGJ/UzvAbPRIwHsi62XscOdMHU2EGcwLo2tG2jT6v/F6XKFSKqnHSo3xwuwybRjmkwV9RUywyqFibLoUIIT45l2pegyVWepoJ1mKPdtnNQtRpOD@4bUrHLzWRwzwlgWlxpAnKgc/G3TbDDnBsARnhj9cmxcjLNOPO1mRwnN1PO2rFH5TV2ocUeadJGnkXeiklEhhbV0Aiod5RLdQxcvGoUG037z5vxsrhtGGeyQ14jS2WL7jx88f/UDwxqdh85eNNuatTJsfxy/ "Python 2 – Try It Online") --- Saved * -3 bytes, thanks to Jonathan Frech [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~256~~ ~~245~~ 241 bytes ``` “x´ž€†0ƒé€Š Jackíš.xâì0íàltx¨Ù0ÄŠxܳ0—Äx€„ssed0‹·x«Ëed0Ч€Ž0 crumpledÑÛx·—ed0움Ÿ€‡lornx¢¢0…Ž€Ÿ»ättered€ƒ€„rnx woke0¡Ë€Ÿ shaven€ƒ shornx¤°0ÝËoster€Š crowed€†0›árnxÊÂed€„0ÃË€Êwing€ËÃÅx0ƒ0 hound€ƒ0ÑÛ“0’ €€’:'x¡'€Š™ìηʒRćD'€€kG¦}„€Œ€ˆªì¸ì»¶«, ``` [Try it online!](https://tio.run/##LZDLSsNAFIZfJbtuRMaFG9eC4NI3qO1gpTWRpDWzEUqtCs1Gi5tiLUkp9dILgmKrpS7Ob7pQ8CHyIvHMxMXAuXzn/@ccsZnf35BpmtS7il7jz6QxTuqhWLXxyGEcWrv5QhmTOFpX6GMsMEFYqSp6QEegGYcKXXoRSf0GTWVme54ni1x4p5miEQJOcEX3WmwprIJbOzquyCKucatoxnO6z2MfGpgbhajiuLaiPvVZZhgvTYcWGFSr0pVFTlftzIoxy3fKUlCEwGCWV8qfSNswHBuhAT0L3CFwPJ7Pliq4jm@U9K5sjohBtND4L/YEzowiWv6hfaCDgCvnSmCqAS0vrJJTs7PvCL0Pn5C1OlYGcLSVUxTljGPS5OP9zr7be1@X27mMKO/Q8JS9NKAX@rmgJ4xpzm9BbzRaS9M/ "05AB1E – Try It Online") [Answer] # Java 8, ~~666~~ ~~649~~ ~~640~~ ~~636~~ 625 bytes ``` $->{String y="This is",x="That ",w="orn\n",A="~house that Jack built.\n\n",B="~malt\n",D="~rat\n",F="~cat\n",H="~dog\n",J="~cow with~crumpled h"+w,L="~maiden all forl"+w,N="~man all tattered and t"+w,P="~judge all shaven and sh"+w,R="~rooster that crowed in~m"+w,T="~farmer sowing his c"+w,r=y+A,a[]={B,"lay in"+A,D,"ate"+B,F,"killed"+D,H,"worried"+F,J,"tossed"+H,L,"milked"+J,N,"kissed"+L,P,"married"+N,R,"woke"+P,T,"kept"+R,"~horse and~hound and~h"+w,"belonged to"+T};for(int i:"123425642786429:8642;<:8642=><:8642?@><:8642AB@><:8642CDB@><:8642EFDB@><:8642".getBytes())r+=(i%2>0?y:x)+a[i-49];return r.replace("~"," the ");} ``` Well.. NOTE: It's just like every other (non-encoded) answer incorrect for the verses about the `maiden` and `man`, where the lines of the dog and cat, as well as rat and malt are on a single line, instead of new-line separated.. I'm just too lazy to fix it, since it's closed as a dupe anyway. **Explanation:** [Try it online.](https://tio.run/##RVLbjtowEH3vV1ijrZQoJmopvSxp2EIpQogitEV9YXkwiQGDsZHtkEUIfp2OE9pKiX1mjmc0l7NlR9bY5rtbJpm15CcT6vyGEKEcNyuWcTLxJiG/nBFqTbLgtxY5eQgT9F7wx8865kRGJkSRlNweGp3z/fEphdlGWCIs0FePmSNAyxS0US8KaDeF60YXlhPnqRHLdmRZCOnil4rvIb9n0nncR2xYBQcIsxoOEeZ67eHIe3VJSuE218wU@4PkOdlAVNJxlUfkXBEmJVlpI717UrlrH7aADWMAUzlxnp0iuy3yNa94u2FHH46srXI@@3q0thhVV58ZXWK8UNe952fIr5jZI2116afhJ5F5yqSnqEvZfJGeexQkO2EQoKdPgTkOUY8OKOyExPoh6tMhhVIbI7w1oCMKTlvrjSEdU9gLufPGiE58UM2M6RQZdg@a0GefYoepp3SGr/gBO0QfDt/g8LEpvwaV18iXCEsutVpjP05DNLskOLMANUFEG943P7SaHz@1mp@/4PHY9mfytbrSTn0/fbuDbu8v@t7/B38M/mOI19z1To7bIAxNlAbibbPz7unUfg0jNheN1uMiMdwVRhETG36QKMkArkABp84JhMnlltQyPBRLiTK8q/HoZYpLV0EtxvmChXcln3Bp@1gXLj4g4wIVZ4EqpAzvor7c/gA) ``` $->{ // Method with empty unused parameter and String return-type String y="This is", // Temp-String "This is" x="That ", // Temp-String "That " w="orn\n", // Temp-String "orn\n" // " the ...\n" temp Strings: A="~house that Jack built.\n\n", B="~malt\n", D="~rat\n", F="~cat\n", H="~dog\n", J="~cow with~crumpled h"+w, L="~maiden all forl"+w, N="~man all tattered and t"+w, P="~judge all shaven and sh"+w, R="~rooster that crowed in~m"+w, T="~farmer sowing his c"+w, r=y+A, // Result-String, starting at: // This is the house that Jack built.\n\n a[]={ // String-array, containing: B, // the malt\n "lay in"+A, // lay in the house that Jack built.\n\n D, // the rat\n "ate"+B, // ate the malt\n F, // the cat\n "killed"+D, // killed the rat\n H, // the dog\n "worried"+F, // worried the cat\n J, // the cow with the crumpled horn\n "tossed"+H, // tossed the dog\n L, // the maiden all forlorn\n "milked"+J, // milked the cow with the crumpled horn\n N, // the man all tattered and torn\n "kissed"+L, // kissed the maiden all farlorn\ P, // the judge all shaven and shorn\n "married"+N, // married the man all tattered and torn\n R, // the rooster that crowed in the morn\n "woke"+P, // woke the judge all shaven and shorn\n T, // the farmer sowing his corn\n "kept"+R, // kept the rooster that crowed in the morn\n "~horse and~hound and~h"+w, // the horse and the hound and the horn\n "belonged to"+T}; // belonged to the farmer sowing his corn\n for(int i:"123425642786429:8642;<:8642=><:8642?@><:8642AB@><:8642CDB@><:8642EFDB@><:8642".getBytes()) // Loop over the bytes of the String above r+=(i%2>0?y // If `i` is odd: Append "This is " :x) // Else (`i` is even): Append "That " instead +a[i-49]; // And also append the string from the array at index `i-49` return r.replace("~"," the ");} // Return the result, with all "~" replaced with " the " ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~322~~ 308 bytes ``` 0horse20hound20h3belonged to0farmer sowing his c3kept0rooster that crowed in0m3woke0judge all shaven2 sh3married0man all tattered2 t3kissed0maiden all forl3milked0cow with0crumpled h3tossed0dog1worried0cat1killed0rat1ate0malt1lay in0house that Jack built. 3 orn1 1 ¶That L^$`0.* This is$&$'¶ 2 and 0 the ``` [Try it online!](https://tio.run/##JY8xbsMwDEV3nUJD0AIdAsm6RdExcxFGYixVshhIdI1eLAfIxVzanj7BR35@NuRUwa6rMpFax0FkrkHE3bBQHTFoJnOHNmHTnZZURx1T195lfLBpRJ2FcATWvtEi86mayS2U0fzMYUQNpege4RfrIOomaC1hMBPUHTGwOGAYNLucet9RCnjQO7XiplSytD0tekkcjW/z9ChyKjqmfSPQaBc6jD2wzakIN01KYBTDwrbA35ZNHux4BP4En/VtToXPyilq1SqrXs/LxtTX9@lqzh/qsr2b@unt9P56qkFpqEEZJQ6o1/Uf "Retina – Try It Online") [Answer] # [Jstx](https://github.com/Quantum64/Jstx), 293 [bytes](https://quantum64.github.io/Jstx/codepage) ``` ↕Δ"▌ÇÇÉÇ◙ëÇÇÇÇÇÇǬÜëºΣ£•☼▀2.─&│E╧=▒√║∙►ybⁿ☯╫QΔ(☺¥ë2↕☯k`u3xò6┘[↨:ªh°♀êΔ╘δ‼δ@W$A⌐ΘsΘ↕║∞Φ⌡▌b⌐M±uc9╖#→δ¡9¼▀Ö╪♠¬╢æ¥.≈ëzTH♂⌡Q┐àÿî♥τ◄≈«‼û4_≤╛─◄→♂U┌█2Üüà╓ªçδ»Aÿ▄╜9■q▒iö♦4s⌐±[╗:áxÿº•╗.é÷╫╙σG¼╧[]┌>5←◙÷ö╣↨>≤±Bøz→▲√┐•♫◘╚←<∟⌡₧o?PB|Å╩↔Θ↨Γ»H☻▒╩z`6_ⁿ#∩⌂ε╦╬SNΦ9└├↓¥n-d┴≤α┐'F+~<,+╒↑│░»|M☯½☺E}°]dπ☻Ñö°á╠üdhP▼{Bßë ``` [Try it online!](https://quantum64.github.io/Jstx/JstxGWT-1.0.3/JstxGWT.html?code=4oaVzpQi4paMw4fDh8OJw4fil5nDq8OHw4fDh8OHw4fDh8OHwqzDnMOrwrrOo8Kj4oCi4pi84paAMi7ilIAm4pSCReKVpz3ilpLiiJrilZHiiJnilrp5YuKBv%24KYr%24KVq1HOlCjimLrCpcOrMuKGleKYr2tgdTN4w7I24pSYW%24KGqDrCqmjCsOKZgMOqzpTilZjOtOKAvM60QFckQeKMkM6Yc86Y4oaV4pWR4oiezqbijKHiloxi4oyQTcKxdWM54pWWI%24KGks60wqE5wrziloDDluKVquKZoMKs4pWiw6bCpS7iiYjDq3pUSOKZguKMoVHilJDDoMO_w67imaXPhOKXhOKJiMKr4oC8w7s0X%24KJpOKVm%24KUgOKXhOKGkuKZglXilIzilogyw5zDvMOg4pWTwqrDp860wrtBw7_iloTilZw54pagceKWkmnDtuKZpjRz4oyQwrFb4pWXOsOheMO_wrrigKLilZcuw6nDt%24KVq%24KVmc%24DR8K84pWnW13ilIw%24NeKGkOKXmcO3w7bilaPihqg%244omkwrFCw7h64oaS4pay4oia4pSQ4oCi4pmr4peY4pWa4oaQPOKIn%24KMoeKCp28_UEJ8w4XilanihpTOmOKGqM6TwrtI4pi74paS4pWpemA2X%24KBvyPiiKnijILOteKVpuKVrFNOzqY54pSU4pSc4oaTwqVuLWTilLTiiaTOseKUkCdGK348LCvilZLihpHilILilpHCu3xN4pivwr3imLpFfcKwXWTPgOKYu8ORw7bCsMOh4pWgw7xkaFDilrx7QsOfw6s%3D) ]
[Question] [ In [my answer](https://codegolf.stackexchange.com/a/133638/72412), I have this code: ``` s.match(/[AEIOU]/) ``` This seems too verbose to check if a string is one of `A`, `E`, `I`, `O`, or `U`. I tried: ``` "AEIOU".includes(s) ``` But that's 1 byte longer. Can I do this in a shorter way? [Answer] Try `/[AEIOU]/.test(s)` Body must be at least 30 characters; you entered 21 [Answer] If `s` is a literal and not a variable, you can do the following: ``` /[AEIOU]/.test`A` "AEIOU".includes`A` ~"AEIOU".indexOf`A` ``` which is shorter than ``` /[AEIOU]/.test("A") "AEIOU".includes("A") ~"AEIOU".indexOf("A") ``` [Answer] `s.match`[AEIOU]`` goes well..... ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 6 years ago. [Improve this question](/posts/114891/edit) Your challenge is simple: write a program or function which appears to print the first ten numbers of any integer sequence (on OEIS, the answerer may choose which sequence), but instead prints the exact text: ``` Happy April Fool's Day! ``` if and only if it is run on April 1st of any year. Run on any other day should make it output its original output. (Unfortunately, I was a little late posting this challenge). Answers should be voted up for clever hiding of the April fools part. This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), so the answer with the most votes on May 8th wins! [Answer] # TI-Basic (TI-84 Plus CE) ``` {1001,10,1}→LA {1010,1,1}→LA {1011,11,1}→LB {1020,2,1}→LC {1021,12,1}→LD {1030,3,1}→LE {1040,4,1}→LF {1050,5,1}→LG {1060,6,1}→LH {1070,7,1}→LI getDate→L1 IF L1(2)=LA(2) and L1(3)=LA(3):Then "Happy October First!" End IF L1(2)=LB(2) and L1(3)=LB(3):Then "Happy New Year!" End IF L1(2)=LC(2) and L1(3)=LC(3):Then "Happy November First!" End IF L1(2)=LD(2) and L1(3)=LD(3):Then "Happy February First!" End IF L1(2)=LE(2) and L1(3)=LE(3):Then "Happy December First!" End IF L1(2)=LF(2) and L1(3)=LF(3):Then "Happy March First!" End IF L1(2)=LG(2) and L1(3)=LG(3):Then Disp "Happy April Fool's Day!" Return:End IF L1(2)=LH(2) and L1(3)=LH(3):Then "Happy May First!" End IF L1(2)=LI(2) and L1(3)=LI(3):Then "Happy June First!" End IF L1(2)=LJ(2) and L1(3)=LJ(3):Then "Happy July First!" End ClrHome Output(1,1,toString(10000LA(1)+100LA(2)+LA(3))) Output(2,1,toString(10000LB(1)+100LB(2)+LB(3))) Output(3,1,toString(10000LC(1)+100LC(2)+LC(3))) Output(4,1,toString(10000LD(1)+100LD(2)+LD(3))) Output(5,1,toString(10000LE(1)+100LE(2)+LE(3))) Output(6,1,toString(10000LF(1)+100LF(2)+LF(3))) Output(7,1,toString(10000LG(1)+100LG(2)+LG(3))) Output(8,1,toString(10000LH(1)+100LH(2)+LH(3))) Output(9,1,toString(10000LI(1)+100LI(2)+LI(3))) Output(10,1,toString(10000LJ(1)+100LJ(2)+LJ(3))) ``` Uses [OEIS A210884](https://oeis.org/A210884). Stores the numbers as dates and converts them on-the-fly to output. It even leaves you a message in `Ans` if today is one of the dates! [Answer] # C I use some fun CLANG properties to do tricky math and print the text sneakishly. I am printing the sequence of even numbers 0,2,4,6 etc up to 42. This is a nice solution because I don't use any letters or hard coded strings, just pure math trickery to end up outputting the desired text even though it appears to a human brain that this should just be outputting 0,2,4,6,etc [Try it online! (Just the sneaky April Fools Day version)](https://tio.run/nexus/c-clang#ldTPToNAEMfxszwFqTEputPuzC4w6Dv4DhW3sYdSrTZpND6250r/aFR@c5CEA4X9dvNh2V12fp/miy7lj@tF93K7Wd6l9XhbHC/n49FFO3L5tsiy5WzRjYv8LTvL8v6YTg9P5M/paZO6Nl3n3omLrnLq2DsWx3EymUT587w/XH396Wtar/JaqJbDzz/nIJf7m1e@uMl@BWQYKKkcDvfH8dKP39/71YjDBnul/rSmEVGmQpmqz1RWpkIZBRkO1J9WRlGGAa0IiUnLHmYQcKDSnAxDYgbGjVJjCjMk5uq/GUjMwFhr0trMQGIBxKqk5mwEEoughUOnF4gykFgAcawomqtPILEAYi1JSzMDiQURB1Jz3QgkDmiDUKpN4gCJAyCuyXzdAQIHAKxMymYGAgcA3H@XgwjxqQJ9A/ANnoK5aAL0jcC3rKk0aSL0jci3oboxM3gjRjsxMaA5befxWzh73@0@uhW1s/YhfQI) ``` #define printNumber(x) printf("%c", x) main() { SYSTEMTIME st; GetLocalTime(&st); BOOL isFunDay = (st.wDay == 4 && st.wDay == 1); if (isFunDay) { printEvenNumbersTheFunWay();//fun way for a fun day! } else { printSomeEvenNumbersTheBoringWay(); } } printEvenNumbersTheFunWay() { //print sequence: 0,2,4,6,8,10,12,14...42 //print 0 #define zero 72-72 printNumber(2*zero+0); //print 2 #define zero 5-5 printNumber(20*zero+2); //print 4 #define zero 108-108 printNumber(2*zero+4); //print 6 #define zero 106-106 printNumber(2*zero+6); //print 8 #define zero 113-113 printNumber(2*zero+8); //print 10 #define zero 22-22 printNumber(2*zero+10); //print 12 #define zero 53-53 printNumber(2*zero+12); //print 14 #define zero 98-98 printNumber(2*zero+14); //print 16 #define zero 98-98 printNumber(2*zero+16); //print 18 #define zero 87-87 printNumber(2*zero+18); //print 20 #define zero 88-88 printNumber(2*zero+20); //print 22 #define zero 10-10 printNumber(2*zero+22); //print 24 #define zero 46-46 printNumber(2*zero+24); //print 26 #define zero 85-85 printNumber(2*zero+26); //print 28 #define zero 83-83 printNumber(2*zero+28); //print 30 #define zero 78-78 printNumber(2*zero+30); //print 32 #define zero 7-7 printNumber(2*zero+32); //print 34 #define zero 81-81 printNumber(2*zero+34); //print 36 #define zero 2-2 printNumber(-1*zero+36); //print 38 #define zero 30-30 printNumber(2*zero+38); //print 40 #define zero 57-57 printNumber(2*zero+40); //print 42 #define zero 79-79 printNumber(2*zero+42); //print 44 #define zero 1-1 printNumber(-10*zero+44); } printSomeEvenNumbersTheBoringWay() { //print sequence: 0,2,4,6,8,10,12,14...42 int i = 0; while (i <= 42) { printf("%i, ", i); i+=2; } } ``` [Answer] # JS, A000027 ``` d=new Date(); if(d.getMonth()+("")[(![]+"")[+[]]+"ontcol"+(!![]+[]["fi"+(![]+"")[!+[]+!+[]]+"l"])[10]+"r"]()[11]+("")["fon"+(!![]+"")[0]+"color"]()[11]+!+[]+!+[]*!+[]+!+[]&&d.getDate()==+!+[])alert("Happy April Fool's Day!"); else{for(i=0;i<10;)alert(++i);} ``` Mmm, good mixture of JS and JSF\*ck. (Fun fact: The majority of the code is used to represent `==`.) Good tip for corrupting code like mine: [JS to JSFuck Conversion code/list](https://github.com/aemkei/jsfuck/blob/master/jsfuck.js) [Answer] # [Python 2](https://docs.python.org/2/), [A000027](https://oeis.org/A000027) ``` import datetime as a if(str(a.date.today())[5:]=='04-01'):print("Happy April Fool's Day!") else: for i in range(10):print(i+1) ``` [Try it online!](https://tio.run/nexus/python2#NcvBCgIhEIDhu08x7UWHaFGoi7CHIKJ3iA4D68aAq6Jz8emtDh3/D/7Be8lVYCUJwnsAakCKN9OkGpp/PEteqRvE58W/lkXb88k6jb5UTmKmB5XS4fqtCPeco25wo36YUIXYglew5QoMnKBSegfj7H/lo8MxPg "Python 2 – TIO Nexus") ]
[Question] [ I've been using a library called Djangular recently, which integrates Django and Angular. After a while I thought 'Wouldn't it be fun to programmatically generate portmanteau?' Here are some examples (e.g. testcases): Django + Angular -> Djangular Camel + Leopard -> Cameleopard Spoon + Fork -> Spoork Ham + Hammer -> Hammer The general rule is to find the first common letter working backwards on first word, and working forwards on the last word. Not all portmanteau can be found this way though... I've deliberately picked 'simple' ones to generate (for instance we're ignoring things like Zebra + Donkey = Zedonk, which is too arbitrary to generate programmatically - the correct behaviour). Ties can be resolved eitherway - suppose you have `cart + ante` - both `carte`, (since t is the last common letter in the first word) and `cante`, (since a is the first common letter of the last word) are value. [Unfun loopholes are not allowed](http://meta.codegolf.stackexchange.com/q/1061/9534) (including pulling 'solved' examples off wikipedia) This is code golf, so shortest answer wins. I'll pick the winner a month from posting. Please post the output for all your code. [Answer] # Python 3, ~~128~~ 79 bytes Let me know if I got anything wrong and critiques are always welcome. ``` def f(a,b): c=len(a)-1-a[::-1].find(b[1]) if a[-1]==b[0]:return a[:-1]+b if a[c]==a[c-1]:c-=1 return a[:c]+b[1:] ``` Called with f(word 1,word 2) and returns the portmanteau. Will throw an error if the inputs aren't compatible. Works for all test cases. Edit: If I've read the edits to this question correctly, this updated code should work ``` f=lambda a,b:a[:-1]+b if a[-1]==b[0] else a[:len(a)-1-a[::-1].find(b[1])]+b[1:] ``` [Answer] ## CoffeeScript, 111 bytes/characters Source: ``` l="toLowerCase";f=(a,b)->return a.substr(0,i)+b.substr(j)[l]()for c,j in b when(i=a[l]().lastIndexOf(c[l]()))>0 ``` Try it [online](http://coffeescript.org/#try:l%3D%22toLowerCase%22%3Bf%3D(a%2Cb)-%3Ereturn%20a.substr(0%2Ci)%2Bb.substr(j)%5Bl%5D()for%20c%2Cj%20in%20b%20when(i%3Da%5Bl%5D().lastIndexOf(c%5Bl%5D()))%3E0%0A%0Aalert(%22%0A%23%7Bf(%22Django%22%2C%22Angular%22)%7D%0A%23%7Bf(%22Camel%22%2C%22Leopard%22)%7D%0A%23%7Bf(%22Spoon%22%2C%22Fork%22)%7D%0A%23%7Bf(%22Ham%22%2C%22Hammer%22)%7D%0A%22))! To use: ``` alert(" #{f("Django","Angular")} #{f("Camel","Leopard")} #{f("Spoon","Fork")} #{f("Ham","Hammer")} ") ``` I hoped it will be shorter, but.... ok, still better than `PHP` :D The examples result in (using the alert statement above): ``` Djangular Cameleopard Spoork Hammer ``` Explanation (Might not be valid coffescript): ``` l="toLowerCase"; # Keeps code shorter (and DRY :D ) f=(a,b)-> return a.substr(0,i)+b.substr(j)[l]() # Return the result for c,j in b # Postfix for loop when(i=a[l]().lastIndexOf(c[l]()))>0 # Run the return statement only when the # character `c` is found (also stores its last position in `i`) ``` [Answer] # Haskell, 61 bytes Doesn't handle case, but that doesn't seem to be a big deal? Tell me if it is. ``` a!b=maybe(init a!b)((a++).(`drop`b))$last a`lookup`zip b[1..] ``` Then `"Django"!"Angular"` is `"Djangular"`. [Answer] # [rs](https://github.com/kirbyfan64/rs), **24 bytes** ``` (.*)(.).* .*?(\2.*)/\1\3 ``` To copy the initial post from @refi64 here's the [live demo and all test cases.](http://refi64.com/rs/index.html?script=%28.*%29%28.%29.*%20.*%3F%5C2%28.*%29%2F%5C1%5C2%5C3&input=django%20angular%0Acamel%20leopard%0Aspoon%20fork%0Aham%20hammer%0Acart%20ante) The only improvement is that you can spare the \2 back reference by including it in the third group. I didn't want to pollute with an answer that's actually a comment, but some person on Stack Exchange decided that you can't comment when you're a newcomer and that edits should be refused, because that should obviously be a comment. Thus, sorry for that misplaced content. [Answer] # PHP (270 bytes) ``` function portmanteau($s1, $s2){ $r = ''; $y = false; foreach(str_split($s1) as $c1){ $r .= $c1; foreach(str_split($s2) as $c2){ if($y){ $r.= $c2; } if(strtolower($c1)==strtolower($c2)){ $y = true; continue; } } if($y){ break; } } if(!$y) $r .= $s2; return ucfirst($r); } ``` Ungolfed: ``` function portmanteau($str1, $str2){ $resultingString = ''; $letterMatched = false; foreach(str_split($str1) as $char){ $resultingString .= $char; foreach(str_split($str2) as $char2){ if($letterMatched){ $resultingString.= $char2; } if(strtolower($char)==strtolower($char2)){ $letterMatched = true; continue; } } if($letterMatched){ break; } } if(!$letterMatched) $resultingString .= $str2; return ucfirst($resultingString); } ``` Usage: ``` echo portmanteau('Croissant', 'Donut'); ``` Tested and works with the examples in the question. [Answer] # Haskell, 148 bytes C/case isn't restored though. Without case this was 99... ``` import Data.Char o a b=|a==""=b|0<1=a p""b="" p a""="" p a b|last a==head b=a++tail b|0<1=o(p(init a)b)(p a(tail b)) z a b=p(t a)(t b) t=map toLower ``` [Answer] ## Perl, 138 I'm sure someone can optimize this further `($a,$b,$l,$r)=(@ARGV,0);for$A(split//,$a){$r.=$A;for$B(split//,$b){$r.=$B if$l;if($A=~/$B/i){$l=1;next;}}last if$l;}$r.=$b if!$l;` 138 w/ optimizations and output [Answer] # [rs](https://github.com/kirbyfan64/rs), 26 bytes ``` (.*)(.).* .*?\2(.*)/\1\2\3 ``` [Live demo and all test cases.](http://kirbyfan64.github.io/rs/index.html?script=%28.*%29%28.%29.*%20.*%3F%5C2%28.*%29%2F%5C1%5C2%5C3&input=django%20angular%0Acamel%20leopard%0Aspoon%20fork%0Aham%20hammer%0Acart%20ante) So far this is the shortest answer! The underlying logic is pretty simple. It just matches greedily on the first word (to get the last common character) and non-greedily on the second (to get the first common character). It then replaces the string with everything *but* the text in between the two characters. ]
[Question] [ Check out this challenge: <https://www.hackerrank.com/codesprint4/challenges/leibniz> (The competition has already ended, so I'm just curious about the Python solution, which the organizers refused to reveal, so this is not cheating in any way.) Modified from that page: > > In Calculus, the Leibniz formula for \$\pi\$ is given by: > > > $$\sum\_{n=0}^\infty \dfrac{\left(-1\right)^n}{2n+1}$$ > > > You will be given an integer \$n\$. Your task is to print the summation of the Leibniz formula up to the \$n\$th term of the series correct to 15 decimal places. > > > That is given \$n\$ calculate: > > > $$\sum\_{k=0}^n \dfrac{\left(-1\right)^k}{2k+1}$$ > > > with the first 15 decimal places correct. > > > # Input Format > > > The first line contains the number of test cases (\$T\$) which is less than 100. Each additional line is a test case for a positive integer value less than 10^7. > > > # Output Format > > > Output \$T\$ lines each containing the calculated result for the corresponding line of the input. > > > # Scoring > > > This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). > > > I only managed to solve the challenge in 77 characters. (Talking only about Python here.) However, one adr2370 managed to solve the challenge in 66 characters! Please help me find the 66-character solution! I'm very very curious because I had to work really hard to bring mine down to 77, and I'm amazed as to how someone came up with a 66-character solution. For reference, my solution: ``` for j in'x'*input():print'%.15f'%sum((-1)**i/(2.*i+1)for i in range(input())) ``` [Answer] ## Python, 65 characters ``` exec'print`sum((-1.)**x/(x-~x)for x in range(input()))`;'*input() ``` [Answer] ## Python 71 bytes ``` exec"print'%.15g'%sum((-1.)**i/(i-~i)for i in range(input()));"*input() ``` Not quite 66 bytes, but with a score of 22.90, it would have ranked second overall. **Edit**: regarding [Ari's comment](https://codegolf.stackexchange.com/questions/10716/#comment20257_10716) about the 66 byte Python solution being a 'hack', I don't think that's exactly what happened. I've noticed several times that the submitted language is displayed incorrectly. For example here: [Baconian Cipher](http://www.hackerrank.com/challenges/baconian-cipher/leaderboard). This challenge may only be submitted in Brainf\_ck, yet the second ranked solution was submitted in Python 2 (interestingly enough, spot 23 is also Python 2. If I were to speculate, I would say that if the language information is missing from a submission for whatever reason, it seems to default to Python). I suspect that a similar error may have occurred here, and that the shortest Python solution submitted during the challenge was actually 72 bytes. **Update**: After speaking with a moderator, it seems that Ari was right: ![enter image description here](https://i.stack.imgur.com/XGReb.png) [Answer] # Python 2 (50 chars, with input loop grows) ``` a=n=1.;s=0;exec's+=a/n;a=-a;n+=2;'*input();print s ``` also prints only 12 digits of result, with loop and formatting ``` exec input()*"a=n=1.;s=0;exec's+=a/n;a=-a;n+=2;'*input();print '%.15f'%s;" ``` 74 chars # Python 3 (57 chars, with input loop grows to 79 chars) without loop ``` a=n=1;s=0;exec('s+=a/n;a=-a;n+=2;'*int(input()));print(s) ``` with loop ``` exec(int(input())*"a=n=1;s=0;exec('s+=a/n;a=-a;n+=2;'*int(input()));print(s);") ``` Python 3 prints 16 digits by default ``` exec(int(input())*"print(sum((-1)**i/(i-~i)for i in range(int(input()))));") ``` 76 chars ]
[Question] [ So the golf question was like this: > > You are given a number `T` and then a total of `T` number of 17-character strings. For each of the strings, output `yes` if it contains four consecutive identical characters or contains the substring `DX`, else output `no`. > > > The following constraints are promised for each of the 17-character strings: 1. The possible character set is `DX2AKQJT9876543`; 2. The input string is sorted in the above mentioned order, hence the number of times each character appears is exactly the size of the longest contiguous substring of the character; 3. No characters will appear more than 4 times; 4. `X` and `D` will appear no more than once each. Test case: ``` 3 X2AAKKKKQT9765433 DX22AKKQJTT884443 X2AAAKQQJT8554433 ``` should have the output ``` yes yes no ``` --- Note: * Output is not case sensitive, so `YeS` is also legal; * You may assume an extra `\n` after the end of the input. --- My attempt goes like this: Python, probably ~~84~~ 85 Bytes ``` import re input() while n:=input():print("yes"if re.search(r"(.)\1{3}|DX",n)else"no") ``` Also, I have the following alternatives for line 3, while are approximately the same length: ``` while n:=input():print("yneos"[not re.search(r"(.)\1{3}|DX",n)::2]) while n:=input():print(["yes","no"][not re.search(r"(.)\1{3}|DX",n)]) while n:=input():print((not re.search(r"(.)\1{3}|DX",n))*"no"or"yes") ``` Is there anything I can do to make this shorter? Thanks in advance! Source: Question made by a friend, problem ID on Luogu is `P8466` [Answer] # [Python](https://docs.python.org/3.8/), 72 bytes ``` for n in[*open(0)][1:]:print("yneos"[all(map(str.__ne__,' X '+n,n))::2]) ``` [Try it online!](https://tio.run/##Xc09C4MwEAbg3V8RXIytlDYfmrgJneokOAgiwcFSwV5CdPHX2xgshd5y3MN7d2ZdXhqoMHbbntoiQCO0J20GwNe4a295lxs7woLDFQY9h20/TfjdGzwv9qIUDEolEWpQdIYE4jjPSRdvmwgaUhSlq6qWWcoZpcG9IcRR9ahrIRhj1GeKsnIiOGc@47d2kcKvBV/4yTHWUopDXM@yNE35fsWd2X/9yQc "Python 3.8 (pre-release) – Try It Online") Knocks 5 more bytes off of Jonathan Allan's answer. [Answer] # 82 bytes Can probably be golfed more, but here is a first golf: -2 bytes by changing ``` "yes"if re.search(r"(.)\1{3}|DX",n)else"no" ``` To: ``` re.search(r"(.)\1{3}|DX",n)and"yes"or"no" ``` [Try it online.](https://tio.run/##Lcq9CsIwFEDhPU9RMiUgBfOjseBQ6GSnQoYOLkUDDehNuI1IUZ89BvSMHyeuaQ4gTcSc/T0GTBU64iE@EuPkOfubq6A5/qGJ6CExdPXiJrzMDCmr@Xn7kp93N9IN8AmudHULDUghUJ6zJKNo27402MN@p5WUpBuFKDScrDVGKfV72n4oYrQuIL8) And another -1 by changing (not sure about this one, but both your 85 bytes version and this one gives an EOFError on TIO): ``` input() while n:=input():...n ``` To: ``` n=input() while n:...input() ``` [Try it online.](https://tio.run/##Lcq9CsIwFEDhPU9RMiUgBfOjUXAodLJTIUMHl6KBBupNuI1IUZ89BvSMHyeuaQogTcSc/T0GTBU6AicP8ZEYJ8/Jz66CY0QPiaGrFzfidWJIWc0v25f8vNuBbv47H@FGV7fQgBQC5TlLMoim6Uq9Pex3WklJ2kGIQv3ZWmOUUr@n6foiRusC8gs) [Answer] # [Python 3.8](https://docs.python.org/3.8/), 77 bytes ``` input() while n:='X '+input():print("yneos"[all(map(str.__ne__,n,n[3:]))::2]) ``` **[Try it online!](https://tio.run/##Xc09C4MwEAbgPb9CXEyodMiXMdBB6FQnIYMgEhwEBRuDphR/fRrFUugtxz28d2c3N8yGCLt4Pxr7chCB9zBOfWTkLamj5HKqtMtoHIw3089r3HTTBJ@dhatbrlqbXuvUpKYhskVIStwi7wWocVGUoSqVZ5xRQsC9xjhQ9VBKCEopOTJFWQURjNEjc2ztkotjDXzhJ@eo8lycEnqWcc7ZfiWc2X/9yQc "Python 3.8 (pre-release) – Try It Online")** The check for four equal characters in a row can be achieved by checking for equality between a character and the character three positions to its right. This can be applied across a string with `any(map(str.__eq__,n,n[3:])` which will yield `True` if so or `False` otherwise. This is inverted in the code by checking that all such pairs of characters are *not* equal with `all(map(str.__ne__,n,n[3:]))` to allow the result to be used in a slice of `"yneos"` that steps by two characters. That is, `"yneos"[False::2]` is equivalent to `"yneos"[0::2]` which is `"yes"`; while `"yneos"[True::2]` is equivalent to `"yneos"[1::2]` which is `"no"`. To check for the presence of "DX" we only need to see if the string *starts with* "DX" due to the strict ordering and the rule that states each of "D" and "X" may only appear once. Moreover this means the string cannot have a second character of "X" unless it starts with "DX", so we actually only need to check if the second character is "X". Therefore prefixing the string with "X " allows a reuse of the check for equal characters being three apart for this too, hence `n:='X '+input()`. ]
[Question] [ # Input Two lists with binary values `(list_a, list_b)` of equal length=>3. # Output Two lists with binary values `(smoothed_a, smoothed_b)` with minimal Forward Difference while keeping the same sum before and after processing `sum(list_a) + sum(list_b) == sum(smoothed_a) + sum(smoothed_b)`. **Forward Difference** being the absolute difference between items. For example: * `[0, 1, 0]` would be `sum(abs([1, -1])) => 2` * `[1, 1, 1]` would be `sum(abs([0, 0])) => 0` # Illustrative test cases Formatted as `(list_a, list_b) => (smoothed_a, smoothed_b)` ``` ([0, 0, 1, 0, 0], [1, 1, 0, 1, 1]) => ([0, 0, 0, 0, 0], [1, 1, 1, 1, 1]) ``` The sum of both arrays pairs is 5. The forward difference was minimized to 0. ``` ([1, 0, 1, 0, 1], [0, 0, 0, 1, 0]) => ([0, 1, 1, 1, 1], [0, 0, 0, 0, 0]) ``` The sum of both arrays pairs is 4. The forward difference was minimized to 1. # Test cases Formatted as `(list_a, list_b): forward_diff => (smoothed_a, smoothed_b): min_diff` where `(smoothed_a, smoothed_b)` are potential solutions. ``` ([0, 0, 1], [0, 1, 0]): 3 ([0, 0, 0], [0, 1, 1]): 1 ([1, 1, 1], [0, 0, 0]): 0 ([1, 1, 1], [0, 0, 0]): 0 ([0, 1, 0], [1, 0, 1]): 4 ([0, 0, 0], [1, 1, 1]): 0 ([1, 1, 1, 1], [0, 0, 0, 0]): 0 ([1, 1, 1, 1], [0, 0, 0, 0]): 0 ([1, 0, 1, 1], [0, 0, 0, 1]): 3 ([1, 1, 1, 1], [0, 0, 0, 0]): 0 ([1, 0, 0, 1], [0, 0, 0, 1]): 2 ([1, 1, 1, 0], [0, 0, 0, 0]): 1 ([1, 1, 0, 1], [1, 0, 1, 0]): 3 ([1, 1, 1, 1], [1, 0, 0, 0]): 1 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` FṢṁ ``` [Try it online!](https://tio.run/##y0rNyan8/9/t4c5FD3c2/v//XyPaQEcBiAzBpEGsjkK0IYwHYsRqAgA "Jelly – Try It Online") Explanation: * **F**latten the list * **Ṣ**ort the flattened list * **ṁ**old the sorted flatten list in the shape of the input. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 4 bytes ``` O`\d ``` My shortest Retina answer thus far. [Try it online](https://tio.run/##K0otycxLNPz/3z8hJuX//@hoQx0DHTCO1Yk20DGA8GJjAQ) or [verify all test cases](https://tio.run/##K0otycxLNPyvquGe8N8/ISbl///oaAMdAx1DIDaI1Yk2BLOAZGwsV3S0IVTGECgDUgXmgWUM4KIwEUOwLqg6qBpDqJkGcPNQVMF1GqCIIuw2wCIKc48himug6mJjAQ). **Explanation:** Sorts all digits in the input, and leaves every other character unchanged (including their positions). [Answer] # [Python 2](https://docs.python.org/2/), 51 bytes ``` def f(a,b):s=sorted(a+b);l=len(a);print s[:l],s[l:] ``` [Try it online!](https://tio.run/##LcaxCoAgFEDRva9wfI8cqlHxS8RBUUkQFbWhr385BJfDbe@8a7mIfIgsguUOxVCj9hk82N2hzCqHAhZl66lMNrTIhg@dhaEIqbRnAnL2D5I@OVsdS7Pp/5bmAw "Python 2 – Try It Online") Function that prints to STDOUT. [Answer] # [Husk](https://github.com/barbuz/Husk), 3 bytes ``` ½OΣ ``` [Try it online!](https://tio.run/##yygtzv7//9Be/3OL////Hx1toGOgYwjEBrE60YZgFpCMjQUA "Husk – Try It Online") ``` ½OΣ – Full program. Takes a list of two lists from the first CLA, outputs to STDOUT. Σ – Flatten (i.e. concatenate the contents of the 2 lists together). O – Sort. ½ – Divide list in two halves (i.e. partition it into two equal-length sublists). ``` [Answer] # J, 7 bytes ``` $$/:~@, ``` ## explanation ``` $ NB. use the input shape $ NB. to shape the result of... /:~ NB. sorting the input @, NB. after flattening it ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/VVT0reocdP5rcqUmZ@QraBgogKAOSImhgqGmgq6VQhpYyBAmaMAFAv8B "J – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ˜{2ä ``` [Try it online](https://tio.run/##yy9OTMpM/f//9Jxqo8NL/v@PjjbQMdAxBGKDWJ1oQzALSMbGAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/03OqjQ4v@a/zPzo62kDHQMcQiA1idaINwSwgGRuroxAdbQiVMgRKgZSBeRApA7gwXMgQrBGqEqbKEGquAcJMFHUIzQYowkguMMAmDHOWIcxRsQA). **Explanation:** ``` ˜ # Flatten the (implicit) input list of lists { # Sort it 2ä # Split it into two equal-sized lists (and output implicitly) ``` [Answer] # C gcc compile flag 64bit, 31 bytes by Rogem ``` -Df(a,n)=qsort(a,n+n,4,"\x8b\x07+\x06\xc3") ``` [Try it online!](https://tio.run/##jZDdCoJAEEbvfYpBKBTX8LcC8a63UC92txShtlpXEKJXb9utdG6bgeHw8XEuhocd51rrQcmRK3g4YKYXCmiVNwSYuYXzBHUaVOHY/EJ74fm/oo03tIoaKGdOFmZVbDkuPtXWW9uUQO5/g5s0uhY8d3WctxYuQeeCMWKCmCJmzT9Ohk6GToZOhk6GTnlSoxQQmTfoF2/PtBt0eGg9SoRf3oerVBYDQTLi1tOe1VO0C8zZ1hNPXf8N "C (gcc) – Try It Online") # C gcc 32bit, 37 bytes ``` f(a,n){qsort(a,n+n,4,"YXZ\x8B\x00+\x02QQQ\xC3");} struct { int a[5], b[5]; } test; int main() { test.a[0] = test.a[2] = test.b[1] = 1; f(&test, 5); printf ("%d%d%d%d%d\n", test.a[0], test.a[1], test.a[2], test.a[3], test.a[4]); printf ("%d%d%d%d%d\n", test.b[0], test.b[1], test.b[2], test.b[3], test.b[4]); return 0; } ``` Written non-ASCII to `\x??` so se won't eat [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes ``` ⪪⭆⊗Lθ‹ι№⁺θη¹Lθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4ICcTSJYAOem@iQUaLvmlSTmpKRo@qXnpJRkahZo6Cj6pxcUamToKzvmlQA0BOaXFGoU6ChlAGUNNIAApgKrV1LT@/z862lBHwQCMDGN1uBSiDRDc2P@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Charcoal doesn't have a sort atom, but all we need to do is to put all the `1`s at the front of the list, which is done by counting them and then setting that many list entries to `1` and the remaining ones to `0`: ``` θ First input L Length ⊗ Doubled ⭆ Map over implicit range and join θ First input η Second input ⁺ Concatenate ¹ Literal 1 № Count matches ι Current index ‹ Less than θ First input L Length ⪪ Split into strings of that length Implcitly print each string on its own line ``` [Answer] # [R](https://www.r-project.org/), 57 bytes ``` function(a,b,s=1:sum(a|1),x=sort(c(a,b)))list(x[s],x[-s]) ``` [Try it online!](https://tio.run/##HYkxCsAgDAC/0jGBCGYt9SXiYAVBaBWMgkP/bm2HOw6uzrgdasaeQ0slg6eTxPAu/Qb/MNIwUmqD8B1EvJI0GFYcDavE4YxradLEC40UgP9cRpwv "R – Try It Online") [Answer] # Scala, 60 bytes ``` def^(a:List[Int],b:List[Int])=(a:::b).sorted.splitAt(a.size) ``` [Try it online!](https://tio.run/##K05OzEn8n5@UlZpcopCvkFpRkpqXUqzgWFCgUP0/JTUtTiPRyiezuCTaM68kVicJwda0BcpYWSVp6hXnF5WkpugVF@RkljiWaCTqFWdWpWr@LyjKzCvJydOI0wDp0TDUUTDQUYCSmjpgMQMwDyqsqanJVfsfAA "Scala – Try It Online") ]
[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/156421/edit). Closed 5 years ago. [Improve this question](/posts/156421/edit) Given a list of *n* strings, return a list of that strings in ascending order. However, be aware, that in this case we want integer comparison for all numbers appearing in the strings, meaning that "12" > "3". Example cases: ``` {"abc123", "abc6", "abc47", "abd49"} -> {"abc6", "abc47", "abc123", "abd49"} {"foo0", "bar12", "foobar12", "foo"} -> { "bar12", "foo", "foo0", "foobar12"} {"Bond007", "Bond07", "Bond7", "Bond12"} -> {"Bond007", "Bond07", "Bond7", "Bond12"} {"one1", "one11two23", "one1two2", "one1two3", "1"} -> {"1", "one1", "one1two2", "one1two3", "one11two23"} ``` You can expect to only find *[a-zA-Z0-9]+* in each string. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins. [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. Update: - Sorting is case insensitive - The ascending order is *integers* < "abcdefghijklmnopqrstuvwxyz" - Every sequence of integers as in the aforementioned order should be interpreted as one integer, meaning "421" represents 421, not 4, 2 and 1 and thus is smaller than "1341", as 421 < 1341 -Treat numbers with leadings zeroes as though they were decimals meaning "001" -> "0.01" so "001" < "01" < "1" Thanks for Adám for pointing out, that this is called natural sort order. [Answer] # [Python 2](https://docs.python.org/2/), 68 bytes ``` lambda l:sorted(l,key=lambda x:int(re.sub("\D","",x)or 0)) import re ``` [Try it online!](https://tio.run/##TY9BCoMwEEX3OcWQlYFQjJWWCm5Kb6EutEYaGhOJKdXT2yRacTPz5vP/MDPM9qVVsnR5uci6b9oaZDZqY3kbSfrmc76pUyaUjQw/jZ8mwuUDU4zpRLSBmBAk@sFlwPBFihFyKBBAgevmyZIzpuDpsvX0ukKb3nBFg6/TOvZiUxuWeHDCkf@@u1ZtHId8wJ12cJHNqxVnXvWd2a9e7/CTHw4c9GDFFaoQ6txLUoBQro6Z2zUY/3kXSUHI8gM "Python 2 – Try It Online") I used something like this to sort PDF files recently! *my entry originally didn't work but [Neil](https://codegolf.stackexchange.com/users/67929/neil) fixed it (thanks!)* [Answer] # [Perl 6](https://perl6.org), ~~32 31~~ 30 bytes ``` *.sort(*.comb(/\d+|\D+/)».&val) ``` [Test it](https://tio.run/##jY/PToNAEMbv@xQTDs1uaSnUBmM3GDR682g89QLsNCFSdsOfKlGfzJsvhruAlCbGeJpvv/nNtzMKi8xv6xLh6DsJJ@TQwCyRAiFo504pi4rOnUQeYrraCft9d2ev2NenMztGGWu5ocMKywoCyNIcS926f7p54MQkPuoGJyqLcrA7ipO9LIaB5TXQ7TM2NExzVVdsAVudWSMN8VVhUqFgwOCNAKTlUiCqrAGz14kfwYl0lL6Hk4@WWlGceOsLawFG@UPdXPZCbK4sBoHe4bfuabDjCLX2UrrGiaPCWxuhjakews6BobhnvEm7lblw3e6zTo5qFAbs1/sfq0Nljp6xTPWqF9mfYF7mMdGd7/3kjzN/0ZNM9g0 "Perl 6 – Try It Online") ``` *.sort(*.comb(/\d+|\D/)».&val) ``` [Test it](https://tio.run/##jY/PToNAEMbv@xQTDs1u/1CoDcZuMGj05tF46oWy04RI2Q0sVaI@mTdfDHcBKU2M8TTffvObb2cUFlnQVCXCMXATTsihhkkiBULYTN1SFppO3UQednS5FbP37d2SfX26k2OcsYZbONJYagghS3MsTev@6eaBExv4aBqcqCzOYdZSnOxl0Q8sroFunrGmUZqrSrM5bExmhTTCV4WJRsGAwRsBSMuFQFRZDXatEz@AI@kqcw4nHw114l3iry6cOVgV9HV92QmxvnIYhGaH37qnwZYj1NlL6VlnFxf@ygpjjHUfdg70xTvjbdqtzIXntZ@1clCDsGC33v9YEypz9K1lq69fZHeCfdnHSLe@/5M/zPxFjzLZNw "Perl 6 – Try It Online") ``` *.sort(*.comb(/\d+|./)».&val) ``` [Test it](https://tio.run/##jY/LTsMwEEX3/opRFpXdh5uUKohaQQGJHUvEik0eUykija3EKUTAl7Hjx4KdhDSVEGI113fOXM8oLHO/rSuEo88TQcihgVkiU4SgnfNKlprOeSIPMV0/pYt3vmZfn3x2jHLWCsuGGisNAeRZgZVp3T3e3Ati8x5MQxCVRwUsOkqQvSyHgdU10N0zNjTMClVrtoSdyayRhviqMNGYMmDwRgCyapUiqrwBu9WJH8GJ5MpcI8hHS50oTrzNhbMEq/yhbi97kW6vHAaB2eG37mmw4wh19lK61omj0ttYYYypHsLOgaG4Z7xNu5VF6rrdZ50c1Sgs2K/3P9aEygI9a9nq6RfZn2Bf9jHRne/95I8zf9GTTPYN "Perl 6 – Try It Online") ## Expanded: ``` *\ # WhateverCode lambda (this is the parameter) .sort( # sort by doing the following to each string *.comb( / \d+ | . / )\ # split the string into consecutive digits or a character ».&val # convert each to a Numeric if possible ) ``` Note: ``` "Bond007".comb(/\d+|\D+/)».&val # results in ("Bond", IntStr.new(7, "007")) # and "Bond007".comb(/\d+|./)».&val # results in ("B", "o", "n", "d", IntStr.new(7, "007")) ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/) 17.0 (currently in alpha), 31 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Anonymous tacit prefix function taking a list of strings as argument. ``` ⊂⊃¨⍨∘⍋({0::⍵⋄⍎⍵}¨⊢⊂⍨1,2≠/∊∘⎕D)¨ ``` As version 17.0 isn't on TIO yet, here is a test session transcript: ``` f←⊂⊃¨⍨∘⍋({0::⍵⋄⍎⍵}¨⊢⊂⍨1,2≠/∊∘⎕D)¨ ⎕JSON f ⎕JSON '["abc123", "abc6", "abc47", "abd49"]' ["abc6","abc47","abc123","abd49"] ⎕JSON f ⎕JSON '["foo0", "bar12", "foobar12", "foo"]' ["bar12","foo","foo0","foobar12"] ⎕JSON f ⎕JSON '["Bond007", "Bond07", "Bond7", "Bond12"]' ["Bond007","Bond07","Bond7","Bond12"] ⎕JSON f ⎕JSON '["one1", "one11two23", "one1two2", "one1two3", "1"]' ["1","one1","one1two2","one1two3","one11two23"] ``` --- `⊂` from the entire argument… `⊃¨⍨` pick each of the indices… `∘` that are… `⍋` the ascending grade (indices which would place in ascending order) of… `(`…`)¨` the following tacit function applied to each of the strings:  `∊∘⎕D` Boolean mask for the characters which are members of the set of **D**igits  `2≠/` pairwise inequality of that (i.e. indicate beginnings of letter runs and digit runs)  `1,` prepend 1 to mark the first character as beginning a run  `⊢⊂⍨` use that to partition (beginning partitions at 1s) the string  `{`…`}¨` apply the following anonymous lambda to each partition:   `0::` if any error happens, then:    `⍵` return the argument as-is   `⋄` try to:    `⍎⍵` evaluate the argument [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` ΣDþïs)} ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3GKXw/sOry/WrP3/P1opPy/VUElHAUwblpTnGxnDeCAOEhssbqgUCwA "05AB1E – Try It Online") # Explanation ``` ΣDþïs)} Full Program Σ } Sort by result of key: a D a, a þ digits_only(a), a ï int(digits_only(a)), a s a, int(digits_only(a)) ) [a, int(digits_only(a))] ``` [Answer] # [Python 3](https://docs.python.org/3/), 107 106 bytes ``` import re lambda a:sorted(a,key=lambda x:[n.isdigit()and n.zfill(9)or n for n in re.findall('\d+|\D+',x)]) ``` [Try it online!](https://tio.run/##jVHRboMgFH3nK276UkiJ0bbZUhNflv2F9QELbGQWDJJMl/27A1zVLssyH7jnnnM4xJx2cK9GH8ZRXVtjHViBZNGwa80ZsLzzlOCY0Tcx3Ng@L3WiOq5elMOEaQ46@ZCqafCJGAsaZDyV9lmJVJozL9ntme8@z8@7Le1JRUYuJDjROdzTgeQI/NdapR2WuCfkxw5FAQNB6MI60UEBZdRxuWH1JdsfNhQCeviex8cJ8ONpU1Eof9OWa9FF6C1RGpMGoWY22wfgiTWeEu@YaaR35lXik9E8TeO7Ec5oBsEfUv/nXJKNFllQwszcu5l@KWxhWeHIZ9Mj842/vKvEiqAKhUZ9UaHT2EG@dDd@AQ "Python 3 – Try It Online") Abused the fact that Python compares two lists lexicographically. Unfortunately `re.split(r'\b',x)` does not work. [Answer] # [Python 2](https://docs.python.org/2/), 92 bytes ``` lambda q:map(lambda a:a[1],sorted(map(lambda a:[int(re.sub("\D","",a)or 0),a],q))) import re ``` [Try it online!](https://tio.run/##VY/BCoMwEETv@YolpwRCMVZaKngp/QvNYa1KA5potJR@vU3USnvJvpnMhGz/nh7WxHOTFXOLXVkhDGmHPdsEpphLJUbrprpifxe5NhNz9WF8lowWNyooFcitg4gLVGLgnBPd9b4Jrp5bPUIGOQHIKZZ3GR@pgECnbSbnFarkQpVYco21UTBLdDIO4I1f/uau1lRRtPQX3GkHX9my1tQyuGHK6WXXfwQVxA8vvqSKKEIav1WrQRt/jql/p3dh@Ya1mvP5Aw "Python 2 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 125 bytes ``` lambda a:[y for _,y in sorted([([i%2and int(e)or e for i,e in enumerate(re.findall("(\D+|\d+)",s))],s)for s in a])] import re ``` [Try it online!](https://tio.run/##PYzBCgIhFEX3fcVDCJSRmKZFELSJ/kIlXvgkYUYHxxYD/btpwWwuh8u5d17zK4ZTcVddRpyeFgEvagUXEzzkCj7AElMmyxVXfj9gsLXLnEQV6Kd5SU2j8J4oYSae6OB8sDiOnHF97z7adoLJRQhTo02WNkAjzM5Pc72HRGVO7ddxxW4x2L4/Mwl/3GiD48CMEOUL "Python 3 – Try It Online") [Answer] # [PHP 7](http://php.net/docs.php), 17 bytes ``` <?php natsort()?> ``` [natsort](http://php.net/manual/en/function.natsort.php) — *"Sort an array using a 'natural order' algorithm"* ]
[Question] [ **This question already has answers here**: [Qeng Ho units of time](/questions/63056/qeng-ho-units-of-time) (8 answers) [Convert English to a number without built-ins or libraries](/questions/71681/convert-english-to-a-number-without-built-ins-or-libraries) (10 answers) Closed 6 years ago. Given the written, spelled-out representation of an integer from `1` to `10^15-1` inclusive, convert it to an actual integer in decimal. # Input Format The input will always be a string of groups, where each group is composed only of letters and spaces(). The groups are separated by commas. You may choose whether you want the letters to be all lowercase, all uppercase, or title case. For the purposes of this challenge, there are no hyphens (`-`) between e.g. `"forty-two"`, so tokens within groups are separated by spaces only. The input will contain no words `and`. You can test if an input is valid by putting it as input into [this](https://tio.run/##nZHBbsMgDIbvPAWTdiASjxCtbzKJBLdBoiAlpB2S3z0zhrBeetkh4Tf298s2KyQXzHEkCAgeHnSkJ/gHYFrcmoDia9ybcFc@N/dTz1LOCtxtYRFcgCLEWP7blyCzkHI1y2TFf/LJ7JKbR64OufK50AWOgdp4RqJXAO6DWGqN0ApWjCkx7sElglSFlWwXwwVbM3jeqMuHXPZgV7CDGLe78f5WwJruKbJoOfJQXYuRiumTaXXeuxiE4XBq0cTRvUVzLV3ivplghWUaxLcyaLSacNJqxlkri1YDwoBdkXyXIf1fcvg8DtrfOaSsG5e8yD6RLre9pL2RLLs/p9TxpYATbWDN79oH1vR@f3Xl@X8B "Retina – Try It Online") Retina program. Here is a full table of tokens: ``` Units: +1 | "one" +2 | "two" +3 | "three" +4 | "four" +5 | "five" +6 | "six" +7 | "seven" +8 | "eight" +9 | "nine" Teens: +10 | "ten" +11 | "eleven" +12 | "twelve" +13 | "thirteen" +14 | "fourteen" +15 | "fifteen" +16 | "sixteen" +17 | "seventeen" +18 | "eighteen" +19 | "nineteen Tens: +20 | "twenty" +30 | "thirty" +40 | "forty" +50 | "fifty" +60 | "sixty" +70 | "seventy" +80 | "eighty" +90 | "ninety" Hundred: ×100 | "hundred" Place markings: ×10^3 | "thousand" ×10^6 | "million" ×10^9 | "billion" ×10^12 | "trillion ``` # How to Evaluate a Spelled-out Representation We will be working with the example input `"forty five thousand,one hundred thirteen"` First, split the input into groups by commas, to get e.g. `["forty five thousand","one hundred thirteen"]` Then, evaluate each group: 1. Split by spaces to get a list of tokens 2. Start with a running total of 0 3. For each token, do as the table says. If the token is `9`, do `+9` and add `9` to the running total. If the token is `thousand`, multiply the running total by `1000`. For the second example group, this would be: ``` running total token 0 1 "one" 100 "hundred" 113 "thirteen" ``` For the first example group, this yields `45000`. After this is done, sum each group to get the output e.g.`45113`. Note that you do not have to evaluate the number exactly as I had laid it out as long as you produce the same results. For example, you could do string substitution to get an expression you can eval. # Test Cases ``` "one" -> 1 "ten" -> 10 "forty" -> 40 "one hundred" -> 100 "one thousand" -> 1000 "ten million" -> 10000000 "one hundred billion" -> 100000000000 "ten trillion" -> 10000000000000 "nine hundred ninety nine trillion,nine hundred ninety nine billion,nine hundred ninety nine million,nine hundred ninety nine thousand,nine hundred ninety nine" -> 999999999999999 "two hundred forty one trillion,eight hundred sixty one billion,seventy seven million,one hundred fifty four thousand,twenty eight" -> 241861077154028 "four hundred eighty five trillion,six hundred fifty seven billion,six hundred million,four hundred eighty two thousand,one hundred seventy eight" -> 485657600482178 "three hundred eighty nine trillion,five hundred twenty billion,one hundred ninety seven million,nine hundred fifty thousand,nine hundred eighty four" -> 389520197950984 "one hundred fifty five trillion,five hundred five billion,four hundred fifty eight million,six hundred seventy thousand,six hundred sixty one" -> 155505458670661 "one hundred fifty two trillion,ninety three billion,two hundred twenty one million,nine hundred thirty two thousand,five hundred eighty" -> 152093221932580 "three hundred forty three trillion,two hundred eighty six billion,nine hundred sixty five million,six hundred four thousand,two hundred seventy nine" -> 343286965604279 "six hundred ninety eight trillion,nine hundred seventy five billion,one hundred five million,sixty thousand,two hundred forty" -> 698975105060240 "five hundred seventy four trillion,one hundred sixty billion,five hundred ninety eight million,one hundred nine thousand,sixty two" -> 574160598109062 "four hundred seventy seven trillion,two hundred twenty five billion,eight hundred sixty three million,one hundred eighteen thousand,eight hundred four" -> 477225863118804 "eighty seven trillion,two hundred eighty three billion,six hundred eighty eight million,eight hundred fifty three thousand,sixty nine" -> 87283688853069 "eight hundred trillion,fifty billion,five hundred seven million,eighty thousand,fifty" -> 800050507080050 "seven hundred seventy three trillion,three hundred billion,four hundred thousand,nine" -> 773300000400009 "three hundred trillion,two hundred eighty eight billion" -> 300288000000000 "four hundred trillion,two hundred six billion,sixty six million,sixty" -> 400206066000060 "eight trillion,ninety nine million,four hundred sixty thousand,four hundred" -> 8000099460400 "seventy trillion,six hundred billion,forty million,seven hundred thousand" -> 70600040700000 "one hundred twenty billion,one hundred million,seventy thousand,forty" -> 120100070040 "four billion,eight hundred million,five hundred four thousand,five hundred six" -> 4800504506 "five hundred trillion,three hundred fifty five billion,seventy six thousand" -> 500355000076000 "fifty eight trillion,ninety eight billion,forty" -> 58098000000040 ``` --- ## Not a Duplicate The other question involves the units only modifying the previous value, such that every 'group' is composed of only an integer and a modifier. This requires a more dynamic approach in order to calculate groups of varying sizes. [Answer] # Mathematica, 28 bytes ~~*Mathematica has a builtin for everything*~~ ``` Interpreter@"SemanticNumber" ``` Of course, Mathematica has a built-in interpreter for spelled-out numbers. [Try it on Wolfram Sandbox](https://sandbox.open.wolframcloud.com) ### Usage ``` f=Interpreter@"SemanticNumber" ```   ``` f["three hundred trillion,two hundred eighty eight billion"] ``` > > > ``` > 300288000000000 > > ``` > > ``` f["five hundred seventy four trillion,one hundred sixty billion,five hundred ninety eight million,one hundred nine thousand,sixty two"] ``` > > > ``` > 574160598109062 > > ``` > > [Answer] # [Python 2](https://docs.python.org/2/), 491 bytes ``` a,m,s,r={'one':1,'two':2,'three':3,'four':4,'five':5,'six':6,'seven':7,'eight':8,'nine':9,'ten':10,'eleven':11,'twelve':12,'thirteen':13,'fourteen':14,'fifteen':15,'sixteen':16,'seventeen':17,'eighteen':18,'nineteen':19,'twenty':20,'thirty':30,'forty':40,'fifty':50,'sixty':60,'seventy':70,'eighty':80,'ninety':90},{'hundred':100,'thousand':1e3,'million':1e6,'billion':1e9,'trillion':1e12},input(),0 for i in s.split(','): j=0 for k in i.split():j=j+a[k]if k in a else j*m[k] r+=j print r ``` [Try it online!](https://tio.run/##RZHNboMwEITvPIVvGxorMuQXSzxJ1QNVTFliDDImbRTl2enaGOXkmR2036wYHq7pTT7PFe/4yG35hN4okBkH99uDzOltrKLJnkPdTxbkgQTeaXLkMOIfyBO96q4MyDMHhT@NA3nhYNAvKmiBjzJBmV4@y8J2pf2SLBDQOhWSSIkuoOpoFlw0KzPaFby4CI@uCDDjHnSNiDDSe@FRQR7EwiF5FAuF5EmsDDJnEQmkLyLuJ12IF39CM5mrVVd/ZSD001gZbxXd06HW2Psmilp/v50vZt82y18czTC5TcpFQtUYMjRs3I2DRrcBDqlMWFuKhPnw5kOMYSrbst1Wn7cvrJekYkqPirUfHQ0TZrdlmwwWjWN2nv2/ZWvpfw "Python 2 – Try It Online") ]
[Question] [ You must write a program that encrypts an input into a string of characters. For every character `i` in the input up to the second to last character, take the `i` and `i+1` characters and encode them by writing the letters of the alphabet, in order, that range in the same direction between those chosen characters. For example: if the original string were `bo` then it would be encoded as `cdefghijklmn`, but if the string were `boa` then `bo` is encoded as `cdefghijklmn` and `oa` is encoded as `nmlkjihgfedcb` with the final encrypted string being `cdefghijklmnnmlkjihgfedcb`. If the original string contain zero letters between two chosen characters, such as the string `ab` then you should encrypt it as `aRb` with `R` standing for what direction in the alphabet to go in determining the original characters. The encrypted string `aRb` represents `ab` but the encrypted string `aLb` represents `ba` (`R` = right, `L` = left). If two chosen characters in the original string are the same, such as the string `tt`, then you should encrypt it as `tZt` with `Z` standing for zero letters in between. **Examples:** Input: `att` Output: `bcdefghijklmnopqrstZt` Input: `brep` Output: `cdefghijklmnopqqponmlkjihgffghijklmno` Input: `Optimizer` Output: `oRpqrssrqponmlkjjkllkjjklmnopqrstuvwxyyxwvutsrqponmlkjihgffghijklmnopq` **Rules:** * You can write a program or a function. * Your input may contain uppercase letters, so you need to put them all to lowercase before encrypting. * You can ignore non-alphabet characters. * One character length strings are undefined. * Shortest code in bytes wins! [Answer] # Pyth, 38 bytes ``` M|strFGjHGsm?>Fd_g_d\Lgd?qFd\Z\R.:rzZ2 ``` [Demonstration.](https://pyth.herokuapp.com/?code=M%7CstrFGjHGsm%3F%3EFd_g_d%5CLgd%3FqFd%5CZ%5CR.%3ArzZ2&input=Optimizer&debug=0) ``` M|strFGjHGsm?>Fd_g_d\Lgd?qFd\Z\R.:rzZ2 Implicit: z = input(), Z = 0 g is a function of a 2 letter string and an insert letter. M def g(G, H): return rFG Take the string range between the letters in G. t Remove the first letter to get just the letters in between. s Concatenate. | Logical or (if nothing in between) jHG H.join(G) rzZ Convert input to lowercase. .: 2 Take 2 letter substrings. m Map d over the substrings ?>Fd If the first character of `d` is greater than the second, _g_\L g(d[::-1], 'L')[::-1] gd else, g(d, ?qFd if the letters of d are the same, \Z 'Z' \R else 'R') s Concatenate and print. ``` [Answer] # C - 161 Bytes - GCC ``` #define y(x) putchar(x) main(_,z){for(_=getchar();-~(z=getchar());_=z)for(_==z?y(_),y(90),y(z):-~_==z?y(_++),y(82),y(z):_==-~z?y(_),y(76),y(z):_;_<z;y(_),_++);} ``` Will update when I get it shorter [Answer] # JavaScript ES6, 253 bytes ``` (d,y=`abcdefghijklmnopqrstuvwxyz`)=>[...`${d}`.toLowerCase()].map((l,i,a,m=a[i-1],c=s=>y.search(s),d=(s,e)=>y.slice(c(s),c(e)).slice(1),j=c(m),k=c(l))=>m?l==m?l+'Z'+l:j+1==k?m+'R'+l:k+1==j?l+'L'+m:j>k?[...d(l,m)].reverse().join``:k>j?d(m,l):0:'').join`` ``` Just by glancing you can see all the places where this can be golfed. I can probably chop off 100 bytes. Ungolfed: ``` (d,y=`abcdefghijklmnopqrstuvwxyz`)=> [...`${d}`.toLowerCase()].map((l,i,a, m=a[i-1], c=s=>y.search(s), d=(s,e)=>y.slice(c(s),c(e)).slice(1)) =>m? l==m? l+'Z'+l: c(m)+1==c(l)? m+'R'+l: c(l)+1==c(m)? l+'L'+m: c(m)>c(l)? [...d(l,m)].reverse().join``: c(l)>c(m)? d(m,l): 0: '').join`` ``` You can clearly see where this can be golfed in the `?:` sequence. --- ES5 Snippet: ``` function t(d) { var y = 'abcdefghijklmnopqrstuvwxyz'; return (d+'').toLowerCase().split('').map(function (l,i,a) { var m = a[i - 1], c = function (s) { return y.search(s) }, d = function (s,e) { return y.slice( c(s), c(e) ).slice(1); }; return m ? l == m ? l + 'Z' + l : c(m) + 1 == c(l) ? m + 'R' + l : c(l) + 1 == c(m) ? l + 'L' + m : c(m) > c(l) ? d(l,m).split('').reverse().join('') : c(l) > c(m) ? d(m,l) : 0 : '' }).join(''); } // Demo document.getElementById('go').onclick=function(){ document.getElementById('output').innerHTML = t(document.getElementById('input').value) }; ``` ``` <div style="padding-left:5px;padding-right:5px;"><h2 style="font-family:sans-serif">Encoding Snippet</h2><div><div style="background-color:#EFEFEF;border-radius:4px;padding:10px;"><input placeholder="Text here..." id="input"><button id='go'>Encode!</button></div><br><div style="background-color:#EFEFEF;border-radius:4px;padding:10px;"><span style="font-family:sans-serif;">Output:</span><br><pre id="output" style="background-color:#DEDEDE;padding:1em;border-radius:2px;overflow-x:auto;"></pre></div></div></div> ``` [Answer] # Python ~~343~~ 334 bytes ``` import sys,re,string j=''.join a=string.ascii_lowercase for l in sys.stdin: s,L=re.sub('[^a-z]','',l.lower()).strip(),[] for i,c in enumerate(s[:-1]):o=s[i+1:i+2]or c;b,d=a.index(c),a.index(o);L.extend(j(e[1])for e in[(c==o,[c,'Z',c]),(c<o,(a[b+1:d],[c,'R',o])[b+1==d]),(c>o,(a[d+1:b][::-1],[c,'L',o])[b-1==d])]if e[0]) print(j(L)) ``` Code on [ideone](http://ideone.com/1bkTYs). First golf ever. Any suggestions would be great. [Answer] # K5, 77 bytes *ouch* ``` ,/{$[(p:d>0)&3>d:1+x-y;"LZR"@d;`c$$[p;1_y+!x-y;|1_x+!y-x]]}':{(x;x+32)@x<97}' ``` Explanation coming after more golfing. [Answer] ## Haskell, 168 bytes ``` import Data.Char s=succ b#a|a==b=[a,'Z',b]|s a==b=[a,'R',b]|a==s b=[a,'L',b]|a>b=reverse$a#b|a<b=[s a..pred b] e=concat.(tail>>=zipWith(#)).map toLower.filter isLetter ``` running: ``` λ: e "att" "bcdefghijklmnopqrstZt" λ: e "brep" "cdefghijklmnopqqponmlkjihgffghijklmno" λ: e "Optimizer" "oRpqrssrqponmlkjjkllkjjklmnopqrstuvwxyyxwvutsrqponmlkjihgffghijklmnopq" λ: e "aabbcfcBBAa" "aZaaRbbZbbRcdeedcLbbZbbLaaZa" ``` [Answer] # Haskell, 185 bytes ``` import Data.Char s=succ p=pred f(a:b:c)|b==s a=q 'R'|a==s b=q 'L'|a==b=q 'Z'|a<b=[s a..p b]++n|a>b=[p a,p$p a..s b]++n where q m=a:m:b:n;n=f(b:c) f _=[] g x=f[toLower e|e<-x,isLetter e] ``` Usage: `g "brep"` -> `"cdefghijklmnopqqponmlkjihgffghijklmno"`. How it works: `g` throws away all non-letters and converts the letters to lower case and calls `f` to do the encryption. Depending on the first two characters `f` inserts `R`, `L` or `Z` or builds the sequence in-between and and appends the result of a recursive call of itself with the tail of the input. ]
[Question] [ In *as few characters of code as you can*, create an algorithm which will pack *the least number of rectangles* necessary to *completely fill* a rasterized circle with integer radius *r* and return the parameters necessary to create each rectangle. ![I don't like cyan or pink, but here they are.](https://i.stack.imgur.com/h5qSK.png) In the above image, the cyan portion is the "idealized" circle. The darkened cells have been selected by a rasterization algorithm. The area to be filled in is within the black line around the cyan circle. Here's one way to fill that circle: ![Transformers!](https://i.stack.imgur.com/1dXEO.png) Here's another: ![Robots in disguise.](https://i.stack.imgur.com/Ckbqh.png) **The fine print:** * All units will/must be centimeters. * Rectangles should be in the format [x y width height], where x and y is the position of the upper left corner and width and height are positive numbers for the width and height from that point. * + Example: [10 20 40 20][-10 -20 20 40] ... * Rectangles *may overlap each other*, but their bounds *must* be within or coincident to the rasterized circle. Rectangles must not extend past those bounds. * The algorithm's results must match what would be expected from the bounds given by the [Midpoint Circle Algorithm](http://en.wikipedia.org/wiki/Midpoint_circle_algorithm) with parameters *x* = 0, *y* = 0, *r* = *radius*. * While there might be a minimum number of rectangles needed to fill the circle, finding them might make your code longer than it's worth with respect to the length of the code. (see scoring system below) * It isn't necessary to actually draw anything. Just return the rectangles needed. * Coordinate system should be Cartesian, so not display graphics definition. Eg. (+x, +y) quadrant is north-east of (0, 0), (+x, -y) is south-east, (-x, -y) is south-west, and (-x, +y) is north-west. To test for correctness, use your chosen rasterization method to draw a circle. Draw the rectangles from your rectangle packing algorithm. Check for gaps inside the circle or pixels outside the circle. **Expected signature of function:** (ℕ radius) → {(ℤ x, ℤ y, ℕ width, ℕ height), ...} **The very complex scoring system:** ``` [code characters]*([rectangles for radius of 10]/10 + [rectangles for radius of 100]/100 + [rectangles for radius of 1000]/1000) ``` *Lowest* score wins. In the event of a tie, winner will be the most popular. Winner will be selected at midnight GMT, January 16th 2014. [Answer] # Mathematica (105) * 63 characters * 1.665 multiplier (5/10+58/100+585/1000) Function: ``` f={-#,#}&/@Last/@{n+1,⌈√(#^2-n^2)⌉}~Table~{n,#-1}~SplitBy~Last& ``` For `r=10` its output is ``` f[10] {{{-5, -10}, {5, 10}}, {{-6, -9}, {6, 9}}, {{-8, -8}, {8, 8}}, {{-9, -6}, {9, 6}}, {{-10, -5}, {10, 5}}} ``` It is coordinates of left-bottom and right-top corners of rectangles (it's native for *Mathematica*'s rectangles) The number of rectangles for `r=10,100,1000` ``` Length@f@# & /@ {10, 100, 1000} ``` > > {5, 58, 585} > > > Visualization: ``` Graphics[{EdgeForm[Black], EdgeForm@Thickness[0.005], Blue, Opacity[0.3], Rectangle@@@f[10], Disk[{0, 0}, 10]}, Axes -> True, GridLines -> {#, #} &@Range[-10, 10]] ``` ![enter image description here](https://i.stack.imgur.com/lQM3U.png) **Update:** it seems that the theoretical limit is ![enter image description here](https://i.stack.imgur.com/gCt4w.png) [Answer] Pre-rule-change answer: ## C# / ECMAScript 6 - 12 ``` r=>r ``` Because overlapping rectangles are allowed, we need at most `r` rectangles. Proof: ![I did not make this a gif. You're welcome.](https://i.stack.imgur.com/kU3Zg.png) With a circle of radius 10, it can be filled with 10 rectangles. Each rectangle has been highlighted in a distinct colour. --- Older pre-rule-change answer: **C# / ECMAScript 6 - 0.444** ``` r=>1 ``` I believe this meets all the rules as of the time of this writing. It evaluates to the number of rectangles required to fill a circle, rasterized with this algorithm: ``` inCircle = max(|x|,|y|) <= radius ``` This algorithm doesn't yield very high-quality results, but it can still be useful. The popular video game *Minecraft* uses this algorithm. [Answer] # C#: ~~514.892~~ 479.298 * Characters: 254 * Number of rectangles: 7, 60, and 587. Rectangle multiplier = 1.887 Method takes a single integer as parameter, and returns a `List<Int32Rect>` as the result. Could probably shave a few more characters off by searching for another rectangle class with a shorter name, but `Int32Rect` is probably the most correct one to use here. You didn't specify which coordinate system we should be using. I'm assuming Cartesian coordinates (X & Y increase toward the top & right), as opposed to the more standard in computer graphics, where Y increases toward the bottom. ``` using System.Collections.Generic;using R=System.Windows.Int32Rect; class G{List<R>A(int r){var z=new List<R>();int x=r,y=0,e=1-x;while(x>=y) if(e<0)e+=2*++y+1;else{z.Add(new R(-x,y,2*x,2*y));if(x!=y)z.Add(new R(-y,x,2*y,2*x)); e+=2*(++y- --x+1);}return z;}} ``` ## Edit * Removed namespace. * In the 10 and 1000 circles, the last two rectangles were exactly the same. As x decreases and y increases, sometimes they meet, sometimes they're one off from each other on the last iteration. On the 100 circle, the last iteration is with x=70,y=71, so there's no duplicate. On the 10 circle, the last iteration is x=y=7, so checking for x!=y eliminates that duplicate rectangle. On the 1000 circle, the last iteration is x=y=707. Results with 10: ![enter image description here](https://i.stack.imgur.com/efMmd.png) Results with 100: ![enter image description here](https://i.stack.imgur.com/csKtn.png) ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/15339/edit). Closed 7 years ago. [Improve this question](/posts/15339/edit) The functions receives 5 numbers, let's call them a, b, c, d and e You must display two numbers. First one is (((a + b) - c) \* d) % e = f Second one is (((a + b) - c) \* d - f) / e ``` Input: Output: 7 5 9 3 8 1 1 1 2 3 4 5 0 0 19 25 9 7 11 3 22 21 12 99 3 13 -3 -15 21 12 99 3 -4 -2 49 ``` Requirement: You are not allowed to use '***+***' '***-***' '***\****' '***/***' symbols (or equivalent) when doing the calculation. You may however use '***%***' symbol (or equivalent) when doing the calculation. By equivalent I meant that you are not allowed to use functions such as `BigInteger.add()` (**I am looking at you java users**). Shortest code wins. EDIT: as Peter suggested a clarification. All input numbers are int, and will never be 0 [Answer] ## Forth, 323 chars ``` : u 2dup ; : p swap ; : t -rot ; : a u xor t and begin ?dup while 2* u xor t and repeat ; : n invert 1 a ; : m dup 0 < if p n p n then 0 p 0 ?do over a loop nip ; : d dup 0 < t p dup 0 < t abs p abs p 0 begin t u <= while over n a rot 1 a repeat 2drop t xor if n then ; : y 4 roll 4 roll a 3 roll n a rot m p u mod . d . ; ``` The forbidden arithmetic operations are defined in terms of binary operations. The core Forth word `mod` is used as the equivalent of `%`. The final word `y` is the top-level function that accepts five numbers and prints two numbers as output. [Answer] # Mathematica, 54 chars I just use dot product. ``` f={Mod@##,Quotient@##}&[{{#,#2,#3}.{1,1,-1}}.{#4},#5]& ``` Example: ``` f[19, 25, 9, 7, 11] ``` > > {3, 22} > > > [Answer] **C++ 503 characters** ``` #include<iostream> #define I int #define R return #define T (I x,I y) I A T{I a,b;do{a=x&y;b=x^y;x=a<<1;y=b;}while(a);R b;} I N(I v){R A(~v,1);} I S T{R A(x,N(y));} I V(I v){R v<0?N(v):v;} I M T{I a=0;I i=0;while(i<V(x)){i=A(i,1);a=A(a,y);}R x<0?S(0,a):a;} I D T{I a=0;x=y==0?0:x;while(M(V(y),a)<V(x))a=A(a,1);R M(y==0?0:S(A(a,1),(x%y==0?1:2)),x<0^y<0?N(1):1);} void C(I a,I b,I c,I d,I e){I g,f;f=(g=M(S(A(a,b),c),d))%e;std::cout<<f<<' '<<D(S(g,f),e);} I main(I a){I b,c,d,e;std::cin>>a>>b>>c>>d>>e;C(a,b,c,d,e);} ``` I get the same results as your examples except for the last two, I get -3 -15 and -2 49 respectively. This is the same result that I get from the following... ``` int f = (((a + b) - c) * d) % e; std::cout << f << ' ' << (((a + b) - c) * d - f) / e; ``` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 4 months ago. [Improve this question](/posts/266414/edit) Given a base \$k\$ as well as two indices (also passed in base \$k\$, call them \$s\$ and \$e\$) return a list containing a frequency count of all base-\$k\$ digits occurring between \$s\$ and \$e\$ inclusive. For example, upon input \$k = 10, s = 1, e = 10\$, we would return the list \$[0: 1, 1: 2, 2: 1, 3: 1, 4:1, 5:1, 6:1 , 7:1, 8:1, 9:1]\$. Note that the values in the list should be base \$k\$ as well. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 75 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 9.375 bytes ``` vβ÷ṡ⁰τfĊ⁰τ ``` Accepts input as \$[s, e], k\$. Takes in indices as a list of digits (to be able to take numbers of bases greater than 10). [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyI9IiwiIiwids6yw7fhuaHigbDPhGbEiuKBsM+EIiwiIiwiW1syXSwgWzEsIDIsIDFdXVxuMyJd) | [Another example](https://vyxal.pythonanywhere.com/?v=2&c=1#WyI9IiwiIiwids6yw7fhuaHigbDPhGbEiuKBsM+EIiwiIiwiW1s1XSwgWzEsIDE0LCAxM11dXG4xNiJd) Bitstring: ``` 100011000100010100000110110111110010011010110100010011110011110110000110010 ``` ``` vβ÷ṡ⁰τfĊ⁰τ vβ Convert each index to base 10 ÷ṡ Split to stack and push range ⁰τ Convert range to base k fĊ Flatten list and push counts ⁰τ Convert counts list to base k ``` [Answer] # [Python](https://www.python.org), 163 bytes ``` def f(k,s,e):b=lambda n:n and b(n//k).lstrip("0")+[str(n%k),chr(n%k+55)][n%k>9]or"0";a="".join(map(b,range(int(s,k),int(e,k)+1)));return{c:b(a.count(c))for c in a} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY9BCsIwEEWvEgLCDI3VLgSt6EXERZImWquTkqYLEU_iRhC9gYfxNo6Ki4EH_394c3m0x7QNdL3e--SH09etcl54aFSnHJZmsdcHU2lBJQlNlTBAo1GD-b5LsW5BjiVmK2agQYPKbr-QTSa4XjEsZ-sQuTPXCynzXagJDroFo6KmjYOaEnSKdx9wDFmBiPPoUh_pZEsDOreh59Ai-hCFFTVrnH-qzzZ-dh6KsZKF5GMZ_GX_d94) Basic solution; a majority of the code is taken up by the helper function converting from base 10 to base \$k\$. I'm sure you could do something clever with a function which directly counts from \$s\$ to \$e\$ in base \$k\$. Only works for bases between 2 and 36. [Answer] # [Ruby](https://www.ruby-lang.org/), 80 bytes ``` ->k,s,e{(s.to_i(k)..e.to_i(k)).flat_map{_1.digits k}.tally.map{[_1,_2.to_s(k)]}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhY3A3TtsnWKdVKrNYr1SvLjMzWyNfX0UmFMTb20nMSS-NzEgup4Q72UzPTMkmKF7Fq9ksScnEo9kHB0vKFOvBFIfTFQfWxtLdRc4wKFtGhDAx0lQyUgNlCK5QIJGOsoGYH4RoZQAUMzHSVTkEhqilIsROuCBRAaAA) Takes `k` as integer, `s` and `e` as strings in base `k`. Test cases taken from math scat's [Vyxal answer](https://codegolf.stackexchange.com/a/266415/78274). [Answer] # [Haskell](https://www.haskell.org), 148 bytes ``` import Data.List k#n|n<k=[n] k#n|(d,m)<-divMod n k=m:k#d f k s e=[(last(show x:[[toEnum$x+55]|x>9]),1+length y)|x:y<-group$sort$concatMap(k#)[s..e]] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY89jsIwFIR7TvGkpLAXEi1CIIgSKuiWE1guLJIQy_FzFL9AkHIMOhqa1Z5pb7P8LM3oK0b6Zq4_lfKmqOvb7bujMlr-XrRtXEuwUaTiL-1pZAIcMDWZQPlklk8sT6NcH3cuBwST2cQE-agEAx6KTLBaeWK-cifoEyHIbbGzYT-ez-XQr1eST6bjusADVXDmQ5-c0-jQuq4J_V0c7h3uFe1Uw0zAhY_jQsr_bYFVGiGDptVIEEIJswV8ArvnxwMjmPJX9X3nDw) [Answer] # Google Sheets, 228 bytes `=let(_,lambda(v,base(v,A1)),r,query(tocol(sort(to_text(split(regexreplace(join(,map(sequence(A3-A2+1,1,A2),_)),"(.)","$1 ")," ")))),"select count(Col1),Col1 group by Col1 label count(Col1)''",0),{map(index(r,,1),_),index(r,,2)})` Put the base in cell `A1`, start in `A2` and end in `A3`, and the formula in `C1`. The same ungolfed: ``` =let( _, lambda(v, base(v, A1)), values, sequence(A3 - A2 + 1, 1, A2), string, join(, map(values, _)), digits, tocol(sort(to_text(split(regexreplace(string, "(.)", "$1 "), " ")))), result, query( digits, "select count(Col1), Col1 group by Col1 label count(Col1)''", 0 ), hstack( map(index(result, , 1), _), index(result, , 2) ) ) ``` | parameters | | results | | | --- | --- | --- | --- | | 16 | base | C | 0 | | 1 | start | 1D | 1 | | 200 | end | 1D | 2 | | | | 1D | 3 | | | | 1D | 4 | | | | 1D | 5 | | | | 1D | 6 | | | | 1D | 7 | | | | 1D | 8 | | | | 1C | 9 | | | | 1C | A | | | | 1C | B | | | | 15 | C | | | | C | D | | | | C | E | | | | C | F | ]
[Question] [ Input: a whole positive number greater than 4 Output: A whole positive number that describes the highest possible period an oscillator could have inside a square space of size (input)x(input) in a "life" grid that follows the rules of Conway's Game of Life. The oscillator never leaves this area throughout its cycles. It may not interact with any outside cells. There is no wall, cells outside this area are just dead by default. Your program should be able to theoretically calculate as high of a number as the 32 bit Integer Limit. Winner: this is code-golf, so shortest code in bytes wins! [Answer] # [Rust](https://www.rust-lang.org/) + [rlifesrc-lib](https://crates.io/crates/rlifesrc-lib), 114 bytes When I wrote this lib I never thought one day I would use it in codegolf. ``` use rlifesrc_lib::*; |n|(1..1<<n*n).rev().find(|&p|Config::new(n,n,p).world().unwrap().search(None)!=Status::None) ``` Very inefficient. Only works for \$n=2\$. It tries every period from \$p=2^{n^2}-1\$ to \$1\$. It would be faster if there is a better upper bound for the period. [Answer] # Python, 368 bytes Let’s get the elephant out of the room: This thing has runtime \$n^2(2^{n^2})^2\$. But hey, you said *short*, not *efficient*. ``` from numpy import * from itertools import * P=lambda x,n:product(x,repeat=n) n=int(input()) s=lambda x,i,j:sum(x[max(0,i-1):i+2,max(0,j-1):j+2]) def c(x): y=copy(x) for i,j in P(range(n),2):x[i,j]=2<s(y,i,j)<4+y[i,j] def r(x): x=array(x);x.shape=(n,n);y=copy(x);a=0 while a<2**(n**2): c(x);a+=1 if all(x==y):return a return 0 print(max(map(r,P((0,1),n**2)))) ``` This solution basically tries all \$2^{n^2}\$ possible variants for periodicity. That is, if after \$k\$ iterations we reach the starting point for the first time. Since only \$2^{n^2}\$ possible combinations exist we know that we can stop after this many iterations. Also note that the memory footprint of this solution is not too bad. Our memory complexity should be around \$n^2\$, so this code will handle fairly large input numbers, but it will take a decent amount of time. ]
[Question] [ Given infinite different integers, order them into a sequence \$a\_1, a\_2, a\_3, ...\$ such that \$a\_i>a\_{i+1}\$ iff \$i\$ is even(or odd, as long as it's constant for all possible inputs and all \$i\$). In other word, make the sequence go alternately up and down (or down first, as long as it's constant). Examples: ``` ℤ => 0,1,-1,2,-2,3,-3,... ℕ => 0,2,1,4,3,6,5,8,7,... ``` `ℤ => -1,1,-2,2,-3,3,...` is invalid, as 0 never appears, claiming it appears infinitely far away doesn't help. Also it is worth to mention that these two examples covers all possible input types(No maximum or minimum / One border exists). --- Default sequence IO applies. You can take input as an unordered(aka. you can't specify the order it has) sequence or a function checking if a value is in the set. Shortest code in each language wins. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 140 bytes ``` k=lambda:[int(input())] S=sorted c,*p=S(k()+k()+k()) u=0 while 1:print(c);p=S(p+k());p.remove(c:=[x for x in p if x-p[u]if(x>c)^-u][u]);u=~u ``` [Try it online!](https://tio.run/##LYvLDoIwFAX39yu6bFUMiA@E1J9gSTDBUkLDoze11brx16sYF2cxmTn4sr2e0wxNCAMfm@nWNnmlZkvVjM5Sxmoo@V0bK1sQmxXykg6Urf9j4HgMz16NkiQ5muUoWLFU@PMFbo2c9ENSkfPKk04b4omaCRLVER9h5WrVUX8R7Bq5@kuscPztQkhgByns4QBHOEEGZ0jiDw "Python 3.8 (pre-release) – Try It Online") -3 bytes thanks to l4m2 -9 bytes thanks to Wasif -5 bytes thanks to l4m2 -9 bytes thanks to Don Thousand -13 bytes thanks to Don Thousand -11 bytes thanks to Don Thousand -3 bytes thanks to l4m2 -2 bytes thanks to l4m2 -6 bytes thanks to ovs -4 bytes thanks to Don Thousand -12 bytes thanks to l4m2 -5 bytes thanks to ophact [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 28 bytes ``` i»2$ịḟñ@ḟ ;ƓṢNÞƭçṄ} Ɠ;Ɠ$⁺çṂƊ ``` [Try it online!](https://tio.run/##y0rNyan8/z/z0G4jlYe7ux/umH94owOQ5LI@NvnhzkV@h@cdW3t4@cOdLbVcxyYDxVQeNe4C8ZuOdf3/b8RlyGXMZcJlyWXGZcFlaMBlyqVrzKVrzqULZBuaclkCWUamBlwGXGbGXEbG5lyGJgA "Jelly – Try It Online") A full program that reads an infinite unsorted series from STDIN and writes it in an order meeting the criteria in the question (up-down-up-down…). Uses a modified version of [@hyper-neutrino’s Python algorithm](https://codegolf.stackexchange.com/a/229272/42248). ## Explanation ### Helper link 1 Takes a sorted list of 4 integers (x) as well as the most recent output (y) and calls helper link 2 with the same list after filtering out the most recent output as the left argument and the next output as the right argument. ``` i | Index of y in x »2$ | Max of this and 2 ịḟ | Index into x after filtering out y (call this z) ñ@ḟ | Call helper link 2 with the filtered y on the left and z on the right ``` ### Helper link 2 Takes a list of 3 integers on the left (v) and the next output on the right (w). Appends a new input to the list, sorts it, prints the output and calls helper link 1 with the new sorted list and the output just printed ``` ;Ɠ | Append next input to list ṢNÞƭ | Sort upwards on first call, downwards on next call and alternate for each subsequent call çṄ} | Call helper link 1 with the sorted list on the left and w on the right ``` ### Main link ``` Ɠ | Input from STDIN ;Ɠ$ | Append next input Ɗ | Following as a monad: ⁺ | - Append next inlut çṂ | - Call helper link 2 with all three inputs on left and min of first two on right ``` [Answer] # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 74 bytes ``` x=>y=>i=g=z=>print(x-(x=(z+=Math.random(i=!i)>.5&&y-(y=z))>x!=i?x:z)+z)||g ``` [Try it online!](https://tio.run/##VcxbCoMwEAXQ/@7CH5lBFKymtpVJV9BFhPpoLD6IUpLg3lMbodDPO/fM7cRbzA8lpyWeJ1nVqh@HV21cQ04TN8QltWSJT0oOC@gYNIGN6C6WZ6LEUI09SAok8oSFoYnBkEXkOiB501eLkcV1bV0DKcIRIUPIERjCCaFAOCNcsNynsTw0W/reCt8zbzP/l/4p5knulZ/YyWZ/yn0A "JavaScript (SpiderMonkey) – Try It Online") I cannot find out any discuss about function reusable requirements for infinite inputs... I hope this one is acceptable.. To my understanding, this should [work with probability 1](https://codegolf.meta.stackexchange.com/questions/12498/how-do-we-define-deterministic-and-is-it-required-by-default/12591#12591). [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~21~~ 17 bytes Uses an even-sized moving window with a size of at least 4, moving it 2 slots on every iteration. This way we can't get stuck on intermediate values, while also not needing separate handling for upwards or downwards movement. Originally, I used a window 4 elements wide, but using `A = 10` saves a byte due to automatic comma insertion. Uses reducing to move through the array, mapping works just the same but is a few bytes longer. Cut off 4 bytes thanks to Shaggy. ``` rÈiYÑXjYÑA Íó)c}N r }N // Reduce the input with the initial value of the inputs array. Xj A // Get A = 10 items from the input YÑ // at iterator index * 2 so we're always at even steps. Íó // Sort and interleave to get the zig-zag pattern. Èi // Insert the result back into the array YÑ // at the same index, )c // and flatten out all nested arrays. ``` [Try it here.](https://ethproductions.github.io/japt/?v=1.4.6&code=cshpWdFYalnRQSDN8yljfU4=&input=LVEKWzksMTAsMTEsMTIsMTMsMTQsLTUsLTQsLTMsLTIsLTEsMCwxLDIsMyw0LDUsNiw3LDhd) A short manual example with a window size of 4: ``` [..., -5, -4, -3, -2, -1, 0, 1, 2, ...] ~~~~~~~~~~~~~~ [..., -5, -3, -4, -2, -1, 0, 1, 2, ...] ~~~~~~~~~~~~~~ [..., -5, -3, -4, -1, -2, 0, 1, 2, ...] ~~~~~~~~~~~~~~ [..., -5, -3, -4, -1, -2, 1, 0, 2, ...] ~~~~~~~~~~ ``` ]
[Question] [ [Choose a challenge from the Cops thread](https://codegolf.stackexchange.com/q/223158/45613), determine the third hidden message, and describe how the system works. Keep in mind limitations and possibilities available to Cops: * You are not expected to guess any cryptographic secrets or additional information required to extract the hidden messages, as they should have already been included in their post. * The hidden message will be in English * The hidden message may be encoded as plain text, a text bitmap rendering, audio clip, or ascii art font. This encoding will be consistent across all hidden messages. * No further processing will be required after obtaining the hidden message. * Data is allowed to be hidden in metadata, but at least one bit of one pixel must have been used for something. Score 1 point per cracked system. [Answer] # [CreaZyp154](https://codegolf.stackexchange.com/a/239893/85334)'s I don't know the first thing about image encodings, but it looks like in each of the three images every pixel is an index into a palette containing two identical colors. Messages are encoded as transposed images in the palette indices. Thus, the third image says `STEGANOGRAPHY`: [![enter image description here](https://i.stack.imgur.com/x2oGb.png)](https://i.stack.imgur.com/x2oGb.png) [Answer] # [emanresu A](https://codegolf.stackexchange.com/a/223192/79857)'s Image 1, which encodes `HI`, can be decoded by turning it into a 32×32 square: [![The word "HI"](https://i.stack.imgur.com/oXBer.png)](https://i.stack.imgur.com/oXBer.png) Same with Image 2, which encodes `BYE`: [![The word "BYE"](https://i.stack.imgur.com/C1YSg.png)](https://i.stack.imgur.com/C1YSg.png) And, with Image 3: > > [![The words "OI You!"](https://i.stack.imgur.com/dkayW.png)](https://i.stack.imgur.com/dkayW.png) > > > > The words `OI You!` > > > Since all the images are 1024×1, you just need to split it into segments 32 pixels wide, and stack them on top of one another. Here's a tool I wrote to do this: <https://gist.github.com/Radvylf/b5d1bc5f39903400b243abf2041feefe> ]
[Question] [ In this task you are expected to provide a **list** output given an input [tq](https://github.com/A-ee/tq) program. The tq programs will not contain whitespace inside them. ## What is tq, in the first place? tq is a lazy-evaluated language that is designed with the idea that array items should be accessable during the definition of them. In tq, there is no explicit separator of an array, only special arrangements of monadic/dyadic functions and nilads. The following program is a program printing `[123]` (Pretend that tq doesn't support strings because we aren't dealing with them in this case): ``` 123 ``` This defines a list with the first item being the number 123, after which all items in the list will be outputted inside a list. In tq, numbers are supported to allow multiple-digits. So this defines a list with 2 items: ``` 12+12,5 ``` In this test case, you are expected to output the list `[24,5]`. Let's explain it step by step. ``` 12+12 # This evaluates 12 + 12 in the current item in the list, returning 24 , # A separator. This separates two items when they could be potentially # ambiguous when they are applied without a separator. 5 # This evaluates 5 in the current item in the list, returning 5 # The comma is simply a no-op that doesn't require parsing. ``` So you think that tq is not hard at all to implement? Well, remember that tq also has a special feature of accessing the items in an array before the array is defined! ``` 555th123 ``` We introduce two new atoms: * `t` (**t**ail) means access the last item in the list * `h` (**h**ead) means access the first item in the list Therefore our list is going to yield: ``` [555,123,555,123] ``` Now take a look at this program: ``` 555ps123 ``` We introduce 2 more atoms: * `p` Yield the next item *before* (**p**revious) the current position * `s` Yield the next item *after* (**s**ucceeding)the current position This yields the list: ``` [555,555,123,123] ``` ## A quick reference of the tq language Just assume that you only have two operands for the operators. * `[0-9]` starts a number. Numbers will *only* be positive integers, i.e. no decimals and negative numbers. * `,` This is a separator of different items when it is given that two consecutive indexes will be ambiguous with each other without a separator. In tq all of the remaining characters can act as a separator, but in this case it is a good idea to implement only `,` for the ease of your implementation. * `+` and `*` These are arithmetic operators. Usually in tq, they may be applied multiple times, e.g. `1+2+3`, but in your implementation, input will be provided so that this will not happen and only `1+2` will happen (there will not be applications multiple times). * `t` return the last item in the list. If the code is `t1,2,3` it shall return `[3,1,2,3]`. * `h` return the first item in the list. If the code is `1,2,3h` it shall return `[1,2,3,1]`. * `p` returns the item before the current item. If the code is `0,1,p,3,4` the code shall return `[0,1,1,3,4]`. * `s` returns the item after the current item. If the code is `0,1,s,3,4` the code shall return `[0,1,3,3,4]`. ## Additional rules (with some examples) * You also have to implement multiple hops. E.g. `1th` should yield `[1,1,1]` * If you know that something is going to form a loop, e.g. `1sp2`, the cells that form the loop should be removed. Therefore the previous example will yield `[1,2]`. * Out of bounds indexing will yield the closest index of the indexed item **that is a number**. E.g. `1,2s` should yield `[1,2,2]` * If any possible indexing fails, you may do whatever operation you prefer. ## More test cases * `4p*p` will yield `[4,16]` * `1p+s2` will yield `[1,3,2]` * `1,2,3h+t4,5,6` will yield `[1,2,3,7,4,5,6]` * `3ppss6` will yield `[3,3,3,6,6,6]` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 131 bytes ``` +Ø+o+2$};;1N;ؽ“spth+*”żF ṣ”,µeþØD,Øa¤Ḥ2¦SSƝ>2k)Ẏµe€⁾+*oḊ$k)µJç€LyⱮ"ƲVḢf?€€ØDAƑƇ.ị;@Ʋµṙ-+;×ɗị@ƭ/$¹L’$?¹Nị⁸¹L’$?ɗAƑ?€AƑ?F¥€`ÐLAƑƇFṖṖ ``` [Try it online!](https://tio.run/##TU9PSwJBFL/Pp5DYiztjtbsqyIAahIcQL0LQrQ7GkoIDsxcPgXoRCqIuuUJeSutiQZKwm@Vhhhb8GDNfZHu7EAQP3o/fP967aHU6vTjG0sddbBuXlFoNKn3xrfsPnHkuNnV/@vNVQyp8AkTEqiU30j8k0j8TMxXMbPHcbEbTst3Oqs8bkPVwoQcbbHZVcGW0s2J1JF@Aq/f0@9tOtDxWweN5JTENF9BzEN1Fo121vqbVaClWKpzkMJXj7RioavS6Z4iwrvsToyLCBlB6EPwR2zFkk6Jk1cQc0Km8raeFNRXew8QUvsjkyhm4nMqRCjcGUusPOQLvSRzvE4sw4pA8ShBPUZ6ZDFkMcxtZxCaOi708KZAichjjvIgsz0UWZzZibqp7HHmFNPPfTZhZcqDEw26h9As "Jelly – Try It Online") A full program taking a tq program string as its input and returning a list of integers. Still needs more golfing, but seems to work ok. Doesn’t use `eval` except for converting numbers from string to integer (which wouldn’t be an `eval` in most languages). [Answer] # [Python 3](https://docs.python.org/3/), ~~536~~ 522 bytes ``` def f(c): D={"t":"o[n]","h":"o[0]","p":"o[i-1]","s":"o[i+1]"};o=[];T="";A=o.append;l=type;n=-1 for C in c: if C==",":A(T);T="" elif C in"0123456789": if"o"in T: A(T);T=C else:T+=C elif C in"htps": if T and T[n]in"+*":T+=D[C] else: if T:A(T) T=D[C] else: T+=C if T:A(T) if D['s']in o[n]:o[n]=o[n].replace("i+1","i-1") while not all([l(m)==int for m in o]): for i in range(len(o)): x=o[i] try:x=eval(str(o[i])) except:pass if l(x)is str:continue else:o[i]=x return o ``` [Try it online!](https://tio.run/##VVFNb6MwEL3nV4x8qSlu1UBItyAfquQncEM5IOIsSK6xsNtNtNrfnh0bQ0CWYN7Me/Opb7btVXq/n8UFLrSJ8g0c@V9iSU76Sp0II60335ypvdm9bB0wI4gR/Ct6Xp2KkhNSfPL@tdZaqHMhub1pUSj@st3ApR/gAJ2CBktAd4ED55gl/6Rl5JXoFdL5kUTetkm6y/bvvz6IoyOf9ATFpUcQRAcHhDQiL2MPHglaq80khRJqdYYS58FI/Ewc/VgdTrPcJ3VE345H5cSYCWONBQvNY/VknjAruGXl7sPd53UQWtaNoAT3g1PiyggK/rSdFKB6C7WUtJL0K@K8U9Yv58stpz@5C3jcOTzU6regUijaRz4CVyzQ@c7tcMuvXPzUkho7UOeOfO/i2ghtc10bExYg6TXqDCAtb3plO/Ut5tmdjl83MAj7PWAHdz1gS/RCCd6ARMA5VGidGEyuaLOgxNuEZYGW7BhkEzEEFuQsy2z7SIqQIWLhP@oenLVQm7VwEi@FgbMQ7vSzDiJsbbsfqaN3OYWOTTKNyiBlkIQpxsCSyhKWtrHdsYztZwn62DvzviBc0xYJUq2NmZQpc2/v3qibosuKtp3r4Av5nXPdlll0k8xdmBXNZo@FJBkeCycNBwuh6P4f "Python 3 – Try It Online") Ungolfed: ``` def tq(code): corresp = {"t":"output[-1]","h":"output[0]","p":"output[i-1]","s":"output[i+1]"} output = [] temp = "" for char in code: if char == ",": output.append(temp) temp = "" elif char in "0123456789": if "h" in temp or "t" in temp or "p" in temp or "s" in temp: output.append(temp) temp = char else: temp += char elif char in "htps": if temp and temp[-1] in "+*": temp += corresp[char] else: if temp: output.append(temp) temp = corresp[char] else: temp += char if temp: output.append(temp) if 'output[i+1]' in output[-1]: output[-1] = output[-1].replace("i+1","i-1") while not all([type(m) == int for m in output]): for i in range(len(output)): x = output[i] try: x = eval(str(output[i])) except: pass if type(x) is str: continue else: output[i] = x return output ``` Somehow, by fixing a bug, I was able to remove 14 bytes. I've well and truly broken code golf now. Anyhow, this takes the program, parses it into `eval`able chunks and then evals them. [Answer] # JavaScript (ES6), ~~269 263~~ 262 bytes ``` v=>(F=r=>r+''==(h=(i,d)=>r[i]?1/r[i]?i:h(i+d,d):h,L=r.length-1,r=r.map((s,i)=>1/(x=eval((s+'').replace(/[h-t]/g,c=>` +r[${c<'i'?0:c>'s'?L:c>F?++i<L?i:h(L,-1):i?i-1:h(0,1)}]`)))?x:s))?r.filter(x=>1/x):F(r))(v.split(/,|((?:\d+|.)(?:[+*](?:\d+|.))?)/).filter(v=>v)) ``` [Try it online!](https://tio.run/##hZHBbuIwEIbv@xSoWikePElwQtIS1eTGiTdgkRqFgL1KwbKtCGm7z85OUrUHAmxGij2j@fzrn/lddZWrrTY@PJ52zWUvL51cspW0cml5EEjJlGQad0D5Rm9LEQ@HLhTTfEf1QuFa2qhtjgevQoGWkvfKMOZQEyRidpZNV7VUoPcgso1pq7ph8UaFfhsfsJbLtwm3m59/6tdAB@WsqJeBC8o1nauSc/26HuTWGAoodKlDQdkMBfzdvgFAeS4c/W20161vLMmR6BmKFbMArIucabVnMX4wVha/dvwjArps@HT7nUMJMXzx5L8DuNSnozu1TdSeDmzPnkgPDaY4fwKYjL44nvQNom/4cYN0/yPTW@TcTM1N6Iuco8ivIWG4S@5SBPViyYjCBFPF/RwzzEf0QFEDPuPQcE2nxjiX3xMlOh0M5n2MlL267/FTmWJEOZM8HI0YezRqMOHdvUUMSoNPimvaZ4@2QXSS0WiS7OFk0UwXKS3Ic5Ut@se@J5vPPkeLWfaCuXjpC9ni8g8 "JavaScript (Node.js) – Try It Online") Test cases borrowed from [Nick's answer](https://codegolf.stackexchange.com/a/197711/58563). ### How? We first split the input into tokens with the following regular expression: ``` +---------------------------> either a comma (discarded) | or the following group (captured): | +------------------> 1st operand: | | a number or a single non-numeric character | | which may be followed by: | | +----------> an operator | | | +--> and a 2nd operand | ___|_ __|_ ___|_ ,|((?:\d+|.)(?:[+*](?:\d+|.))?) ``` Example: ``` "12,3p*4h" --> [ '12', undefined, '3', 'p*4', 'h' ] ``` Empty or undefined elements are removed with `filter(v => v)`. The result is passed to the main function \$F\$ which recursively attempts to replace expressions with numeric values until no further modification is possible. ``` F = r => // F is a function taking a list of tokens r[] r + '' == ( // test whether r[] is modified by this iteration h = (i, d) => // h is a function taking i = position, d = direction r[i] ? // if r[i] is defined: 1 / r[i] ? i // if r[i] is numeric, return i : h(i + d, d) // otherwise, add d to i and try again : // else: h, // return a non-numeric value L = r.length - 1, // L = index of last element in r[] r = r.map((s, i) => // for each element s at position i in r[]: 1 / ( // x = eval((s + '').replace( // evaluate s /[h-t]/g, // where letters are replaced with c => ` +r[${ // " +r[index]" where the index is: c < 'i' ? 0 : // 'h' -> 0 c > 's' ? L : // 't' -> L c > F ? // 's' -> ++i < L ? i // i + 1 if this is not the last item : h(L, -1) // or the first preceding number : // 'p' -> i ? i - 1 // i - 1 if this is not the first item : h(0, 1) // or the first following number }]`)) // ) ? x : s // yield x if it's numeric or s otherwise ) // end of map() ) ? // if r[] is unchanged: r.filter(x => 1 / x) // return it with non-numeric items removed : // else: F(r) // do a recursive call ``` [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 174 bytes [SBCS](https://github.com/abrudz/SBCS) ``` a←('t'⎕R'a[≢a]')¨('h'⎕R'a[1]')¨','(≠⊆⊢)'[^,\d]([+×][^,\d]){0,1}'⎕R',&,'⊢⎕ a←{'s'⎕R(x,'+1]')⊢'p'⎕R((x←'a[',⍕⊃⌽⍵),'-1]')⊢⊃⍵}¨↓a,⍪⍳≢a t/⍨(⊢≢⍕)¨t←⊃¨{a⊢←{0::⍵⋄⍎⍕∘⍎⍣(≢a)⊢⍵}¨a⋄a}⍣≡a ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=e9Q31TlSPSUtr1gdAA&c=NY4xCsJAEEV7D@LskhWTNsewjREGLCwFUwRCKiWY6AZBgpYam8VWUtrEm8xJnN1oN7x5/88gFScBCVDdzAAjKluMQfZGwOrPAgdAgaDyRlVBVSshWqj5MhaR97nEwywzXwX5EFJjBazxPEI@kMHGcZEq8Gwd72A9IJGywFdAkW6o2tLxTbqTCiY/0TLd5b2h4owsPUm/7JujZEraCGuULWf5x4SrWO9NhhbzYT8MOUyHHena9u@vbngI2@DaXTWygTlzKu/4BQ&f=AwA&i=S@NSNyzJUOdK41I3KTg8vQDMMizQLjaCsHSMdIwztEtMdEx1zMAixgUFxcUQpmFxgZE6AA&r=tio&l=apl-dyalog&m=tradfn&n=f) A tradfn submission which takes a string from STDIN. ]
[Question] [ Given a positive integer input `n` seconds, output the time in human readable format. The time will be considered from 00:00:00, 1st January, 1 A.D. Leap years must be taken into account. Assume that the gregorian calendar was followed since the beginning. (Gregorian Calendar: Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100, but these centurial years are leap years if they are exactly divisible by 400. For example, the years 1700, 1800, and 1900 were not leap years, but the years 1600 and 2000 were) Output must be a string of the format: ``` x Millennia/Millennium, x Centuries/Century, x Decades/Decade, x Years/Year, x Months/Month, x Days/Day, x Hours/Hour, x Minutes/Minute and x Seconds/Second ``` The 0 values must not be shown. Program must handle at least up to 999 Millennia(inclusive). Plural/Singular must be kept in mind. (For millennium, both millennia and millenniums are valid) `,`,`and` and spaces must also be kept in mind. Case may be anything. ### Examples: ``` 1:1 second 2:2 seconds 60:1 minute 62:1 minute and 2 seconds 3600:1 hour 3661:1 hour, 1 minute and 1 second 31536001:1 year and 1 second 317310301:1 decade, 20 days, 13 hours, 45 minutes and 1 second 3499454714:1 century, 1 decade, 10 months, 22 days, 22 hours, 45 minutes and 14 seconds 73019321114:2 millennia, 3 centuries, 1 decade, 3 years, 10 months, 22 days, 45 minutes and 14 seconds ``` Reference: [date-difference to duration converter](https://www.calculatorsoup.com/calculators/time/time-date-difference-calculator.php) This is **code-golf** so shortest code wins [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~273 245 233~~ 230 bytes *-28 bytes thanks to nwellnhof!* ``` {S/rys/ries/}o{S:th(*)/\,/ and/}o{join ', ',map {$_~'s'x(.[0]>1)},grep *[0],(|[R,](.[0].polymod(10 xx 3)),|.skip Z <millennium century decade year month day hour minute second>)}o{~DateTime.new($_-62135596800)~~m:g/\d+/Z-(^6 X<3)} ``` [Try it online!](https://tio.run/##dVLbToNAEH3nK@bBCKsIewEqqH3yC9QHY62GlK1dhYWwNJbU9tfrgFgv0YSHMzsz58ycoZJ1Hu2KFg7ncAG79bVft8avlTT@plxfJ83COSL@vetDqrPu6blUGmwXvyKtYH3wuLWNvXK8CZ2OGdm4T7Ws4Agj13mbXLnTPuNVZd4WZeYwCqsVCELcN8@8qAru4LxQeS61VssCZlI3y7qFTM7STEIr0xqKUjcLyNIWFuUSQ6WXjQQjZ6XOxgQn2l6mjbxRhfS0fHUOHk8izkQYxtEppWS7LZIn/z479u9OnIcIbs8F2ezmZQ250tKMx56pctU4dmITWFsABoXm/dDkbAi9CZueWZsdS9iga/GED9BYEcX3j7GsiO9xZxh8VYmIdnXdDogjNmAXftTvBQQLu46urHfhV3IkGBV99sMqFzjtPDLIJ3piREE4UJtf7UEcB2EwYgH2D5Z3c3xS4ZF605GC84EVwT@swX7FEU4UC84YEnP4Ois2iUEH/6vvSqJfzvwt@b8QmsNDEYeUBnjjJI7j72rv "Perl 6 – Try It Online") ~~I think there might be a trick or two I can use with `EVAL` to make this shorter. This solution takes into account leap seconds, so the last test case is a bit off.~~ Both no longer applicable. ### (Old) Explanation: ``` { } # First code block DateTime.new($_-62135596800) # Initialise a date time object with input amount of seconds { ... }o # Pass value to the next code block fmt(.year-1: "%04d").comb Z # Zip each digit of the year with <millennium century decade year> # The appropriate word <month day hour minute second>.map:{ ... } # For each of these words ".$^a".EVAL # EVAL the method on the DateTime -(2>$++) # -1 if month or day ,$a # Followed by the word itself grep +*[0], # From these, filter out the ones with value 0 map {$_~'s'x(.[0]>1)}, # Add plurals if greater than 1 join ', ', # Join with commas { ... }o # Pass string to next code block S:th(*) # Substitute the last instance of /\,/ # A comma / and/ # With ' and' { ... }o # Pass to next code block S/rys/ries/ # Fix plural of century ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~304~~ 297 bytes ``` lambda s:' and '.join(', '.join([`n`+' '+d+'s'*(n>1)for n,d in zip([int(str(datetime(1,1,1)+timedelta(0,s))[i:i-~(i>4)])-(2<i<9)for i in[0,1,2,3,5,8,11,14,17]],'millennium century decade year month day hour minute second'.split())if n]).replace('rys','ries').rsplit(', ', 1)) from datetime import* ``` [Try it online!](https://tio.run/##dVLLbsIwELz3K1bqwXYxKLYDFET7IxSpLnbEVokT2eaQHvrr1HlQqCjKZTPamdnZddPGQ@3kqXh5O5W6@jAawpqAdgbI7LNGRwk/V9t39z4hQCZmQgJ5ou5VsKL24LgBdPCFDd2iizRET42ONmJlqeDpY5OuNraMmmY8MLbFNU6/Kb7mbMemVG5ws@q1MClts8SRXPE5f@Yi0XMulrsdJxWWpXUOjxXsrYtH34Kxe20stFZ7qGoXD2B0C4f6mH7RHaOFYPe1M2QWmhIjZQwLcDs287Yp9d5S4ttAOPFoA0no0NVl5iAYeyh8XcE5DGDV1D4@nRqfckJBBYNHEKPFwxmVHSpHNPzCi2zoHua6wPIa7jd/y1WLbGR30a7ghbjA/K/KzVxKzDudkdGv7E7fUolMnRuHFXOQWbfbkFxUb5eqfD4ahjtK@WqVz/OlyAep8Wr8SlVkw92SmpSjQSruGOQ3m1mmOVdKCjF4SLg8ksRXo2W67rWp6tOH/93vep5@AA "Python 2 – Try It Online") Centuries are annoying... [Answer] # Wolfram Language ~~255~~ 251 bytes If an Oxford comma is acceptable, this works: ``` Row[#," "]&/@(Cases[Partition[StringSplit@ToString@UnitConvert[#~Quantity~"Seconds",MixedUnit@{"Millenium","Century", "Decades","Years","Months","Weeks","Days","Hours","Minutes","Seconds"}],2],Except@{"0",_}]/.{a__,{b__}}:> {a,{"and",b}})& ``` `UnitConvert` is used to convert the number of seconds into mixed unit representation. `Cases` displays only those measures in which the magnitude is not zero. The remaining functions, `Row`, `Partition`, `ToString` and `StringSplit` merely format the output as required. `/.{a__,{b_, c_}}:> {a,{"and",b, c}` inserts "and" before the final measure in those answers containing more than one unit of measure. [Answer] # [C (gcc)](https://gcc.gnu.org/) / glibc / Linux / 64 bits, 337 bytes ``` int*gmtime();f(long s){s-=62135596800;int*t=gmtime(&s),y=t[5]+1899,i=10,j=0,c=0,v[]={1,*t,t[1],t[2],t[3]-1,t[4],y%i,y/i%i,y/100%i,y/1e3},l[]={0,"second","minute","hour","day","month","year","decade","centur","millenium"};for(;i--;)v[i]&&(j&&printf("%s%d %s%s%s",c++?i?", ":" and ":"",v[j],l[j],j-8?"":v[j]<2?"y":"ie","s"+(v[j]<2)),j=i);} ``` [Try it online!](https://tio.run/##NVBbjqMwEPyGU1geBeFgdmxeCUPYHITlA4GTdARmFJyR2IizZ9skK8tV3eWy2q42PLft8wnabM@DgUH5rDj5/ajPZGKPKSyzSMZpmmd7IQrrMuXb502Mz6Wp0jqQ@zznUErBr6XgLe6fqi4fkm8NN5WsESILcR1KpKTm8wb4/AkrSiFerOKF9/ai4HRS7ag7yukA@m4UFpfxfkPqmtmqozYX5Fk1q6japrOmVmmz2gboe6XhPtClOI03v4AwLNhPBbXn@VfP@77hZ04@3UybjiDgorwNgiMcKSf0i5JGd5Yp/uVa47sQruH@SOmXFQ7Rkc54DHbqRAP/JTKGEQArlucH6La/d4ocJtPB@Ovy28WJZGhA@4w8XGfN2FQ1KW3nSI4QWcjEimsdZ0K8OFsNsUyt9K53sRTxu0nyPEmTnUxst0M1jyMpZeI6S@E6GAHx7XwoRUHgMMFfNZ58wz7f1dYw1INgfZqDJ5gUw4vO/6D@aGr7xV2e/wA "C (gcc) – Try It Online") ### Explanation ``` int*gmtime(); // Declare gmtime f(long s){ // Function taking seconds as long s-=62135596800; // Subtract constant for 0001-01-01 int *t=gmtime(&s), // Break down time y=t[5]+1899, // Years since 1 AD i=10, j=0, c=0, v[]={ // Values 1, // Sentinel *t, // Seconds t[1], // Minutes t[2], // Hours t[3]-1, // Month days t[4], // Months y%i, // Years y/i%i, // Decades y/100%i, // Centuries y/1e3 // Milleniums }, // Labels l[]={0,"second","minute","hour","day","month","year","decade","centur","millenium"}; for(;i--;) // Loop from i=9 to 0 v[i]&&( // If current value not 0 (or sentinel reached) j&&printf("%s%d %s%s%s", // Print if previous index not 0 c++?i?", ":" and ":"", // Separator v[j], // Value l[j], // Label j-8?"":v[j]<2?"y":"ie", // Handle century/centuries "s"+(v[j]<2)), // Plural j=i // Remember index ); } ``` [Answer] ## JavaScript (ES6), 384 bytes ``` f= (n,r=[],d=new Date(n%31556952e4*1e3-621355968e5),y=d.getUTCFullYear()+(n/31556952e4|0)*1e4-1,g=(u,n=d[`getUTC${u}s`](),p=`s`,s=``)=>(n|=0)&&r.push(n+` `+u+(n>1?p:s)))=>(g(`Millenni`,y/1000,`a`,`um`),g(`Centur`,y/100%10,`ies`,`y`),g(`Decade`,y/10%10),g(`Year`,y%10),g(`Month`,d.getUTCMonth()),g(`Day`,d.getUTCDate()-1),g`Hour`,g`Minute`,g`Second`,g=r.pop(),r[0]?r.join`, `+` and `+g:g) ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o> ``` ]
[Question] [ Your challenge is to implement a cyclic Program Sequence Generator (PSG) in a language of your choice. Given a language, *L*, a **PSG in *L*** is **a program in *L* that outputs a PSG in *L***. Some properties of a PSG are: * Repeated execution of a PSG in *L* generates a sequence of programs in *L*. * A PSG is said to be cyclic if the sequence it generates is cyclic. * The period of a cyclic PSG, *P*, is written *T*(*P*) and is the period of the cycle in the sequence it generates. The period of a non-cyclic PSG is written the same way and is infinite. A trivial example of a PSG is a quine; any quine is a cyclic PSG with period 1. To make this challenge interesting, **the period of your PSG must be at least 5**. Scoring is a bit different than typical code golf. Informally, **your score is the sum of the length of all programs in one cycle of the sequence generated by your PSG divided by the period of your PSG**. Formally: let *P* be your PSG, *pₙ* be the *n*th term in your PSG's sequence, and *l*(*pₙ*) be the length in bytes of *pₙ*. Then your score is: [![score formula](https://i.stack.imgur.com/GdPIF.gif)](https://i.stack.imgur.com/GdPIF.gif) For a non-cyclic PSG, since the limit of *l*(*pₙ*) as *n* goes to infinity is infinity, the score of any non-cyclic PSGs diverges to infinity. **The PSG with the lowest score wins** [Answer] ## JavaScript (ES6), score ~~50~~ ~~49~~ ~~48~~ ~~47~~ 37 *Saved 10 points thanks to @alephalpha* ``` (f=x=>alert(`(f=${f})(${++x%5})`))(0) ``` Period is 5, each program is 37 bytes long. The `0` is changed to `1`, `2`, `3`, `4`, then back to `0`. [Answer] # JavaScript (ES6), score ~~77~~ ~~74~~ 66 The period of this PSG is 5. Each iteration of the sequence removes one asterisk in the block comment until it reaches 2, then goes back to 6. ``` f=_=>/**/`f=${f}`.replace('**/','*/').replace('/*\/','/******/') ``` Let's look at some partial sums to see what the limit approaches. ``` m 1 2 3 4 5 score 64 66 66.33 66.25 66 ``` **Edit:** thanks to @ETHproductions for pointing out that I should put the comment first. Not only is the code much shorter, it appears neater! [Answer] # [Python 2](https://docs.python.org/2/), score ~~119~~ 89 ``` s='s=%r;c=0;s=s[:7]+`c+1-c/4*5`+s[8:];print s%%s';c=0;s=s[:7]+`c+1-c/4*5`+s[8:];print s%s ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v9hWvdhWtcg62dbAuti2ONrKPFY7IVnbUDdZ30TLNEG7ONrCKta6oCgzr0ShWFW1WJ1IlcX//wMA "Python 2 – Try It Online") The period of my PSG is 5. Each program is 89 bytes in length. Therefore, my score is 89. *-30 bytes thanks to ovs.* [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), score 38 ``` (f=(x)->print1("(f="f")("x++%5")"))(0) ``` Period is 5. [Try it online!](https://tio.run/##K0gsytRNL/j/XyPNVqNCU9euoCgzr8RQQwnIV0pT0tRQqtDWVjVV0lTS1NQw0Pz/HwA "Pari/GP – Try It Online") ]
[Question] [ Your task is to print the titles of the questions with the five highest scores (upvotes minus downvotes) here on CodeGolf.SE, while skipping over any closed, locked and on-hold questions. Currently these are: ``` Produce the number 2014 without any numbers in your source code Showcase your language one vote at a time American Gothic in the palette of Mona Lisa: Rearrange the pixels Images with all colors Build a Compiler Bomb ``` Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the smallest number of bytes wins. [Answer] # JavaScript + JQuery, 178 bytes Quite a simple approach that makes the StackExchange API do all the work. ``` $.ajax('//api.stackexchange.com/search/advanced?sort=votes&closed=False&wiki=False&notice=False&pagesize=5&site=codegolf').pipe(x=>x.items.map(x=>document.write(x.title+'<br>'))) ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> ``` ``` a=x=>x.items.map(x=>document.write(x.title+'<br>')) document.write('<script src="//api.stackexchange.com/search/advanced?sort=votes&closed=False&wiki=False&pagesize=5&site=codegolf&callback=a"><\/script>') ``` ``` <!-- No dependencies, Pure JS. 204 bytes. --> ``` <http://api.stackexchange.com/search/advanced?sort=votes&closed=False&wiki=False&pagesize=5&site=codegolf> is the StackExchange API page that gives a JSON. This JSON data is the questions on codegolf.stackexchange.com sorted by votes where they haven't been closed and are not a wiki page and don't have a closed notice. This is called with JQuery's `$.ajax`, which works JSON-P. It adds a `&callback=functionName` to the url so the API returns some javascript for a function that calls the data, so it can be used with the function that logs it. ``` <!-- For fun, do this for any site --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>StackExchange&nbsp;Site:&nbsp;<input value="codegolf"> <button onclick="$.ajax({success:x=>{try{document.getElementById('pre').innerHTML=x.items.map(x=>x.title).join('\n')+'\n\nQueries left: ' + x.quota_remaining}catch(e){try{document.getElementById('pre').textContent='Queries left: ' + (x.quota_remaining || 'Error')}catch(e){document.getElementById('pre').textContent='Error'}}},url:'//api.stackexchange.com/search/advanced?sort='+document.getElementById('s').value+'&closed=False&wiki=False&notice=False&pagesize=5&site=' + this.previousElementSibling.value})">Go</button> Sort&nbsp;by:&nbsp;<select id='s'><option value="activity">Active</option><option value="votes" selected="selected">Score</option><option value="creation">New</option><!--option value="hot">Hot</option><option value="week">Week</option><option value="month">Month</option--></select><pre id="pre"></pre> ``` Some caveats while answering this question: 1. StackExchange API *always* trys to returns gzipped data. In JS, the browser un-gzips for you. 2. The API only seems to be able to return the top 100 at maximum, so if you were to filter out the closed questions programatically, you must assume that less than 96 of the top 100 questions are closed, which you can't so you have to do everything in the APIs query. 3. The things in the API are HTML encoded, so you must also decode those. In JS, I let the browser decode it, but in something like Python, you must employ an external library, or else hard-code the dozens of entities. That said, here is my Python solution that has to jump all of those hoops: # Python 3, 259 bytes ``` import urllib.request as r,gzip,html,json for i in json.loads(gzip.decompress(r.urlopen('http://api.stackexchange.com/search/advanced?sort=votes&closed=False&wiki=False&notice=False&pagesize=5&site=codegolf').read()))['items']:print(html.unescape(i['title'])) ``` [Answer] # Bash + curl + gunzip + recode + [jq](https://stedolan.github.io/jq/), 165 bytes (Newline for clarity) ``` curl "api.stackexchange.com/search/advanced?sort=votes&closed=False&wiki=False&notice=False&pagesize=5&site=codegolf" |gunzip|jq -r ".items[].title"|recode html:ascii ``` Or if you don't want any output on `stderr` for 4 more bytes : ``` curl -s "api.stackexchange.com/search/advanced?sort=votes&closed=False&wiki=False&notice=False&pagesize=5&site=codegolf" |gunzip|jq -r ".items[].title"|recode html..ascii ``` I thought a `bash` solution using @Artyer's url would be shorter, turns out it's not that much. Problems that make it longer : * The stackexchange API responds with compressed data. Using `curl`'s `--compressed` flag, `gzip -d` or `gunzip` solve that, `gunzip` being the shortest * We need to translate HTML entities * `jq` outputs JSON data, where strings are enclosed in quotes. Using `-r` makes it output raw data. ]
[Question] [ ## Introduction Say you have a population of people. This population is made up of 100 Alices and 25 Bobs. So, 80% of the population are Alices and 20% are Bobs. We want to change the proportional makeup of the population to be 62% Alices and 38% Bobs. ## Rules 1. You can only add to the population. You cannot take any away from the starting population. 2. You can only add in multiples of the original subpopulation size. So following the above example, you can only add batches of 100 Alices to the group; likewise, you can only add batches of 25 Bobs to the group. 3. You have a pool of unlimited Alices and Bobs that are not in the population yet. 4. The algorithm must be able to handle N different name groups (e.g. N=4: Alice, Bob, Carol, David). ### Pseudocode framework ``` # 100 Alices, 25 Bobs, 35 Carols, 60 Davids starting_population = (100, 25, 35, 60) # Goal percentages, must sum to 100 reproportion_goal = (10, 20, 30, 40) # Reproportion the population to meet the goal percentages, following the rules new_population = reproportion_population(starting_population, reproportion_goal) ``` ## Winner Create an algorithm to re-proportion the population following the rules with an arbitrary starting\_population and reproportion\_goal. The winning algorithm will solve the above-quoted problem in the fastest time on a single-core single-CPU i686 system with fixed clock speed. The algorithm must also solve other reasonable cases through the same code-path. That is, do not special-case for the example data. I will use many thousands of iterations to test the timing of the approach. VM/runtime startup times will not be counted. The algorithm will be warmed up before timing starts. You can specify the specific version of framework you would like me to run your code under, and if I can reasonably set it up, I will. ## Introduction Say you have a population of people. This population is made up of 100 Alices and 25 Bobs. So, 80% of the population are Alices and 20% are Bobs. We want to change the proportional makeup of the population to be 62% Alices and 38% Bobs. ## Rules 1. You can only add to the population. You cannot take any away from the starting population. 2. You can only add in multiples of the original subpopulation size. So following the above example, you can only add batches of 100 Alices to the group; likewise, you can only add batches of 25 Bobs to the group. 3. You have a pool of unlimited Alices and Bobs that are not in the population yet. 4. The algorithm must be able to handle N different name groups (e.g. N=4: Alice, Bob, Carol, David). ### Pseudocode framework ``` # 100 Alices, 25 Bobs, 35 Carols, 60 Davids starting_population = (100, 25, 35, 60) # Goal percentages, must sum to 100 reproportion_goal = (10, 20, 30, 40) # Reproportion the population to meet the goal percentages, following the rules new_population = reproportion_population(starting_population, reproportion_goal) ``` ## Winner Create an algorithm to re-proportion the population following the rules with an arbitrary starting\_population and reproportion\_goal. The winning algorithm will solve the above-quoted problem in the fastest time on a single-core single-CPU i686 system with fixed clock speed. The algorithm must also solve other reasonable cases through the same code-path. That is, do not special-case for the example data. I will use many thousands of iterations to test the timing of the approach. VM/runtime startup times will not be counted. The algorithm will be warmed up before timing starts. You can specify the specific version of framework you would like me to run your code under, and if I can reasonably set it up, I will. ### Dates (deadline and winner) Deadline for submissions is before March 14, 2016. I will post benchmarks by March 20. Feel free to answer after these dates, but I can't commit to re-benchmarking submissions after March 14. [Answer] # C ``` void reproportion( const unsigned int n, const unsigned int *const starting_population, const unsigned int *const reproportion_goal, unsigned int *const new_population) { unsigned int unit = 1U; for(unsigned int i = 0U; i != n; ++i) { unit *= starting_population[i]; } for(unsigned int i = 0U; i != n; ++i) { new_population[i] = reproportion_goal[i] * unit; } } ``` This assumes that the original subpopulation sizes are greater than zero. `starting_population = { 0, 1, 2 }` and `reproportion_goal = { 0, 50, 50 }` would give the incorrect result of `new_population = { 0, 0, 0 }`. If the original subpopulation size can be zero, `unit *= starting_population[i];` should be preceded by `if(starting_population[i] != 0U)`. Call this function from within your program like so: ``` #include <stdio.h> int main(void) { unsigned int starting_population[] = { 1, 2, 31, 4 }; unsigned int reproportion_goal[] = { 25, 25, 40, 10 }; unsigned int new_population[4]; reproportion(4, starting_population, reproportion_goal, new_population); for(int i = 0; i < 4; ++i) { printf("%d ", new_population[i]); } } ``` [Answer] # Javascript ES6 I'm not really sure how you time these things but here's what I have ``` (p,g)=>g.map(_=>_*m,m=p.reduce((l,o)=>o*l)) ``` the instinct to use ``` (p,g)=>g.map(_=>_*p.reduce((l,o)=>o*l)) ``` to save a few bytes is overwhelming, but I suspect js isn't smart enough to reuse the p.reduce for each iteration [I know this gives back larger than necessary solutions, but I don't think that a minimal solution was a requirement :) ] Usage ``` f=(p,g)=>g.map(_=>_*m,m=p.reduce((l,o)=>o*l)) f([100, 25],[62, 38]) //outputs [155000, 95000] //sum of those is 250000 //155000/250000 = 0.62 f([100, 25, 35, 60] ,[10, 20, 30, 40]) //outputs [52500000, 105000000, 157500000, 210000000] //sum of those is 525000000 ``` [Answer] # Matlab This function is very fast, but doesn't return the minimal solution ``` function s=reproportion_population(a,T) s=prod(lcm(a,T)).*T; ``` This version returns the minimal solution. ``` function s=reproportion_population(a,T) L=lcm(a,T); g=prod(L)./a; r=g(1); rt=T(1); for i=1:numel(g)-1 r=gcd(r,g(i+1)); rt=gcd(rt,T(i+1)); end s=g./r.*a.*T/rt; ``` Usage is, for both versions, `new_population = reproportion_population(starting_population, reproportion_goal)`, for example, ``` reproportion_population([100 25],[62 38]) ``` which returns `[182590000 111910000]` (first version) or `[3100 1900]` (second version), or ``` reproportion_population([100 25 35 60],[10 20 30 40]) ``` which returns `[2520000000 5040000000 7560000000 10080000000]` (first version) `[2100 4200 6300 8400]` (second version). If you don't have Matlab, it should work as-is in Octave, although you need to need to add `endfunction` at the end of the file (I think---I don't have Octave). [Answer] ## Python Assuming that any valid solution is acceptable, and not the minimal solution... ``` def reproportion_pop(start_pop, pop_goal): import operator reduced = reduce(operator.mul, start_pop) new_pop = [] for x in range(len(start_pop)): new_pop.append(reduced*pop_goal[x]) return new_pop ``` This can be put in a .py file, pasted into an interpreter, or run [Here](https://repl.it/Bsue/0), whichever you prefer. Function call is in the form of `reproportion_pop(list_of_start_pop, list_of_pop_goal)` Examples: ``` > reproportion_pop([100,25],[62,38]) [155000, 95000] > reproportion_pop([100,25,35,60],[10,20,30,40]) [52500000, 105000000, 157500000, 210000000] ``` [Answer] # Rust To change the cases, simply change the numbers in the vectors (if you want commandline arguments instead, I can do that). On my computer I ran ``` time for i in {1..1000}; do target/release/population > /dev/null; done; ``` and got the output ``` real 0m4.202s user 0m0.748s sys 0m3.613s ``` I'm not sure how much actual optimization there is to be done, and how much will even show because its so fast. ``` fn reproportion_population( starting_population: &Vec<usize>, reproportion_goal: &Vec<usize>, ) -> Vec<usize> { let mut prod: usize = 1; let mut size: usize = 0; for i in starting_population { size += 1; prod *= *i; } let mut answers: Vec<usize> = vec![0; size]; for i in 0..size { answers[i] = reproportion_goal[i] * prod; } answers } fn main() { let starting_population: Vec<usize> = vec![100, 25, 35, 60, 100]; let reproportion_goal: Vec<usize> = vec![10, 20, 30, 30, 10]; let answers: Vec<usize> = reproportion_population(&starting_population, &reproportion_goal); /* // the following prints out POPULATION: PERCENT with a newline for each pop. // the percent is given as a decimal. let mut total: usize = 0; for i in 0..reproportion_goal.len() { total += answers[i]; } for i in 0..reproportion_goal.len() { println!("{}: {}", answers[i], (answers[i] as f64)/(total as f64)); } */ } ``` To compile (after rust+cargo are installed) run `cargo build --release`. To run `./target/release/<binary_name>`. ]
[Question] [ Binary search is an algorithm that looks for an element in a sorted data-structure by constantly dividing the search space in half. ### [Rosetta Code](http://rosettacode.org/wiki/Binary_search) > > A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. > > > ### [Wikipedia](https://en.wikipedia.org/wiki/Binary_search_algorithm) > > In computer science, a binary search or half-interval search algorithm finds the position of a target value within a sorted array. The binary search algorithm can be classified as a dichotomic divide-and-conquer search algorithm and executes in logarithmic time. > > > --- Smallest # of bytes wins ### Clarifications * Example of calling the function/lambda/macro should be included, but don't count those chars! * Output should be `> -1` if found, and `<=-1` otherwise * `import binary_search` (20 bytes) DOES NOT count! * Implementation should run in O(log n), as algorithm dictates Also see the [code-golf StackExchange FAQ](https://codegolf.stackexchange.com/tags/code-golf/info). ### Example ``` > binary_search([1,3,5,6,7,8,8,10], 5); 4 > binary_search([1,3,5,6,7,8,8,10], 543); -1 ``` [Answer] ### JavaScript (94 bytes) ``` (a,e)=>{u=a.length,m=0;for(l=0;l<=u;)e>a[m=(l+u)>>1]?l=m+1:u=e==a[m]?-2:m-1;return u==-2?m:-1} ``` Expanded out a little so you can see what's going on: ``` function binary_search(array, elem) { let u = array.length, m; for (let l = 0; l <= u;) if (elem > array[(m = (l + u) >> 1)]) l = m + 1; else u = (elem == array[m]) ? -2 : m - 1; return (u == -2) ? m : -1; } ``` Example usage: ``` > a = [1,2,3,4,5,6,7,8,9,10] > binary_search(a, 5) 4 > binary_search(a, 15) -1 ``` [Answer] # C – 119 ~~115~~ bytes Iterative solution at 119 bytes: ``` f(a,x,l,h)int*a,x,l,h;{while(l<h){int m=(h+l)/2;if(a[m]>x)h=m;else if(a[m]<x)l=m+1;else return m;}return a[l]==x?l:-1;} ``` Recursive solution at 115 bytes: ``` f(a,x,l,h)int*a,x,l,h;{if(l==h)return a[l]==x?l:-1;int m=(h+l)/2;return a[m]>x?f(a,x,l,m):(a[m]<x?f(a,x,m+1,h):m);} ``` You can precede with `int` to prevent compiler warnings or if you're using `gcc` compile with `-Wno-implicit-int`. Sample: ``` #include <stdio.h> f(a,x,l,h)int*a,x,l,h;{while(l<h){int m=(h+l)/2;if(a[m]>x)h=m;else if(a[m]<x)l=m+1;else return m;}return a[l]==x?l:-1;} int main() { int x, a[] = {-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10}; for (x = -15; x <= 15; x++) printf("%d\t%d\n", x, f(a, x, 0, 10)); return 0; } ``` [Answer] # Python 112 bytes ``` def b(A,k): l,h=0,len(A) while l<h: m=(l+h)/2 if A[m]>k:h=m elif A[m]<k:l=m+1 else:return m return -1 ``` **Example:** `print b([1,3,5,6,7,8,8,10], 5)` `2` [Answer] ## [AutoIt](http://autoitscript.com/forum), 92 bytes This function binary searches an array in-memory and replaces it with an integer holding the index (or -1 if not found). Array needs to be sorted to work with the binary search: ``` #include <Array.au3> Func b(ByRef $a,$n) _ArraySort($a) $a=_ArrayBinarySearch($a,$n) EndFunc ``` Testing: ``` Local $a = [1,2,3,4,5,6,7,8,9,10] b($a,5) ConsoleWrite($a & @LF) ``` Output: `4` [Answer] # C++14, ~~87~~ 85 bytes ``` #include<algorithm> [](int i,auto v){return std::binary_search(begin(v),end(v),i)-1;} ``` Assumes a sorted data structure which has iterators as input. **Example:** ``` #include<algorithm> #include<iostream> auto f = [](int i, auto v){ return std::binary_search(begin(v), end(v), i) - 1; }; int main() { std::vector<int> v = { 1, 2, 3, 4, 5 }; std::cout << f(3, v); } ``` [Answer] # Prolog, 146 bytes I made the assumption that a program returning easy to understand truthy/falsy values is OK, as adding code just to return -1/1 instead of true/false in a code-golf challenge seems counter-productive. So the program returns **true** if the value is present in the list, otherwise **false**. ``` s(F,S,L):-append(F,S,L),length(F,G),length(S,T),T>=G,T-G<2. c(L,X):-s(_,[X|_],L). c(L,X):-s(_,[M|T],L),X>M,c(T,X). c(L,X):-s(F,[_|_],L),c(F,X). ``` **How it works** ``` s(F,S,L):-append(F,S,L),length(F,G),length(S,T),T>=G,T-G<2. ``` Helper function that takes the list **L** and splits it in the middle into the lists **F** and **S** where **F** is the lower part of the list. If **L** has an odd number of elements, **S** is one element larger than **F**. ``` c(L,X):-s(_,[X|_],L). ``` Succeeds if the sought after element **X** is in the middle of list **L**. ``` c(L,X):-s(_,[M|T],L),X>M,c(T,X). ``` Checks for **X** in the higher part of the list if **X** is bigger than the middle element of list **L**. ``` c(L,X):-s(F,[_|_],L),c(F,X). ``` Checks for **X** in the lower part of the list if **X** is smaller than the middle element of list **L**. As the previous predicates are checked first we can save a few bytes by not doing a comparison here. **Examples:** ``` > c([1,3,5,6,7,8,8,10],5). true > c([1,3,5,6,7,8,8,10],543). false ``` [Answer] ## Common Lisp, ~~142~~ 143 bytes *Having seen some of the comments about recursive vs iterative, I'd point out that in any implementation with tail-call optimization, the second (original) solution* is *iterative.* ### pure iterative, with `do` loop (143): ``` (lambda(a e)(do((l 0)(h(length a)))((<= h l)-1)(let*((m(ash(+ h l)-1))(x(aref a m)))(if(= x e)(return m)(if(< e x)(setf h m)(setf l(1+ m))))))) ``` ``` (lambda (a e) (do ((l 0) (h (length a))) ((<= h l) -1) (let* ((m (ash (+ h l) -1)) (x (aref a m))) (if (= x e) (return m) (if (< e x) (setf h m) (setf l (1+ m))))))) ``` ### recursive (142) ``` (defun b(a e &optional(l 0)(h(length a)))(if(<= h l)-1(let*((m(ash(+ h l)-1))(x(aref a m)))(if(= x e)m(if(< e x)(b a e l m)(b a e(1+ m)h)))))) ``` ``` (defun b (a e &optional (l 0) (h (length a))) (if (<= h l) -1 (let* ((m (ash (+ h l) -1)) (x (aref a m))) (if (= x e) m (if (< e x) (b a e l m) (b a e (1+ m) h)))))) ``` ``` CL-USER> (loop with array = #(1 3 5 6 7 8 8 10) for element in '(1 7 5 3 2 4 6) collect (b array element)) (0 4 2 1 -1 -1 3) ``` ]
[Question] [ # Exchange the Stacks! Write a program that can exchange any character from two stacks. In this challenge, a stack is a tower of characters. An example stack is below: ``` 1 a 4 d * c 3 ``` There are two stacks involved in the challenge and both are inputted when the program runs. The program will also be given an argument of which position in Stack 1 to exchange with stack 2. So if the stacks look like this: **STACK 1** ``` a $ 5 D 0 ) _ ``` **STACK 2** ``` ^ p 0 - @ L m ``` and the program is told to exchange position 2, the resulting stacks will look like this: **STACK 1** ``` a p 5 D 0 ) _ ``` **STACK 2** ``` ^ $ 0 - @ L m ``` and the program should output them. The program should run with any stack size, not just 7, and should work with all standard characters (characters that are easily types at the keyboard, without using fancy stuff like Alt codes). Space is not required to work. Your program should accept three inputs: The contents of stack 1, the contents of stack 2 and the character to swap. Inside the program, I don't mind what form the stacks take, but when they are outputted, it must be in the form of each character separated by a newline. Input can be in any form. ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") and so the least bytes wins! ## Leaderboard Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you 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 ``` ``` var QUESTION_ID=57831;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] # Python 3, 107 bytes This account's first golf ;) ``` x,y,p=input(),input(),int(input())-1 print('\n'.join(x[:p]+y[p]+x[p+1:])+'\n'+'\n'.join(y[:p]+x[p]+y[p+1:])) ``` Takes input as three lines, the first being the first stack, the second line, the second stack and the third, the position. Outputs the stack as separated by newlines. [Answer] # CJam, ~~16~~ 17 bytes Didn't notice the position was 1-based. Fixed now, at the cost of 1 byte. ``` ll+_,2/li(_@+e\N* ``` Takes the input on three lines: ``` Stack 1 Stack 2 Position (1-based) ``` Also supports spaces in the stacks. Outputs the swapped stacks, one character per line. [Try it online](http://cjam.aditsu.net/#code=ll%2B_%2C2%2Fli(_%40%2Be%5CN*&input=a%245D0)_%0A%5Ep0-%40Lm%0A2). # Explanation ``` ll+ e# Concatenate first two lines _,2/ e# Push half length (size of one stack) li( e# Read third line as integer, subtract 1 _@+ e# Sum a copy of the position with the stack size e\ e# Swap (position) <-> (position + stack size) N* e# Join with newline ``` [Answer] # AutoIt, ~~135~~ ~~132~~ 129 ``` $l=$CmdLine $d=StringLen($l[1]) $b=$l[2] $c=$d/2+$b For $n=1 To $d ConsoleWrite(StringMid($l[1],$n=$b?$c:$n=$c?$b:$n,1)&@LF) Next ``` Run like this: ``` compiled.exe abccba 1 ``` where `abccba` are both stacks concatenated and `1` is the switch position (1-based). Supports spaces and all unicode characters. Output: ``` c b c a b a ``` [Answer] # C#, ~~238~~ ~~222~~ 213 bytes ``` namespace System.Linq{class A{static void Main(string[]a){int n=int.Parse(a[2])-1;Console.Write(string.Join("\n",a[0].Select((x,i)=>i==n?a[1][n]:x))+"\n\n"+string.Join("\n",a[1].Select((x,i)=>i==n?a[0][n]:x)));}}} ``` To execute: ``` compiled.exe <stack 1> <stack 2> <index to exchange> ``` The stacks have to be inputted without separator between the stack items, e.g. `compiled.exe abcdef 123456 2`. Thanks to Andrea Biondo for saving 25 bytes! Ungolfed code: ``` using System; using System.Linq; namespace ExchangingStacks { class Program { static void Main(string[] args) { string stack1 = args[0]; string stack2 = args[1]; int exchangeIndex = int.Parse(args[2]) - 1; var newStack1 = stack1.Select((x, index) => index == exchangeIndex ? stack2[exchangeIndex] : x); var newStack2 = stack2.Select((x, index) => index == exchangeIndex ? stack1[exchangeIndex] : x); Console.Write(string.Join("\n", newStack1) + "\n\n" + string.Join("\n", newStack2)); } } } ``` [Answer] # PowerShell, 81 Bytes ``` param([char[]]$a,[char[]]$b,$n);$n--;$t=$b[$n];$b[$n]=$a[$n];$a[$n]=$t;$a;"`n";$b ``` Holy Dollar Signs, Batman! 16 of the 81 characters (~20%) are `$`. The input is expected to be literal-string delimited and space-separated, thanks to the very liberal input requirements. If one of the input stacks includes the `'` character, it will need to be escaped with a backtick. Example of the input from the question: ``` .\exchange-the-stacks.ps1 'a$5D0)_' '^p0-@Lm' 2 ``` Pretty simple char-array manipulation. PowerShell, by default, when "executing" an array, will print each item on its own line, so simply `$a` will output each element newline-separated, hence why this is so competitive with other non-golfing languages, as we don't need to specially format the output. ]
[Question] [ **Challenge** For any given input **Y** of length >= 1024 bytes: * sort in ascending or descending order -- your choice * generate output **Q**, where **Q** = [*sorted data*] + [*restore information*] * restore **Y** using **Q** as input **Sorting Example** ``` input: [2, 5, 119, 0, 1, 223, 0, 118, ...] output: [0, 0, 1, 2, 5, 118, 119, 223, ...] + [restore information] ``` **Restore Example** ``` input: [0, 0, 1, 2, 5, 118, 119, 223, ...] + [restore information] output: [2, 5, 119, 0, 1, 223, 0, 118, ...] ``` **Winning** The program that generates the least amount of information in order to restore to original state wins, however it must work within a reasonable amount of time on modern hardware, less than 10 minutes. **UPDATE 1** You may use any third party libraries that are open-source if you so desire. **UPDATE 2** The [restore information] size is measured in bytes, it's your choice what it contains. **UPDATE 3** In case it's not yet clear, the input **Y** is a stream of bytes, you shouldn't care what it contains, all you care is to sort the values of the bytes in the order you prefer while also generating the necessary data in order to restore to **Y** from **Q**. [Answer] ## Python The restore information is just the original list. *n* bytes of restore information for an *n* byte list. ``` def sort(Y): return (sorted(Y), Y) def restore(Q): return Q[1] ``` [Answer] # Scala + Arithmetic coding Once we sort the data, all we're left with is the frequencies of the bytes within the original. Conveniently, this is exactly what we need for efficient adaptive arithmetic coding. We use arithmetic coding on the frequencies of the remaining elements of the data. I suspect this is information theoretically optimal, for random data. I've used nayuki's arithmetic coding library. ``` import nayuki.arithcode._ import java.io.ByteArrayOutputStream import java.io.ByteArrayInputStream import java.nio.charset.StandardCharsets.UTF_8 object Unsort { def mkTable(data: Array[Byte]) = { val frequencyMap = data.groupBy(identity).mapValues(_.size) val frequencyArray = (0 to 255).map(i => frequencyMap.getOrElse(i.toByte, 0)).toArray new RemainingFrequencies(frequencyArray) } def sort(data: Array[Byte]) = { val freqTable = mkTable(data) val output = new ByteArrayOutputStream val bitOutput = new BitOutputStream(output) val encoder = new ArithmeticEncoder(bitOutput) for (b <- data) { val i = b.toInt & 0xff encoder.write(freqTable, i) freqTable.decrement(i) } encoder.finish() bitOutput.close() (data.sorted, output.toByteArray) } def unsort(dataAndMetadata: (Array[Byte], Array[Byte])) = { val (data, metadata) = dataAndMetadata val freqTable = mkTable(data) val input = new ByteArrayInputStream(metadata) val bitInput = new BitInputStream(input) val decoder = new ArithmeticDecoder(bitInput) (for (_ <- 0 until data.length) yield { val x = decoder.read(freqTable) freqTable.decrement(x) x.toByte }).toArray } def main(args: Array[String]) = { val stringData = args.reduce(_ + " " +_) val data = stringData.getBytes(UTF_8) val (sorted, metadata) = sort(data) val unsorted = unsort((sorted, metadata)) val unsortedString = new String(unsorted, UTF_8) println(s"""Received "${stringData}"""") println(s"""Sorted to ${sorted.toList} + ${metadata.toList}""") println(s"""(${sorted.length} bytes of data, ${metadata.length} bytes of metadata)""") println(s"""Unsorted to "$unsortedString"""") } } class RemainingFrequencies(private val frequencies: Array[Int]) extends FrequencyTable { override val getSymbolLimit = 256 override def get(symbol: Int) = frequencies(symbol) override def set(symbol: Int, freq: Int) = ??? override def increment(symbol: Int) = ??? override def getTotal = frequencies.sum override def getLow(symbol: Int) = frequencies.slice(0, symbol).sum override def getHigh(symbol: Int) = frequencies.slice(0, symbol + 1).sum def decrement(symbol: Int) = frequencies(symbol) -= 1 } ``` As an example of the output, here's what happens when we run it against the first paragraph of Franz Kafka's Metamorphosis: ``` Received "One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into stiff sections. The bedding was hardly able to cover it and seemed ready to slide off any moment. His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked." Sorted to List(32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 44, 44, 44, 44, 44, 44, 45, 46, 46, 46, 46, 71, 72, 72, 79, 83, 84, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 99, 99, 99, 99, 99, 99, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 103, 103, 103, 103, 103, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 107, 107, 107, 107, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 112, 112, 112, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 117, 117, 117, 117, 117, 117, 118, 118, 118, 118, 119, 119, 119, 119, 119, 119, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 122) + List(53, -2, -48, 47, 98, -11, -73, 89, 24, -16, 122, -22, -52, -112, 110, -5, -47, -93, 33, -78, 30, 101, -75, 105, 48, -118, 86, -94, -111, 6, 99, 80, 123, 106, 114, -94, -106, -56, -14, 85, -81, -111, 4, -65, 10, -38, -56, -83, 73, 51, -80, 34, -116, 112, -125, -89, -107, 77, 69, -123, -121, -55, 104, 24, 105, 93, 60, -88, 50, -117, 21, -17, 119, 56, 51, -53, 63, 116, -48, 13, -35, 67, -3, -73, -126, 58, -117, 19, -24, -18, -18, -73, -108, -3, -100, 30, 47, -32, -52, -22, -108, 37, 110, 79, -37, -78, -2, 72, 99, -42, 30, 102, -70, -33, -52, -32, -109, -37, 104, 26, 126, 67, 80, 101, 15, 1, -101, 21, -38, -95, 32, -24, 12, -75, -92, 28, 124, -65, 39, -58, 68, -58, 70, -90, -17, -29, -12, 1, 37, 84, 91, 61, 13, -28, 73, -112, -47, 42, -12, 64, -21, -95, 67, -113, -109, 28, 67, 35, -13, 81, -109, -49, 63, -20, -98, -112, 64, -53, 51, -96, -49, -111, 28, 46, 97, 77, -115, 78, -61, 110, 105, -4, -88, 0, -127, -66, -59, -65, -4, -105, -120, 53, 49, 2, 60, -7, -83, -102, -128, -118, -77, 77, 28, -126, 58, 16, 4, 70, 28, 91, 96, -73, 29, -126, -6, 8, 112, 122, 40, 48, -45, 0, 24, -91, -5, -59, 61, 122, -96) (468 bytes of data, 239 bytes of metadata) Unsorted to "One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into stiff sections. The bedding was hardly able to cover it and seemed ready to slide off any moment. His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked." ``` It's only 468 bytes, but still an interesting test. The metadata used to unsort it is 239 bytes. When I tested it against 4096 bytes of random data (not shown), the metadata was 3967 bytes. [Answer] ## Python 2.x - Score ? I acrually have no idea how to calculate the score in this case. I use bubble sort and log the swaps along the way. Now, these swaps can then be applied in reversed order to get the original list back. Give the program a `-r` flag when restoring (ie. `file.py -r`) I have a feeling the most optimal way in the long run is to just save the indexes for each value. But that isn't fun. ``` import sys import binascii def sort(data): swaps = '' swapped = True while swapped: swapped = False for i in xrange(len(data)-1): if data[i] > data[i+1]: temp = data[i] data[i] = data[i+1] data[i+1] = temp swapped = True swaps += '1' else: swaps += '0' swaps = swaps[:-len(data)+1] swaps += '0' while len(swaps) % 8 != 0: swaps += '1' swaps = int(swaps, 2) swaps = binascii.unhexlify('%x' % swaps) return ''.join(map(chr, data)) + swaps + binascii.unhexlify('%08x' % len(swaps)) def unsort(data, swaps): swaps = bin(int(binascii.hexlify(swaps), 16))[2:] swaps = swaps[::-1] while swaps[0] != '0': swaps = swaps[1:] swaps = swaps[1:] datalen = len(data) - 2 i = datalen for s in swaps: if s == '1': temp = data[i] data[i] = data[i+1] data[i+1] = temp i -= 1 if i < 0: i = datalen return ''.join(map(chr, data)) if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == '-r': data = sys.stdin.read() size = int(binascii.hexlify(data[-4:]), 16) swaps = data[-size-4:-4] data = map(ord, data[:-size-4]) print unsort(data, swaps) else: data = map(ord, sys.stdin.read()) sys.stdout.write(sort(data)) sys.stdout.flush() ``` Example: ``` In: 94731 Out: 13479 ÷╚⌂ -r flag In: 13479 ÷╚⌂ Out: 94731 ``` [Answer] Theoretical solution: Will work, but chances for it to complete within the time limit are pretty low. Through brute-force search I try to find any random seed that, when used to shuffle of the original indexes, happens to create exactly the ordered list. Sample output: ``` Input: [185, 60, 253, 77, 64, 146, 155, 66] Sorted: [60, 64, 66, 77, 146, 155, 185, 253] 7099 ``` Now if I could just figure out how to speed this up a little... ;) ``` public class SortRestore { public static void main(String[] args) { final Random rnd = new Random(123); final int[] input = IntStream.iterate(rnd.nextInt(256), s -> rnd.nextInt(256)).limit(2048).toArray(); System.out.println("Input: " + Arrays.toString(input)); final int[] sorted = Arrays.copyOf(input, input.length); Arrays.parallelSort(sorted); System.out.print("Sorted: " + Arrays.toString(sorted) + " "); final List<Integer> indexBase = IntStream.range(0, input.length).boxed().collect(Collectors.toList()); IntStream.rangeClosed(0, Integer.MAX_VALUE).parallel() .filter(seed -> { final List<Integer> indexes = new ArrayList<>(indexBase); Collections.shuffle(indexes, new Random(seed)); for (int i = 0; i < input.length; ++i) { if (input[i] != sorted[indexes.get(i)]) { return false; } } return true; }).limit(1) .forEach(System.out::println); } } ``` [Answer] Performs selection sort and records all the swaps. Input: [15, 18, 1, 6, 2, 16, 13] Output: [1, 2, 6, 13, 15, 16, 18] [(0, 2), (1, 4), (2, 3), (3, 6), (4, 6)] Also: list == restore(\*sort(list)) ``` def swap(l, indexes): l[indexes[0]], l[indexes[1]] = l[indexes[1]], l[indexes[0]] def sort(l): restore = [] for i in range(len(l)-1): m = min(l[i+1:]) if l[i] > m: restore.append((i,l.index(m))) swap(l, restore[-1]) return l, restore def restore(l, restore): restore.reverse() for i in restore: swap(l,i) return l ``` [Answer] # J Not sure how this should be scored, but it's a simple deal with J. * `/:~` sorts the list. * `A.@/:@/:` gives the restoration information, an integer less than N! for a list of length N, which can be coded into ceil(*log*256 N!) bytes or less, using `(256#.3&u:)inv`, and decoded with `(256#.3&u:)`. * `((A.i.@#){])` takes the restoration integer on the left and the sorted array on the right. The integer is literally a permutation number—that's what the `A.` is doing, converting between permutations and permutation numbers. If you need a single program that can convert between the two, you're probably looking at something like: ``` (/:~;4 u:256#.inv A.@/:@/:) :(]{~i.@#@]A.~256#.3 u:[) ``` which sorts and gives the restore if it's used with one argument, or takes the restoration on the left and the sorted array on the right to fix it. For the record, the J equivalent of Python's trivial solution, where the restoration information is the array itself, is the simple `(;~/:~) :[`. ]
[Question] [ Let **N** be the set of nonnegative integers, i.e. {0, 1, 2, 3, ...}. Let c0(**N**) be the set of all infinite sequences in **N** that converge to 0, i.e. { (xn) ∈ **N****N** | xn → 0 as n → ∞}. c0(**N**) can be equivalently written as the set of all finite sequences of natural numbers, such that there are no trailing zeroes. The infinite sequence of all zeroes (corresponding to a finite sequence of length 0) is an element of c0(**N**). ***Your task*** is to implement a bijection in your language between **N** and c0(**N**), in as few characters as possible. This means every number in **N** corresponds to a unique item of c0(**N**), and vice versa. Do this by defining two functions: `f`, going from **N** and c0(**N**); and `g`, the inverse of `f`. *The length in bytes of these two definitions is your score.* You may use the largest internal integer and list types of your language, even if they aren't bignums or capable of handling infinite length. However, they should theoretically still be able to terminate with the right answer if the language was modified with a suitable bignum or lazy/infinite list type. Some suggestions for ways to pack are below. Note that these aren't quite solutions yet and could need some tweaking to work; they're mostly to get the blood flowing. * `f(1463616) = f(2^6 * 3^3 * 5^0 * 7^1 * 11^2) = [6, 3, 0, 1, 2]` - Factorize the number into primes and read off exponents to get the sequence. * `f(64971) = f(0b1111110111001011) = [6, 3, 0, 1, 2]` - Expand the number in binary and use 0 as a separator to read strings of ones, representing the sequence in unary. --- While this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") and the shortest answer will win, creative and interesting solutions are encouraged and may be subject to a bounty. [Answer] # J - 17 char ``` g=:(f=:_ q:>:)inv ``` We implement the prime exponent idea with this bijection—that's what the `_ q:` is doing, getting a list of the exponents of the primes of a number—except we also increment the input number by one before doing so, with `>:`, so that we don't forget 0, who doesn't have its own prime factorization. For the definition of `g`, it's exactly what it looks like: instead of writing it ourselves, we just tell J to take the inverse of `f`. Arguably this is cheating, or just not interesting, but I think that the ability to do this is what makes J such an interesting language: J can often figure things out for you, allowing you to focus on expressing your solution instead of implementing it. ``` i. 20 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 f i. 20 NB. J pads with zeroes on right 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 3 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 2 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 1 0 0 0 0 0 1 1 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 0 1 0 0 0 0 0 g f i. 20 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ``` Proving that this is a bijection is straightforward: the injectivity of this `f` is a well known fact and, if you assume that J's automagical inverse is correct (which it is), then this is trivial. If you don't want to take it on faith that J knows how to take the inverse of `f`, we can inspect its automatic inverse for `_&q:`: ``` _&q: b. _1 (p:@i.@# */ .^ ])"1 :.(_&q:) ``` and then [check the definition](http://www.jsoftware.com/help/dictionary/vocabul.htm): ``` (p:@i.@# */ .^ ])"1 :.(_&q:) NB. the alleged inverse of _&q: :.(_&q:) NB. defining _&q:inv inv to be _&q: ( )"1 NB. operate on rows of the argument # NB. length of argument i.@ NB. nonnegative integers less than p:@ NB. n-th prime for each integer n ] NB. the argument again .^ NB. pointwise exponentiation */ NB. product ``` and then confirm that J's inverse of `f` gives the decrement of the result of this: ``` >: b. _1 NB. inverse of increment is decrement <: f b. _1 NB. ([: f g) is one way of writing f composed with g [: <: (p:@i.@# */ .^ ])"1 :.(_&q:) ``` [Answer] # GolfScript, 41 bytes ``` {[2base[0]/{,}/]-1%}:f{:|;-1{).f|=!}do}:g ``` ### Function “f” ``` [ 2base # Push the digits of the argument in base 2. [0]/ # Split the digits around the 0's. This leaves sequences of 1's. {,}/ # Compute the lengths of those sequences. ]-1% # Reverse the array of the lengths. ``` The binary expansion of any given non-negative integer in its canonical form may have *trailing* 0's, but not *leading* 0's. Thus, reversing the array is necessary and sufficient to comply with the specification. ### Function “g” ``` :|; # Save the argument in variable “|” and pop it from the stack. -1 # Push the integer “-1”. { # ) # Increment the integer. .f|= # Check whether it is the preimage of “|”. ! # If it is not, }do # repeat the loop. ``` ### Function “g” (alternative) An alternative, straightforward and efficient implementation of `g` is ``` {[-1%{0\{1}*}/]2base}:g ``` The brute-force approach is *much* slower, but it is four bytes shorter. ``` [ -1% # Reverse the order of the integer sequence. { # For each integer “N”, 0 # push 0, \{1}* # followed by “N” 1's. }/ # ] # Convert this bit sequence into an array. 2base # Convert the array into an integer. ``` ### Example * `1250` is `10011100010` in base 2. * The lengths of the sequences of consecutive 1's are `1,0,3,0,0,1,0`. * Thus, the sequence corresponding to `1250` is `0,1,0,0,3,0,1`. ### Proof of work ``` 10000,(; # Push an array of all integers from 1 to 9999. { # For each integer “N”, f-1=0= # if “f(N)” has a trailing zero, {0p}* # print a message. }/ ``` leaves nothing on the stack, so `f` is well-defined. ``` 1000,. # Push the array of all integers from 0 to 999 and duplicate it. [ # {f g}/ # For each integer “N”, push “g(f(N))”. ]= # Check if the array of the images matches the original array. ``` leaves `1` on the stack (using either definition of `g`). This means that `g` is a left inverse of `f`, so `f` is injective. ``` [ 1000,. # Push the array of all integers from 0 to 999 and duplicate it. 10%- # Remove the integers with trailing 0's. { # For each integer “N”, 10base # push the array of its digits in base 10, .0\+.0\+ # and create copies with one and two leading 0's. }/ # ]. # Collect all sequences in an array and duplicate it. [ # {g f}/ # For each sequence “S”, push “f(g(S))”. ]= # Check if the array of the images matches the original array. ``` leaves `1` on the stack (using the second definition of `g`). This means that `g` is a right inverse of `f`, so `f` is surjective. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 + 3 = 10 or 11 bytes, language postdates question ``` JÆN*¹P’ ‘ÆE ``` [Try it online!](https://tio.run/nexus/jelly#ATQAy///SsOGTirCuVDigJkK4oCYw4ZF/zQx4bi2wrXIrjLEv8iuMcS/4bmEwrXigqzhuZvigJz/ "Jelly – TIO Nexus") Defines an packing function `1Ŀ` and an unpacking function `2Ŀ`. These could be defined in two separate programs, but if you define them both in a single program, you need a newline to separate the definitions. Thus I'm not 100% sure how to count it. ## Explanation This packs the sequence into a product of primes, which was one of the suggestions in the question. **Packing** ``` JÆN*¹P’ J Replace each element of {the input} by its index ÆN Replace each index n by the nth prime number * Raise each element to the power of ¹ {the original input} P Take the product of all the elements ’ Subtract 1 (so that some sequence maps to 0, making a bijection) ``` **Unpacking** ``` ‘ÆE ‘ Add 1 (undo the subtraction earlier) ÆE Output the number of times each prime divides the current value ``` As can be seen, unpacking is very simple here due to the builtin `ÆE`, which is why I selected this format. ~~There's no builtin to do the packing~~, but it has a fairly terse implementation too. # Jelly, 3 + 3 = 6 or 7 bytes, with some help from @Dennis OK, apparently there *is* a builtin to do the packing… ``` ÆẸ’ ‘ÆE ``` [Try it online!](https://tio.run/nexus/jelly#ATEAzv//w4bhurjigJkK4oCYw4ZF/zQx4bi2wrXIrjLEv8iuMcS/4bmEwrXigqzhuZvigJz/ "Jelly – TIO Nexus") The explanation above still works; it's just that all of `JÆN*¹P` have been replaced by a builtin. [Answer] # Python, ~~257~~ 265B ``` from itertools import* T=lambda i:[list(a)for l in range(i)for a in product(range(i-l+3),repeat=l+1)if a[-1]>0and sum(a)==i-l] def f(N): A,i=[[0]],0 while len(A)<=N:A+=T(i);i+=1 return A[N] def g(t): A,i=[[0]],0 while t not in A:A+=T(i);i+=1 return A.index(t) ``` To list every sequence, for each integer i, for each length l ``` 0 : 1 1 : 2 2 : 0 1 3 : 3 4 : 0 2 5 : 1 1 6 : 0 0 1 7 : 4 8 : 0 3 9 : 1 2 10 : 2 1 11 : 0 0 2 12 : 0 1 1 13 : 1 0 1 14 : 0 0 0 1 15 : 5 16 : 0 4 17 : 1 3 18 : 2 2 19 : 3 1 20 : 0 0 3 21 : 0 1 2 22 : 0 2 1 23 : 1 0 2 24 : 1 1 1 25 : 2 0 1 26 : 0 0 0 2 27 : 0 0 1 1 28 : 0 1 0 1 29 : 1 0 0 1 30 : 0 0 0 0 1 ``` so `f(256)=[9]`, and `g([4,2,0,3])=2254`. NB that this is SLOW for large numbers. [Answer] # MATL, 8+3 = 11 bytes ## Function f ``` QYF ``` Nice and simple, outputs the exponents of the prime factor decomposition of the input+1, for instance input of 1752922079 gives [5, 3, 1, 4, 0, 2] ## Function g Takes a finite vector of non-negative integers and outputs a single non-negative integer. ``` n:YqG^pq ``` ### Explanation ``` n % find the length of the input : % make a range that long Yq % use the range to find the first n primes G % paste the input vector again ^ % take powers element wise p % product of elements q % decrement by 1 so 0 is included % (implicit) convert to string and display ``` For instance, input [5, 3, 1, 4, 0, 2] first pushes the vector [2, 3, 5, 7, 11, 13], then combines them into [32, 27, 5, 2401, 1, 169] before taking the product, giving 1752922080 and decrementing to give the final answer 1752922079. ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 5 years ago. [Improve this question](/posts/12461/edit) I recently had to add a small basic calculator to a project. I wrote a quick dirty one, but it seemed small enough to check with you people out here ;) Just out of curiosity & an appetite to get surprised for some real hacky solutions, try and beat this one : **CODE (JS/JQUERY):** ``` function scalcy() { var b="", p=parseFloat,t,i; return $("<div>").append("789/456*123-.0=+".split("").map(function(i){ return $("<button/>").text(i).width(32).height(32).click(function(){ b = (!p(i=$(this).text())? b.replace(/\D+$/,""): b) + i; t.val(((!(i.match(/[.\d]/))? (b=eval(b.slice(0,-1))+i+"").slice(0,-1): p(b.match(/[.\d]+/g).pop()) || 0) + "").slice(0,8)); })})).prepend(t=$("<input/>").width(123).click(function(){ this.value=b="0";})).width(130); } ``` **Screenshot (in chrome):** ([**DEMO**](http://jsfiddle.net/XM7mD/)) ![enter image description here](https://i.stack.imgur.com/XaMVE.png) **Considerations:** Better the UI & lesser the bugs, the better. **Minimum Functionalities:** * Supports floating point arithmetic (/\*-+), * Reset feature, * Continuous Operation (like working on with the last result) **Note:** * Use any language & library, but please not a library call like *new calculator()*. * Forking the above code itself is most welcome. --- **Additional Notes:** * A graphical UI is obviously considered better than not having any at all. * I'd suggest to have a look at this challenge (for inspiration): [Create a GUI Piano](https://codegolf.stackexchange.com/questions/7346/create-a-gui-piano). [Answer] ## Tcl/Tk, 100 ``` pack [entry .e -textv e] -f both -e 1 bind . <Return> {catch {expr $e} e} bind . <Escape> {set e {}} ``` Buttons are not required, so leave them alone. The GUI is great. So simple that you can finally focus on the task that you try to do. ]
[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/264987/edit). Closed 5 months ago. [Improve this question](/posts/264987/edit) ## Pseudo-Quantum Bogosort Quantum Bogosort is as follows: 1. Quantumly randomise the list, such that there is no way of knowing what order the list is in until it is observed. This will divide the universe into O(n!) universes; however, the division has no cost, as it happens constantly anyway. 2. If the list is not sorted, destroy the universe. (This operation is left as an exercise to the reader.) 3. All remaining universes contain lists which are sorted. [Source](http://wiki.c2.com/?QuantumBogoSort) Given that we cannot destroy the universe, the next best thing is to destroy a thread! The challenge is as follows: Make a new thread/branch for each possible permutation of a list and if the list is not sorted, destroy the thread/branch (or just dont output it) ## Rules Input is a list of length 4 or less Output should be the randomized list for each thread or branch that successfully sorted it. Destroying/exiting the thread or branch is optional, but funny. If there is a repeated number, output list duplicates. This is standard code-golf Test cases: ``` [1,4,2,9] -> [1,2,4,9] [3,1,1,9] -> [1,1,3,9] and [1,1,3,9] [3,1,1,3] -> [1,1,3,3] [1,1,3,3] [1,1,3,3] [1,1,3,3] ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` fS=OP ``` [Try it online!](https://tio.run/##yygtzv7/Py3Y1j/g////0YY6hjpGOsY6JjomsQA "Husk – Try It Online") Quite closely follows the description. ``` P # Make a list with an element for each possible permutation of the input list f # Destroy (or just don't output) any element that doesn't satisfy: S=O # it's sorted ``` [Answer] # [Python](https://www.python.org), 77 bytes ``` lambda l:[x for x in permutations(l)if[*x]==sorted(x)] from itertools import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3fXMSc5NSEhVyrKIrFNLyixQqFDLzFApSi3JLSxJLMvPzijVyNDPTorUqYm1ti_OLSlJTNCo0Y7nSivJzFTJLUotK8vNzihUycwuAcloQQzcXFGXmlWikaUQb6xjrGOoYxmpqQmQWLIDQAA) [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), ~~3~~ 4 bytes *Edit: +1 byte to fix (unobservable) mechanism-of-action, thanks to [alephalpha](https://codegolf.stackexchange.com/questions/264987/pseudo-quantum-bogosort/264990?noredirect=1#comment578782_264990).* ``` ↕:o= ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHHBgqWlJWm6FssetU21yrddUpyUXAwVWrAy2lDHUMdIxygWIgAA) Nekomata seems well-suited for this. Default behaviour is to output all successful forks. ``` ↕ # non-deterministically choose a permutation of the input list : # duplicate it o= # keep one duplicate if it's equal to the other, sorted ``` [Answer] # [Factor](https://factorcode.org) + `math.combinatorics`, 49 bytes ``` [ <permutations> [ dup sort = ] parallel-filter ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TUw5DsIwEOzzivkAkaI0iKtFNDSIKkphjAMWztpar4sI8RKaNORP-Q0RadAUoznfQ6O0eO7H6nw6HPcrtEruufbtxZKaAqsjHobJOETPYukG7UknZkO6-ytGBDYiXWBLgnWWPVGimFDi9UnSLJZjUWETDLdJlFhPcYcK1xR-x9iiRlCsnDNu0VgnhlHPw0FPLvJZ9P3MXw) `parallel-filter` is a version of `filter` that spawns cooperative threads to handle each iteration. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes ``` ⊞υ⟦⟧Fθ≔ΣEυE⁻Eθνκ⁺κ⟦μ⟧υFυUMι§θκEΦυ⁼ι⌊υ⭆¹ι ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NU_BCsIwDL37FWWnFrrD8KLsJKLgQRh4HD3UqVtZ27m1Ef_Fyw6Kgl_gp_g3plMTQuDlvZfk8igq2RWN1H1_A3-IJ-9XBq6iwEkuWDo6NB2hLSMz51Rp6QYMXctjGIe2VhbcALScWMZJjZVpxGrUG8EwOIG_D7CgmjfGSLujipOZX9nd_hzUNUNW1inrB7-l0n7fhT2LFqR2gY3blMEDYHDdeCSXgZtwohBKr25buN8b9zyKTzoSzzwf8wRzKsR38gE) Link is to verbose version of code. Explanation: ``` ⊞υ⟦⟧Fθ≔ΣEυE⁻Eθνκ⁺κ⟦μ⟧υ ``` Generate all of the permutations of the indices of the input. This is taken from my answer to [Count N-Rich Permutations of an Integer Sequence](https://codegolf.stackexchange.com/q/264166/). I use the indices because they're unique and it makes it easier to generate the permutations. ``` FυUMι§θκ ``` Map each index to the actual value from the input list. ``` EΦυ⁼ι⌊υ⭆¹ι ``` Pretty print those that equal the minimum i.e. sorted value. [Answer] # [Python 3.8+](https://docs.python.org/3.8/), 75 bytes ``` lambda a:filter(min(p:=[*permutations(a)]).__eq__,p) from itertools import* ``` An unnamed function that accepts a tuple and returns a generator. **[Try it online!](https://tio.run/##LY3NCoMwEITvPsXiKZGlVG1BBfsiVSSlhgbMT@P2UIrPnia1O4f9Zlhm3Zse1tSN80H2Q1iEvt0FiE6qhWbPtDLMdf21cLPXLxKkrFmZ4CM/TNP8nCZ0PJPealDxnKxdVlDaWU9FkNYDzSuBMsBYhTWWeOIILEGJbcIznqLOCVts8binDf6UsMIqrRJ3U@4mlv39ntSxvOa8yyCO88oQk/knPd@gv8DnWkiWHB@3weQ8pLPwBQ "Python 3.8 (pre-release) – Try It Online")** ### How? `a` is the input tuple. `p` is initialised to a list of all permutations of `a`. A condition of being equal to the minimal permutation is then used to create a filter object. --- Also, non-conforming but interesting at **62 bytes**: ``` lambda a:8**sum(a.count(v)**7-1for v in{*a})%66%26*[sorted(a)] ``` [Try it online!](https://tio.run/##LY7dCoMwDIXv9xRBENqSjVWnU8G9iHrRTcuEWUWrMMRn71pdzsX58kOS4avfvQqTYTQyL81HdM9agMgSxqa5I@Ly6melyUIZu5@57EdYoFUrExv149gPYlZM/aibmghaGdfXzaTtCJAiwBA53iqEwgHH1GGEN6vIYYopXo9qgrscBhg44wfvxtHu@udHJbS7w4pmJ7AxjK39UXqru71B/oBVEsd0K5VHjfkB "Python 3.8 (pre-release) – Try It Online") The number of repeats of the sorted list needs to be \$\prod\_{m \in \text{multiplicities}} m!\$, e.g. `[5,4,5,5]` has multiplicities `[3,1]` and \$3!1!=6\$. But that's going to cost a lot of bytes. However, since the input has a length of at most four there are only twelve cases to handle by multiplicity, so I thought a hash might be golfier, so I had a play and came up with: | multiplicities | \*\*7-1 | sum | 8\*\*sum%66%26 == required length | | --- | --- | --- | --- | | [] | [] | 0 | 1 | | [1] | [0] | 0 | 1 | | [2] | [127] | 127 | 2 | | [3] | [2187] | 2187 | 6 | | [4] | [16383] | 16383 | 24 | | [1,1] | [0,0] | 0 | 1 | | [1,2] | [0,127] | 127 | 2 | | [1,3] | [0,2187] | 2187 | 6 | | [2,2] | [127,127] | 254 | 4 | | [1,1,1] | [0,0,0] | 0 | 1 | | [1,1,2] | [0,0,127] | 127 | 2 | | [1,1,1,1] | [0,0,0,0] | 0 | 1 | ...it's certainly shorter than this, more logical, shortcut for lists of length at most four (71): ``` lambda a:(sum((c:=a.count(v))*~-c*-~(c>3)for v in{*a})or 1)*[sorted(a)] ``` ]
[Question] [ What tips do you have for golfing in [(,)](https://www.esolangs.org/wiki/(,))? I've found that there are so many ways to make code shorter, and I want more ways. I doubt there even are any tips for (,) that are applicable in the majority of programming languages, but if there are, feel free to include them. Please, one tip per answer. [Answer] # Nest Variables When you have a variable (lets say A) with a index at least two more than a constant, fairly large variable B (or at least constant while you use A), you can usually instead have A be var[B]. Or, you can nest it more deeply. For an example of how this can help, first assume all variables are constant, sufficiantly large, and sufficiantly distinct. Then, with only one set of parentheses characters you can only make one variable: `()`. With 2, `()()` and `(())`. With 3, `()()()`, `(())()`, `(()())`, `((()))`. With 4, `()()()()`, `(())()()`, `(()())()`, `((()))()`, `(()()())`, `((())())`, `((()()))`, `(((())))`, `(())(())`. As you can see, it more than doubles for each new set of parentheses. However, since you usually don't have all constant variables, you should try out each reasonable combination of variable orderings to see which is smallest, and also keep in mind that constant variables greatly increase total accessable variables. [Answer] # Take advantage of flags There are a ton of flags currently existing. 'D' is only useful for debugging, but all others can be useful. The 's'/'S' flags are only useful for golfing, and can help cut down on commas used. 'i' is useful when input is an integer, 'm' is useful for multiplication of negative numbers, 'n' and 'N' are useful for different output formats, and 'd' is useful only rarely. [Answer] # Nest print statements When you are printing values of variables you could have a situation like this: ``` (,,(()))(,,(()())) ``` Where we are printing var1 followed by var2. Thanks to the fact that referring to a variable in the first argument does not require surrounding the variable address in parentheses, we could do this instead: ``` (,,(()(),,(()))) ``` Where the inner statement prints var1 and returns the value of var2, to be printed by the outer statement for two less bytes. With this approach it is still possible to do sums before printing, and this saved me lots of bytes in my [(,) quine](https://codegolf.stackexchange.com/a/262210/62393). [Answer] # Edit variables when you use them Title is fairly self-explanatory. Instead of going `[something](var)[something](var,[something])`, you can usually shorten it to `[something](var,[something])[something]`, because var access happens before var setting (aka return value += vars[var\_to\_access] happens before vars[var\_to\_access] = value\_to\_set\_var\_to). ## An example To output then increment variable one, instead of writing `(,,(()))((),(())())` write `(,,((),(())))`. ]
[Question] [ **This question already has answers here**: [Largest Number Printable](/questions/18028/largest-number-printable) (93 answers) Closed 3 years ago. The goal is to raise the error message with the most bytes! The error message may not be generated by the program itself, such as Python's `raise`. errors that do not terminate the program are not allowed unless they do not show an error message. Here is an example in python that raises 243041 bytes of error code: ``` def a(m): try:-'' except: if m>0: a(m-1) else:-'' a(900) ``` you can try it [here](https://tio.run/##K6gsycjPM/7/PyU1TSFRI1fTiksBCEqKKq101dXB7NSK5NSCEog4CGSmKeTaGSD4IADUqWuoCRdKzSlOBetP1LA0MND8/x8A). [Answer] # [Python 3](https://docs.python.org/3/), \$\approx\$A(A(A(9,9),A(9,9)),A(A(9,9),A(99,99))) where A is the Ackermann function,or limited by RAM ``` A=lambda m,n:m and A(m-1,n<1or A(m,n-1))or-~n a='.'*(A(A(A(9,9),A(9,9)),A(A(9,9),A(99,99)))) exec(a) ``` [Don't try it online!](https://tio.run/##K6gsycjPM/7/39E2JzE3KSVRIVcnzypXITEvRcFRI1fXUCfPxjC/CMTWydM11NTML9Kty@NKtFXXU9fScARDSx1LTR0IBaIRAkAaKKSpyZVakZqskaj5/z8A "Python 3 – Try It Online") Stole the Ackermann function from [here](https://codegolf.stackexchange.com/a/40151/89930). More manageable version to demonstrate: ``` A=lambda m,n:m and A(m-1,n<1or A(m,n-1))or-~n a='.'*(9999) exec(a) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/39E2JzE3KSVRIVcnzypXITEvRcFRI1fXUCfPxjC/CMTWydM11NTML9Kty@NKtFXXU9fSsAQCTa7UitRkjUTN//8B "Python 3 – Try It Online") Admittedly I'm not certain this approach is arbitrarily extendible in practice. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), a huge number \$ + 1605\$ bytes ``` ȷ!!!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡!¡”.xŒV ``` [Try it online!](https://tio.run/##y0rNyan8///EdkVFxUMLBwl61DBXr@LopLD//wE "Jelly – Try It Online") More specifically, this outputs an error message which is 1605 bytes long, plus two occurrences of massive chains of `...`. Unsurprisingly, this does not actually show an error really no matter where you run it, but in theory it will I'm not entirely sure just how large this number is, aside from being significantly larger than \$1000!\_{1000!\_{(1000!)!}}\$, where \$n!\_k\$ represents applying \$!\$ to \$n\$ \$k\$ times e.g. \$3!\_3 = ((3!)!)! = (6!)! = 720! = 2.6 \times 10^{1746}\$ [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), limited only by available memory Full program. Causes error message a bit bigger than twice the given number. ``` ⍎2e6⍴⎕A ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94P@j3j6jVLNHvVse9U11BAn9LwAA "APL (Dyalog Unicode) – Try It Online") `⎕A` the uppercase **A**lphabet `2e6⍴` cyclically **r**eshape to a string with two million characters `⍎` execute This causes an error of the form: ``` VALUE ERROR: Undefined name: *string* *string* ∧ ``` [Answer] ## Java 11, repeat error message [231 - 1] times [String's Maximum length](https://stackoverflow.com/q/816142/14940971) in Java is [`Integer.MAX_VALUE`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Integer.html#MAX_VALUE) i.e. == 231 - 1, or less, it depends on *server max memory size* and other conditions otherwise it produces [`OutOfMemoryError`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/OutOfMemoryError.html). 1. You can throw some [`Error`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Error.html) with the certain message, for example: ``` throw new Error("fatal".repeat(Integer.MAX_VALUE/5)); ``` Number of times to [`repeat`](https://hg.openjdk.java.net/jdk/jdk11/file/1ddf9a99e4ad/src/java.base/share/classes/java/lang/String.java#l3129 "Source code OpenJDK 11") is [`Integer.MAX_VALUE`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Integer.html#MAX_VALUE) / 5 - because `"fatal"` is 5 chars. 2. You can return something like this. It is not the error itself, but the error message: ``` for(int i=0;i<Integer.MAX_VALUE;i++){ String m="fatal"+i; out.println(m.repeat(Integer.MAX_VALUE/m.length()-1)); } ``` [Answer] # [Zsh](https://www.zsh.org/), \$4\times(9\times10^{307})^{32}+47\$ bytes ``` alias r=repeat\ 9e307 r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r r a+=1111 let $a ``` [Try it online!](https://tio.run/##qyrO@F@cWqKg68ZlZWOj7unu5x/kqv4/MSczsVihyLYotSA1sSRGwTLV2MCcq0iBMpiobWsIBFw5QAtVEv9DLOOC2AG0wlABwbQGqbWGKgQA "Zsh – Try It Online") Generates a string containing \$4\times(9\times10^{307})^{32}\$ ones, then tries to evaluate it as an integer. In practice you will obviously run into memory limitations. Here is a more manageable version: ``` repeat 9e1 repeat 9e1 a+=1 let $a ``` * `alias r=repeat\ 9e307` allows us to nest more `repeats` in the 100 bytes we have * `9e307` (\$9\times10^{307}\$) is the largest compact finite floating-point number `zsh` might be able to count to ]
[Question] [ ## Challenge Given a `number width`, `number height`, `hours` and `minutes` print the time using the following format style: ``` ------ - ------ ------ - - ------ ------ ------ ------ ------ | | | | | | | | | | | | | | | | | ------ ------ ------ ------ ------ | ------ ------ | | | | | | | | | | | | | | | | | | | | | | | | | | ------ - ------ ------ - ------ ------ - ------ ------ ``` For numbers with a mid line, when the height is odd just place it in the middle (example for `height = 3`): ``` ------ | | ------ | | ------ ``` However, when the height is even you can choose up or down: ``` ------ ------ | | | | | | ------ ------ | | | | | | ------ ------ ``` Of course, you need to specify this and use it every time. --- ## Input * **W**: The width of each number * **H**: The height of each number * **HRS**: Time hours * **MINS**: Time minutes --- ## Output You can either print the time, return a string (including the newlines) or return a list of strings (one string per line). --- ## Rules 1. Assume number width `> 2` 2. Assume number height `> 2` 3. The space between numbers is fixed to `2` 4. The space between hours and minutes is fixed to `4` 5. If hours or minutes are `< 10` (single digit), make sure to add a `0` (see example) 6. Assume that input hours and minutes will always be valid time 7. Digit `1` is a special case which always has the same width `1` and only it's height changes. 8. Height is considered the inner height, excluding the upper and lower rows of `---` (see example) --- ## Example Here's an example for `W=6`, `H=4`, `hrs=2`, `mins=18`: ``` ------ ------ - ------ | | | | | | | | ------ | ------ | | | | | | | | | | | | ------ ------ - ------ ``` [Answer] # JavaScript (ES8), ~~258~~ ~~245~~ ~~242~~ 239 bytes ``` (w,h,H,M)=>[2,h-1,2,h,2].map((r,y)=>`${(g=x=>((k=[876,,1284,260,8461,276,788,8484,780,268][x%10|0])?(s=x=>' -|'[[21,8,5,10,4,2][k*2>>y*3&7]>>x&3])().padEnd(w-2,s(4))+s(2):'-|||-'[y])+' ')(H/10)+g(H)} ${g(M/10)+g(M)} `.repeat(r/2)).join`` ``` [Try it online!](https://tio.run/##LY7daoNAFITv@xRepNlz4tG4G6tLwe1VwRufYFlQojF/VdHQKDHPbjfQm4H5hhnmXPwWw74/dTevactqOSQL3OlIKWWYKC3o6HGySsL4P0UH0NNkg3z1gDoZEwVwSbSMIyIuZEgiCkiGka1YFEtpjaWxDGwijR7feTAHBr9geJWZ481Ma8FJ0gfxgOyA0ZeNUGra7NaxUWpc7wwC@l1Rfjcl3D1BA4SI7gACP5k3z7PH9GTQZY7DENItD9CtIcWn46weNWT/IMPnW@73VVcVN@i3AtE/t6cmz5d92wzttfKvbQ0HiF4niEvE5Q8 "JavaScript (Node.js) – Try It Online") ### Character encoding Digits are made of 3 distinct characters: * 0: space * 1: `-` * 2: `|` ### Pattern encoding Each digit is made of 5 patterns: ``` 0: ----- <-- top pattern 1: | | <-- upper side repeated pattern 2: ----- <-- middle pattern 3: | <-- lower side repeated pattern 4: ----- <-- bottom pattern ``` Each pattern is made of a leading character \$L\$, followed by a repeated middle character \$R\$, followed by a trailing character \$T\$. All digits can be built by using only 6 distinct patterns, which are encoded as: $$L+R\times16+T\times4$$ ``` ID | Leading | Repeated | Trailing | Codes | Encoded as ----+---------+----------+----------+-------+------------ 0 | "-" | "-" | "-" | 1,1,1 | 21 1 | " " | " " | "|" | 0,0,2 | 8 2 | "-" | " " | "-" | 1,0,1 | 5 3 | "|" | " " | "|" | 2,0,2 | 10 4 | " " | " " | "-" | 0,0,1 | 4 5 | "|" | " " | " " | 2,0,0 | 2 ``` ### Digit encoding Because of its non-standard width, \$1\$ is a special case and is processed separately. All other digits are encoded as: $$\frac{1}{2}\sum\limits\_{n=0}^{4}2^{3n}P\_n$$ where \$P\_n\$ is the \$n\$-th pattern for this digit (0-indexed, from top to bottom). ``` Digit | Patterns | Encoded as -------+-----------+------------ 0 | 0,3,3,3,0 | 876 1 | n/a | n/a 2 | 0,1,0,5,0 | 1284 3 | 0,1,0,1,0 | 260 4 | 2,3,0,1,4 | 8461 5 | 0,5,0,1,0 | 276 6 | 0,5,0,3,0 | 788 7 | 0,1,1,1,4 | 8484 8 | 0,3,0,3,0 | 780 9 | 0,3,0,1,0 | 268 ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~296~~ ~~270~~ ~~256~~ ~~249~~ ~~244~~ 241 bytes ``` w,h,H,M=input() a,d,e='| -' b,c=d*(w-2),e*w f,g=e+b+e,d+b+e l,r,m=a+b+d,d+b+a,a+b+a E=eval for L in['ceccfccccc']+~-h/2*['marrmllrmm']+['macccccrcc']+h/2*['malrrrmrmr']+['ceccgccgcc']:print E(L[H/10]),d+E(L[H%10]),d+d,E(L[M/10]),d+E(L[M%10]) ``` [Try it online!](https://tio.run/##TY7bCoMwDIbv@xS9GfUQccoYY9BLwQt9AvGia@sBWpXiJoOxV3dt2WBJCPnzf4Qsz3WYp3zfNxighJqO03JfgxAxECApeeGEoBtwKqJgS/IQZLShDnoq41ssQbiOFBjQlNlZ@A0DNzNUUPlgCnWzwRUep4ZwyXnHXZA2fidDmkcN0cwYrZTR2i6d9IDxzI9QxjI2PeGu9L5Ie13MOK24CKqmTLNjG9oHvDh8hQAn63@v9t6@n@EEOWSXDw "Python 2 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 101 bytes ``` NθNη⊞υ¶F-|F⟦ι◧ιθ⁺◨ι⊖θι×ιθ⟧⊞υ⁺κ¶FE⪫E²◧IN²:⭆§⪪”)⧴9;ïjÞ⊟Pj%Uδ>LτS·Qr^ψQ”⁵﹪℅ι¹⁶×÷§⟦²⊖η²η⟧첧υIλ«Pι§⪪ι¶⁰→→ ``` [Try it online!](https://tio.run/##ZVHRTsMgFH1ev4LwRBOWrJVSM5@Me5mxujjf5h5qy1YipV0Li4n67fWC29wiCTfnXLicew9FlXdFk6thmOvWmkdbv4mO7MKb4JxXwBe2r4ilCL9qDHTTdIjg8RcOkYcrSdEiLx/ExhCAuxCosj2B3LPcVj45E0UnaqGNKEECbkjYL7IW/W/JOkRHFV/7flA7ymV5S@4bqT2I//Tu8t6Q837d27ELeIohLk0n9dYV3Zq5LsUHWbZKGoJZmqYsSpIkYpwlDAJnVynjMRDOIKSQ40BTh@CATdzCFCXwbNaUVjXkqSulzhVxw0Q8PI0012Ym97IUJ9VVfOlB5dqkqFpTVPuOKTpeBQv8VCr0C30Go8wqI1uYBLwER0YLDy8nkgfHKJo410ZZsxdk6j/gP/0eBh6wIA6i62G8Vz8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` NθNη ``` Input the height and width. ``` ⊞υ¶ ``` Push a newline to the predefined empty list. ``` F-| ``` Loop over the characters `-` and `|`. ``` F⟦ι◧ιθ⁺◨ι⊖θι×ιθ⟧ ``` Loop over the four values given by the character, the character padded to the width, the character on both sides of the width, and the character repeated across the width. ``` ⊞υ⁺κ¶ ``` Push those values plus a newline to the list. This results in the following elements for a width of 6: ``` - - - - ------ | | | | |||||| ``` (Note that the last one is unused, and the first and fifth elements are only one character wide.) ``` FE⪫E²◧IN²: ``` Input two numbers, convert to string, left pad to a width of 2, join them with `:`, then loop over the characters in that string. ``` ⭆§⪪”)⧴9;ïjÞ⊟Pj%Uδ>LτS·Qr^ψQ”⁵﹪℅ι¹⁶ ``` Split the compressed literal `4777415551464544646437462454644547446662474744746400000` into blocks of 5, then take the block indexed by the code point of the current character modulo 16, thus mapping space to 0 and `:` to 10. Map over those characters. ``` ×÷§⟦²⊖η²η⟧첧υIλ ``` Look up the character in the predefined list, then multiply it according to its index; the first, middle and last strings get multiplied by `2/2` while the intermediate strings get multiplied according to the height. ``` «Pι§⪪ι¶⁰→→ ``` Print the string without moving the cursor, then print the first line of the string again, then move the cursor a further two squares to the right. This means that `1` is special-cased because its first line is only a `-` while `:` is special-cased to have no intrinsic with at all and merely ends up doubling the space between digits. [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~101~~ ~~98~~ 96 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ┘{l2∔0×;+{ø;┤“\⤢YJ>`S‰/„2┬7n@{⁴Y?y5<?⁸»├⁸⇵|*-∔y3<?↕;┐1;}1y2%‽⁷+╷}┘╋]⁷-×1y5-⁸╵×⇵╵╋╋}}}} ×+} 4××+ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXUyNTE4JXVGRjVCJXVGRjRDJXVGRjEyJXUyMjE0MCVENyV1RkYxQiV1RkYwQiV1RkY1QiVGOCV1RkYxQiV1MjUyNCV1MjAxQyU1QyV1MjkyMiV1RkYzOUolM0UlNjAldUZGMzMldTIwMzAvJXUyMDFFJXVGRjEyJXUyNTJDJXVGRjE3JXVGRjRFJXVGRjIwJXVGRjVCJXUyMDc0JXVGRjM5JXVGRjFGJXVGRjU5JXVGRjE1JXVGRjFDJXVGRjFGJXUyMDc4JUJCJXUyNTFDJXUyMDc4JXUyMUY1JTdDJXVGRjBBLSV1MjIxNCV1RkY1OSV1RkYxMyV1RkYxQyV1RkYxRiV1MjE5NSV1RkYxQiV1MjUxMCV1RkYxMSV1RkYxQiV1RkY1RCV1RkYxMSV1RkY1OSV1RkYxMiV1RkYwNSV1MjAzRCV1MjA3NyV1RkYwQiV1MjU3NyV1RkY1RCV1MjUxOCV1MjU0QiV1RkYzRCV1MjA3Ny0lRDcldUZGMTEldUZGNTkldUZGMTUldUZGMEQldTIwNzgldTI1NzUlRDcldTIxRjUldTI1NzUldTI1NEIldTI1NEIldUZGNUQldUZGNUQldUZGNUQldUZGNUQlMjAlMjAlRDcldUZGMEIldUZGNUQlMjAldUZGMTQlRDclRDcldUZGMEI_,i=NSUwQTYlMEElNUIyJTJDMTglNUQ_,v=6) Nothing too fancy - stores the 7 bytes of info of each number and draws according to them. While making this I fixed 3 bugs in Canvas (though only one resulted in shortening the answer; [this](https://dzaima.github.io/Canvas/?u=JXUyNTEwJXVGRjM4JXVGRjVCJXVGRjRDJXVGRjEyJXUyMjE0MCVENyV1RkYxQiV1RkYwQiV1RkY1QiVGOCV1RkYxQiV1MjUyNCV1MjAxQyU1QyV1MjkyMiV1RkYzOUolM0UlNjAldUZGMzMldTIwMzAvJXUyMDFFJXVGRjEyJXUyNTJDJXVGRjE3JXVGRjRFJXVGRjIwJXVGRjVCJXUyMDc0JXVGRjM5JXVGRjFGJXVGRjU5JXVGRjE1JXVGRjFDJXVGRjFGJXUyMDc4JUJCJXUyNTFDJXUyMDc4JXUyMUY1JTdDJXVGRjBBLSV1MjIxNCV1RkY1OSV1RkYxMyV1RkYxQyV1RkYxRiV1MjE5NSV1RkYxQiV1MjUxMCV1RkYxMSV1RkYxQiV1RkY1RCV1RkYxMSV1RkY1OSV1RkYxMiV1RkYwNSV1MjAzRCV1RkY1OCV1RkYwQiV1MjU3NyV1RkY1RCV1MjUxOCV1MjU0QiV1RkYzRCV1RkY1OC0lRDcldUZGMTEldUZGNTkldUZGMTUldUZGMEQldTIwNzgldTI1NzUlRDcldUZGMTIlRjcldTI1NzUldUZGNTUldTI1NEIldUZGNUQldUZGNUQldUZGNUQldUZGNUQlMjAlMjAldUZGMUIldUZGMEIldUZGMEIldUZGNUQlMjAldUZGMTQlRDcldUZGMUIldUZGMEIldUZGMEI_,i=NCUwQTYlMEElNUIyJTJDMTglNUQ_,v=6) is how the result would've looked without [that commit](https://github.com/dzaima/Canvas/commit/15a58edff82013c87cf50eb60fa8d0c6ae92e85d#diff-7a9076d6d94e62c13d641aa71f19ae8eL1051)) Explanation: ``` ┘{ for each item of the 3rd input l2∔0×;+ prepend 2-length 0s to the item { for each character ø; push an empty canvas below the character ┤ cast the character to a digit “...„2┬7n the number 741859858201224148989 base-2 decoded & split into chunks of 7 - the digit data @ pick the item in that list corresponding to the current number { for each bit there ⁴Y store the index in the loop in Y ? if the current bit is set: y5<? if y < 5 (aka one of the vertical parts) ⁸»├ push height>>1 + 2 (y position of the part) ⁸⇵|* push a list of ceil(height/2) "|"s -∔ prepend a "-" to that y3<? if y < 3 (aka the top parts) ↕ reverse that list ;┐1; replace the y position with 1 } 1 push 1 (x position of the part) y2%‽ if y%2 is 0 ⁷+╷ add the width to that, then decrement } ┘╋ at those coordinates enter that array in the canvas pushed earlier ] else (aka y >= 5, the horizontal parts) ⁷-× repeat "-" width times 1 push 1 y5-⁸╵×⇵╵ push ceil((y-5) * (height+1) / 2) + 1 ╋╋ at (1; above line) in the canvas, place the dashes, without smart overlapping } } } } ×+ join the 2 digits with 2 spaces } 4××+ join the 2 numbers with 4 spaces ``` ]
[Question] [ [![enter image description here](https://i.stack.imgur.com/k2Rbq.png)](https://i.stack.imgur.com/k2Rbq.png) (The text asks how many boxes there are in the picture) Now you are required to generate such a problem and its answer. # Input * an integer `n` * (optionally) random source of two values, in case you don't want to use the [default random](https://codegolf.meta.stackexchange.com/a/1325). # Output can be * a 3D array `A[n][n][n]` of booleans, where `A[i][j][k] => (i==0 || A[i-1][j][k]) && (j==0 || A[i][j-1][k]) && (k==0 || A[i][j][k-1])` (assuming 0-index) where `&&` is logical AND, `||` is logical OR, and `=>` is "implies" (if `X` is true, then `Y` is true). Basically this says that if you have a box at some position then for each coordinate that coordinate must be either `0` or also have a box if that coordinate is one less. So no holes in any direction that gets you closer to the origin. * a 2D array `B[n][n]` of integers, where `B[i][j]` means how many `k` satisfy `A[i][j][k]` Basically this is the height of the stacks where these heights can't become lower in any direction that gets you closer to the origin. * Besides the array, the amount of boxes (how many `i,j,k` satisfy `A[i][j][k]`) Every valid output should have nonzero probability to be outputted. Example: (Here use 2D output format for convenience) ``` 1 => [[0]] 0 or [[1]] 1 2 => [[0,0],[0,0]] 0 [[1,0],[0,0]] 1 [[1,0],[1,0]] 2 [[1,1],[0,0]] 2 [[1,1],[1,0]] 3 [[1,1],[1,1]] 4 [[2,0],[0,0]] 2 [[2,0],[1,0]] 3 [[2,0],[2,0]] 4 [[2,1],[0,0]] 3 [[2,1],[1,0]] 4 [[2,1],[1,1]] 5 [[2,1],[2,0]] 5 [[2,1],[2,1]] 6 [[2,2],[0,0]] 4 [[2,2],[1,0]] 5 [[2,2],[1,1]] 6 [[2,2],[2,0]] 6 [[2,2],[2,1]] 7 or [[2,2],[2,2]] 8 ``` So for input `2` your program should randomly return one of the 20 possible outputs, and if run enough times every one of them should be returned at some point. Your program must terminate. # Winning criteria This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes win! [Answer] # [Perl 5](https://www.perl.org/), `-ap` 121 bytes / 56 bytes This 121 byte solution has a uniform distribution over all valid arrangements of boxes. It tries to be somewhat efficient but still times out on TIO for size 4 or more ``` #!/usr/bin/perl -ap @a=((0 x$_.$")x$_.$/)x$_."";s%0%/0(|.{@F}|(\X{@F}\X){@F})\G/+${$z="$`1$'"}++||push@a,$z;0%eg for@a;$_=$a[rand@a];$\=y/1// ``` [Try it online!](https://tio.run/##HcXBCoIwGADgV5HxSxNzm4SnMdipTt2FFvZDWkG44QpK56u30O/yuXZ4VjFqVJSK5AMNA5Kt8TVCpE9FygUNbNL7OVBTL5s6W8rMgecwwagIXErYkDnPQ3Bvf9e4hVGKtL0lnR00SmgU4GnA/qrxLMGoLy85j3H3s@71sL2PBbpYHCtWCib@ "Perl 5 – Try It Online") If you don't care about uniformity it's of course easy to go shorter, e.g. this 56 bytes solution is very biased towards the origin (it probably gives more nice pictures for the motivating example though) ``` #!/usr/bin/perl -a say map{\@$_[rand@;+1,$#{$_-1}];@;-$#$_.$"}@;for@;=1..$_ ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVIhN7GgOsZBJT66KDEvxcFa21BHRblaJV7XsDbW2sFaV0VZJV5PRanWwTotv8jB2tZQT08l/v9/s3/5BSWZ@XnF/3UT/@v6muoZGugZAAA "Perl 5 – Try It Online") (checked for size 2 and 3 that it indeed generates all possible outputs) [Answer] # [Python 2](https://docs.python.org/2/), 144 bytes ``` from random import* n=input() a=[n]*n*n for x in range(n*n):a[x]=randint(0,min(a[x-(x%n>0)],a[x-n])) print[a[i*n:i*n+n]for i in range(n)],sum(a) ``` [Try it online!](https://tio.run/##ZY7BCsIwEETv@YpepEmsUOtNqD8Scgja6h4yCTGF@PVxcxAK8liWGWaHjZ/8CpjqUpZ73/d1TcF3yeHBi3wMKWuBmRC3LJVws4HV0BBrSF3pCC37XCRb6upMsXO7JWQ5Dp4g2TrJcsBtVHZoAlYpERMnjDOkceU5wrY62tVx@r156VTlp/Q01rP4Me24/PEF "Python 2 – Try It Online") Quick and dirty solution. Generates a random number (which is upper-bounded by its left (if present) and upper cells) for each cell as a linear array, and then prints its 2D version and the sum. [Answer] ## JavaScript (ES6), 100 bytes ``` n=>[...Array(n)].map((_,i,a)=>k=a.map((_,j)=>l=0|Math.random()*-~(i?j?Math.min(k[j],l):k[0]:j?l:n))) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` ³‘X’¤þ`ṂƤ€Z$⁺ṄS⁺ ``` [Try it online!](https://tio.run/##y0rNyan8///Q5kcNMyIeNcw8tOTwvoSHO5uOLXnUtCZK5VHjroc7W4KB1P///y0B "Jelly – Try It Online") --- I made a terrible mistake. No idea why no-one noticed that. Full program. Prints the array and the sum. Not uniform, of course. Return all-zero most of the time. [Verification for side length 2](https://tio.run/##JYhBD4IgAEbv/Irv0KEOTJAsXIyNbPyPUpk2B6a47NeTrXd4b3uP@9yltK4N6Ag6QSkFKWxVSHtjgtsTu4ryzKrC5EdpqrIQ0kDDkXcNWm8lLkzo0Xvs9nP7Agdn7HBBEwg2sjDG7NkOw@dvOA@HHFojLJE0wbeEzGGKoMvvpPQF). ]
[Question] [ # Robbers thread In this thread, your task is to find a non-recursive solution which produces the same integer series of a submission not marked as 'safe' in the **[Cops' thread](https://codegolf.stackexchange.com/questions/157396/this-challenge-is-about-recursion-cops-thread/)**. # Challenge synopsis In many languages, recursive functions can significantly simplify a programming task. However, the syntax overhead for a proper recursion may limits its usability in code-golf. The **cops** will create a program or function taking a single integer `n`, which will generate the first `n` entries of an integer series, **using only recursion.**1. The **robbers** will try to find a **shorter** program or function in the same language, generating the same integer series, **using no recursion**2. If the cops' submission is not cracked within ten days (240 hours), the cop will prove it was in fact possible to have a shorter non-recursive approach by revealing their own solution. They may then mark their submission as **safe**. The winner of the cops challenge will be the shortest (according to [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")) recursion-based submission marked safe. **The winner of the robbers challenge will be the robber who cracked the most solutions.** 1: It only needs to be recursive in syntax; you don't need to worry about for example tail call optimization. 2: Again, non-recursive in syntax; so you can't post a recursive solution and claim its compiled to a loop thanks to tail call optimization. # Requirements Each submission will take a single integer `n` (zero- or one-based). The submission will then output or return the first `n` entries of the same integer series as the cops' entry. The input and output method may differ between the recursive and non-recursive approach. Your robbers' entry must be **strictly shorter** in byte-count than the recursive solution. It must work for at least the same `n`, or up to `n=2^15-1`, whichever is smaller. # Recursion For the sake of this challenge, recursion is defined as creating the desired sequence using a **function** (or function-like construct) that **calls itself** (or calls a sequence of functions that ends up calling itself). The recursion depth should go to infinity as `n` goes to infinity. The non-recursive approach is anything that is **not** recursive. [Answer] # [Octave](https://codegolf.stackexchange.com/a/157397/31516), by Sanchises 27 bytes There are so many, many ways to do this in a loopy-way. For instance this one, if an explicit loop is needed: ``` for i=1:input('')disp(i)end ``` [Try it online!](https://tio.run/##y08uSSxL/f8/Lb9IIdPW0Cozr6C0RENdXVMnJbO4QCNTUyc1L@X/f0MDAA "Octave – Try It Online") Or, if you want to create a vector (I haven't golfed this terribly well, since using a loop like this is kinda pointless): ``` x=0;for i=1:input(''),x(i)=i;end,x ``` Or 7 bytes if it's OK to not use a loop at all: ``` @(n)1:n ``` [Answer] ## [Python 3, 75 bytes by Bubbler](https://codegolf.stackexchange.com/a/157494/20260) **[Python 3](https://docs.python.org/3/), 51 bytes** ``` lambda n:[k for k in range(1,2**n)if 60**k%k<1][:n] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKjpbIS2/SCFbITNPoSgxLz1Vw1DHSEsrTzMzTcHMQEsrWzXbxjA22iov9j9IXSaSOgNNKy6FgqLMvBKNNI1MTc3/AA "Python 3 – Try It Online") Tests for 5-smoothness of `k` with `60**k%k<1`. [Answer] # [JavaScript (Node.js)](https://nodejs.org/), by [user71546](https://codegolf.stackexchange.com/a/157406/76323), ~~74~~ 72 Bytes ``` n=>{for(i=s=0;j=i++<n;console.log(s))for(x=i;j++<i;)for(;x%j<1;x/=j)s++} ``` [Answer] # [Gol><> by Jo King](https://codegolf.stackexchange.com/a/157662/34718), 12 bytes iterative ``` I:FL:R0|rRN; ``` [**Try it online**](https://tio.run/##S8/PScsszvj/39PKzccqyKCmKMjP@v9/IyMA) Makes good use of `R`, the repeat command. Once I thought of this method, I knew it would be shorter than trying to use a for loop within a while loop. **Explanation:** ``` I: Input and duplicate (will be used at the end to print). F For loop input times. L: Push and duplicate loop counter (leaving one on the stack). R0 Pop counter and push that many zeros. | End of loop. r Reverse the stack. RN; Print input times and halt. ``` [List of language commands](https://github.com/Sp3000/Golfish/blob/master/src/doc.txt) (`D` debug is useful for understanding what is going on) Golfish [Answer] <https://codegolf.stackexchange.com/a/158075/76323>, 78 Bytes ``` def A(n): x=[1]*n for i in range(2,n):x[i]=x[x[i-1]-1]+x[i-x[i-1]] return x ``` [Answer] # <https://codegolf.stackexchange.com/a/157397/76323>, 7 bytes assuming it's not recursive ``` @(n)1:n ``` or if use for, ``` function o=f(n);for i=1:n;disp(i);end;end; ``` [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), by jmarkmurphy, 22 bytes iterative ``` : | 0 do i 1+ . loop ; ``` [Try it online!](https://tio.run/##S8svKsnQTU8DUf//WynUKBgopOQrZCoYaivoKeTk5xcoWP83Vaj5DwA "Forth (gforth) – Try It Online") [Answer] ## [Python 3](https://codegolf.stackexchange.com/a/157757/78841) by PunPun1000, 59 bytes iterative ``` def f(x): l=[1] while x>0:l+=[sum(l[-2:])];x-=1 return l ``` I tried my hardest to do a closed-form one-liner, but I only got as low as the original submission. [Answer] # [COM function](https://codegolf.stackexchange.com/a/157428/55934), by l4m2, 11 bytes iterative ``` 0: 31 C0 xor ax, ax 2: BF 01 00 mov di, 1 5: 01 F8 add ax, di 7: AB stosw 8: E2 FB loop 5 A: C3 ret ``` Input CX, output [ES:1] ~ [ES:2\*CX] (inclusive) [Answer] # [JavaScript (Node.js)](https://codegolf.stackexchange.com/a/157811/76323), 45 bytes ``` x=>[...Array(x)].map(_=>h=h&1?3*h+1:h/2,h=14) ``` [Try it online!](https://tio.run/##BcFtDoIwDADQ25jWacn8@CMU4zmIIQsyW4OUDGLw9OO9T/iFuUs6LcfRXn3OkVeuGyJ6pBT@sOKTvmGClmth2fn7eS/O36Q4HYT9BXO0BMq@1IqvpTqHnY2zDT0N9oYIipg3 "JavaScript (Node.js) – Try It Online") ]
[Question] [ [Proton](https://github.com/alexander-liao/proton) is a quite new language created by PPCG user [Hyper Neutrino](https://codegolf.stackexchange.com/users/68942/hyperneutrino). It is very similar to [Python](https://docs.python.org/3/), and has similar syntax to the language [Cheddar](http://cheddar.vihan.org/), hence there are some clever tricks you can use in order to reduce your byte count. Let's get those cool tricks listed here. As usual, please post one tip per answer and avoid obvious things (e.g. remove spaces). If you have any further questions about any of the tips listed, there is a [dedicated chat room](https://chat.stackexchange.com/rooms/63945/proton) for Proton. [Answer] # Use currying when you need a lambda with 2 arguments If you want a function with 2 arguments, currying syntax always saves 1 byte. For example: ``` f=(a,b)=>a+b ``` Is one byte longer than: ``` f=a=>b=>a+b ``` The first function can be called with `f(number_1, number_2)`, whilst the latter is called using `f(number_1)(number_2)`. [Try it online!](https://tio.run/##KyjKL8nP@/8/zTbR1i7J1i5RO4kr3VYjUSdJE8LhKijKzCvRSNMw1dQw09SEctM1THWAvP//AQ) [Answer] # Take advantage of the fun features: operator functions `(+)` for all binary operators where the `+` is evaluates to a function that performs the exact same task as the operator itself. Where you'd use `int.__add__` when golfing in Python, use `(+)` for many bytes saved. [Answer] # Use `..`-ranges Instead of using `range(lower_bound, upper_bound)`, use `lower_bound..upper_bound`. For unary ranges, use `0..number` instead of `range(number)`. Some examples: ``` range(1,10) ``` Can be replaced by (-6 bytes): ``` 1..10 ``` And: ``` range(10) ``` Can be replaced by (-4 bytes): ``` 0..10 ``` [Answer] # Use inline-assignment Consider the following two: ``` a=>(a+5)*2/(a+5) a=>(b=a+5)*2/b ``` You can use inline assignments (where you treat an assignment as an expression) in Proton. The value given will be the right side of the assignment. This can sometimes help you take off a few bytes; more the longer the repeated expression, and especially if it has brackets already (because you need the brackets around the expression). [Answer] # Use point-free notation Even though lambda notation has a much shorter overhead than Python (`a=>` vs `lambda a:`), point-free notation is still often shorter, where you define a function as a composition of other functions. For example, consider the following chain of golfing: ``` a=>b=>dict(a)[b] a=>dict(a).get dict+((.)&get) ``` The last one currently isn't any shorter than the second last, but it does become shorter in some cases, for example, this: ``` a=>b=>[dict(a).get(f)for f:b] a=>b=>map(dict(a).get,b) a=>map(dict(a).get) dict+((.)&get)+map ``` You can get some pretty short code with that. `a & b` will return a function `*q => a(*q, b)` if `a` is a function and otherwise `*q => b(a, *q)` if `b` is a function, and `a + b` will return a function `*q => b(a(*q))`. ]
[Question] [ Implement the Discrete Cosine Transform (DCT). This may implemented as either a function or a program and the sequence can be given as either an argument or using standard input. Your program must be able to handle sequences of any length (assuming a hypothetical version of your language which has no limits on things like memory and integer size). There was a [previous challenge](https://codegolf.stackexchange.com/questions/82631/compute-the-discrete-fourier-transform) for DFT, now lets compute DCT! ;-) Use the [DCT-II definition from Wikipedia](https://en.wikipedia.org/wiki/Discrete_cosine_transform#DCT-II): [![DCT-II](https://i.stack.imgur.com/c8k8t.png)](https://i.stack.imgur.com/c8k8t.png) Your program takes a sequence *x**n* as input, and must produce the corresponding sequence *X**k*. In this formula, the cosine is in radians. ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest solution wins. * Builtins that compute the DCT in forward or backward (also known as inverse) directions are not allowed. * Floating-point inaccuracies will not be counted against you. * You don't have to use the exact algorithm shown here, as long as you produce the same results. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` LḶµ+.×þ÷L-*Ḟ³æ. ``` [Try it online!](https://tio.run/##AS8A0P9qZWxsef//TOG4tsK1Ky7Dl8O@w7dMLSrhuJ7Cs8OmLv///1sxLCAzLCAyLCA0XQ "Jelly – Try It Online") This uses the identity that `cos(pi * x) = real(e^(i * pi * x)) = real((-1)^x)` ## Explanation ``` LḶµ+.×þ÷L-*Ḟ³æ. Input: array A L Length Ḷ Lowered range - [0, 1, ..., len(A)-1] µ Begin a new monadic chain +. Add 0.5 ×þ Outer product using multiplication ÷ Divide by L Length -* Compute (-1)^x Ḟ Real part æ. Dot product with ³ The first argument (A) ``` [Answer] # Mathematica, 79 bytes ``` Tr/@(s=#;x=Length@s;Table[s[[n+1]]Cos[Pi/x(n+1/2)#],{n,0,x-1}]&/@Range[0,x-1])& ``` Since there are (currently) no test cases, as it turns out, there *is* a built-in for this: `FourierDCT`. However, the function "normalizes" the result by dividing it by a value before returning it. Thankfully, the documentation specifies that this division factor is just the square root of the input list's length (for DCT-II). So, we can verify our results by multiplying the output of `FourierDCT` by the square root of the length of our input list. For anyone else who tries this problem, here are some test cases: `FourierDCT@{1,3,2,4}*Sqrt@4` > > {10, -2.38896, 0, -2.07193} > > > `FourierDCT@{1,1,1,1,1}*Sqrt@5` > > {5, 0, 0, 0, 0} > > > Note that I've slightly edited the output of the last one; the last four values output as very small decimals, around 10-16, due to floating point precision errors around 0. My answer does give 0 for them, if you convert it to a decimal. This solution gives exact answers when Mathematica can do so. If that's not okay and you want decimals, let me know. [Answer] ## Clojure, 100 bytes ``` #(for[c[(count %)]k(range c)](apply +(map(fn[n x](*(Math/cos(*(/ c)Math/PI(+ n 0.5)k))x))(range)%))) ``` Sometimes it is difficult to be creative. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~88 83 78~~ 77 bytes ``` k;d(a,b,c)float*a,*b;{for(k=c*c;k--;)b[k/c]+=a[k%c]*cpow(-1,k/c*(.5+k%c)/c);} ``` [Try it online!](https://tio.run/##rY7BboMwEETvfMUKKZJt7Boa9eTyJciH9aaOLEhAgapSI369dA3XHnuwPPO8O2MyV6Jt691FoA6aZBxGXBRqFdwzjg/Rt6TI9cY4Gbrekq9a7PoTeUXT@CVMoxkq8fJWMZSWpFu3PQOwa2rvisOEw6T7AjdMdyGfBfBE7dvGsbJ219idM@DNrF99a/bX/A/IqwlaqB1f7zCn748xAtpDKGRcVSAhBwNMD56PAspThFJzU/Igc9bKZ/pcZlGWB7gIQA1BQ1PL/ykLf5WxX4vth@KA13kzw@0X "C (gcc) – Try It Online") This assumes the output vector is cleared before use. Thanks to [@Peter Taylor](https://codegolf.stackexchange.com/users/194/peter-taylor) for -5 [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~49 46 45~~ 42 bytes Here we consider the DCT as a matrix multiplication. The matrix is basically the entry-wise cosine of a rank 1 matrix which is very simple to construct. Thanks @Cowsquack for -1 byte, thanks @ceilingcat for another -3 bytes! ``` @(x)cos(pi/(n=numel(x))*(0:n-1)'*(.5:n))*x ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQaNCMzm/WKMgU18jzzavNDc1ByiiqaVhYJWna6iprqWhZ2qVBxSo@J@YV6wRbWitC0aGsZr/AQ "Octave – Try It Online") [Answer] # Mathematica, ~~51~~ 49 bytes ``` Re@Total[I^Array[(2##+#2)/n&,{n=Length@#,n},0]#]& ``` [Try it online!](https://tio.run/##y00sychMLv7/PyjVISS/JDEn2jPOsagosTJaw0hZWVvZSFM/T02nOs/WJzUvvSTDQVknr1bHIFY5Vu1/QFFmXkm0anS1oY6xjpGOSW2svr5f7H8A) (Using Mathics) Based on my solution to [DFT](https://codegolf.stackexchange.com/questions/82631/compute-the-discrete-fourier-transform/83127#83127). ]
[Question] [ ## The shortest reliable password testing code **Introduction** I started playing Empire of Code recently, and there was some challenge. The player is supposed to write a piece of Python or Javascript code to detect if the string passed to it is reliable password, that is, it contains at least one lowercase Latin letter, one uppercase Latin letter and one digit and has at least 10 characters. It was quite easy for me to fit within the 130 characters limit for rank 3 using Javascript, however, I spent a lot of time trying to fit within the 100 characters limit for rank 3 using Python. Some guy said that he has managed to fit in 71 characters for Python. I tried hard but still couldn't reduce the code to less than 90 characters. Is it possible to use even less than 71 characters? **Winning condition:** The shortest Python code (or Javascript), which solves given problem, wins. You may assume whatever was assumed in the original problem description in the game, given below. *Remark:* The solution should define a function or method called "golf" which takes the password as the first parameter and returns a boolean value indicating whether the given password satisfies the criterion. > > **Challenge Vault Password** > > [The following description is merged from two versions of the problem description (for Python and > for Javascript), copied from the game site > <https://empireofcode.com/> ] > > > We've installed a new vault to contain our valuable resources and > treasures, but before we can put anything into it, we need a suitable > password for our new vault. One that should be as safe as possible. > > > The password will be considered strong enough if its length is greater > than or equal to 10 characters, it contains at least one digit, as > well as at least one uppercase letter and one lowercase letter. The > password may only contain ASCII latin letters or digits, no > punctuation symbols. > > > You are given a password. We need your code to verify if it meets the > conditions for a secure password. > > > In this mission the main goal to make your code as short as possible. > The shorter your code, the more points you earn. Your score for this > mission is dynamic and directly related to the length of your code. > > > **Input:** A password as a string. > > > **Output:** A determination if the password safe or not as a boolean, or any data type that can be converted and processed as a boolean. > When the results process, you will see the converted results. > > > **Example:** > > > golf('A1213pokl') === false > > > golf('bAse730onE') === true > > > golf('asasasasasasasaas') === false > > > golf('QWERTYqwerty') === false > > > golf('123456123456') === false > > > golf('QwErTy911poqqqq') === true > > > **Precondition:** > > > 0 < |password| ≤ 64 > > > The password matches the regexp expression "[a-zA-Z0-9]+" > > > **Scoring:** > > > Scoring in this mission is based on the number of characters used in > your code (comment lines are not counted). > > > **Rank1:** > > > Any code length. > > > **Rank2:** > > > Your code should be shorter than 230 characters for Javascript code or > shorter than 200 characters for Python code. > > > **Rank3:** > > > Your code should be shorter than 130 characters for Javascript code or > shorter than 100 characters for Python code. > > > [Answer] # Python, 59 bytes ``` golf=lambda s:(9<len(s))*(s.lower()>s>s.upper())*'?'>min(s) ``` (Still) probably not optimal. [Answer] # JavaScript ES6, 67 - ES5, 88 Slightly longer than necessary as it has to return a proper true/false value (not truthy/falsy) ``` // MORE COMMON JAVASCRIPT - ECMASCRIPT 5 - 88 byte function golf(p){return!(!~(p.search(/\d/)|p.search("[a-z]")|p.search("[A-Z]"))||!p[9])} // NEWEST JAVASCRIPT - ECMASCRIPT 6 - 67 byte /* golf=p=>!(!~(p.search`\\d`|p.search`[a-z]`|p.search`[A-Z]`)||!p[9]) */ // Explanation // search gives -1 if not found, if any of search results is -1 then ORing we have a result of -1 // ~ operator is 0 if and only if operand is -1 // !p[9] is true if the string has less than 10 characters // TEST function out(x) { O.innerHTML += x + '\n' }; ;[['A1213pokl',0],['bAse730onE',1],['asasasasasasasaas',0],['QWERTYqwerty',0],['123456123456',0],['QwErTy911poqqqq',1]] .forEach(function(pwd){out(pwd[0]+' '+!!pwd[1]+' '+golf(pwd[0]))}) ``` ``` <pre id=O></pre> ``` [Answer] # JavaScript – 83 bytes ``` function golf(x){return!!(/\d/.test(x)&/[a-z]/.test(x)&/[A-Z]/.test(x)&x.length>9)} ``` [Answer] # Python, 83 bytes Alternatively, you can try this (**93 bytes**): ``` import re def golf(p): return bool(re.findall(r'(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{10,}',p)) ``` or (**83 bytes**) ``` import re golf=lambda p:bool(re.findall(r'(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{10,}',p)) ``` [Try it online!](https://tio.run/##VY/disIwEIXv5ylyl0S0GOsPKxTpRR9AEcS/i5Smu2FjJiYB6S4@e23VG@fAnI@5mJnjmviDNm1bfXHoI/EKvtHUmZGXspLELUtEw7xKam0raTqkbJUlg6Mc/Z35C/PR4Y2niif/Yjy806HjvI0qxEAyQikt86AW6RhtAetb4bfNlxAOr11BLiYidfhrQIYPyQDrXbHZ7q835WMDYpJOZ/NX71YmwRkdGT1ZygFq9KS/R7R9elgCIc5rG1kfiPWz7qUH "Python 3 – Try It Online") [Answer] The solution on Python I could implement, 90 bytes ``` import re golf=lambda p:re.compile(r'(?=.{10,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])').search(p) ``` ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/29998/edit). Closed 7 years ago. [Improve this question](/posts/29998/edit) Write a program that prints "Hello, world!" without using any kinds of literals. Don't use string literals, numeric literals, byte literals, char literals, etc. Default values are allowed in languages that have them. Printing data from external files/websites/arguments is not encouraged. edit: probably don't use Boolean literals either. double edit: I don't necessarily want the code to be obfuscated. results that are clearly understandable are better. triple edit: this is not duplicate because the other questions require obfuscated answers or are code-golf. [Answer] # JSfuck Try it in any javascript console. **Edit** To avoid the array literal. Shorter too. ``` a=Array(); a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+ a)[!+a+!+a+!+a]+(!!a+a)[+!+a]][(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+! +a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!!a+a[(!a+a )[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(! !a+a)[+!+a]])[+!+a+[+a]]+(a[a]+a)[+!+a]+(!a+a)[!+a+!+a+!+a]+(!!a+a)[+a]+(!!a+a)[ +!+a]+(a[a]+a)[+a]+(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[ +a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!!a+a)[+a]+(!!a+a[(!a+a )[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(! !a+a)[+!+a]])[+!+a+[+a]]+(!!a+a)[+!+a]]((!a+a)[+!+a]+(!a+a)[!+a+!+a]+(!!a+a)[!+a +!+a+!+a]+(!!a+a)[+!+a]+(!!a+a)[+a]+(!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+ a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[!+a+!+a+[+a]]+(a+a) [(!a+a)[+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a] +(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(a[a]+a)[+!+a]+(!!a+a)[+a]+(a[( !a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a ]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a) [!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(!a+a)[!+a +!+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+ a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(!!a+a)[+!+a]]()[+!+a+[!+a+!+a]]+a[(! a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a] +(!!a+a)[+!+a]][(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a] +(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a ])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+ !+a+[+a]]+(a[a]+a)[+!+a]+(!a+a)[!+a+!+a+!+a]+(!!a+a)[+a]+(!!a+a)[+!+a]+(a[a]+a)[ +a]+(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a +!+a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!!a+a)[+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a ])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+ !+a+[+a]]+(!!a+a)[+!+a]]((!!a+a)[+!+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+a]+(a[a]+a) [+a]+(!!a+a)[+!+a]+(a[a]+a)[+!+a]+(+[!a]+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a +a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+!+a]]+(a[a] +a)[+a]+(a[a]+a)[+!+a]+(!!a+a)[!+a+!+a+!+a]+(!a+a)[!+a+!+a+!+a]+(a[(!a+a)[+a]+([ !a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+! +a]]+a)[!+a+!+a+!+a]+(!a+a)[+!+a]+(+(!+a+!+a+[+!+a]+[+!+a]))[(!!a+a)[+a]+(!!a+a[ (!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+ a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(+!a+(a+a)[(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(! a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(! !a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+! +a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(a[a]+a)[+!+a]+(!a+a)[!+a+!+a+!+a]+(!!a+a)[+a ]+(!!a+a)[+!+a]+(a[a]+a)[+a]+(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a ]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!!a+a)[+a]+(! !a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+! +a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(!!a+a)[+!+a]])[+!+a+[+a]]+(!!a+a)[+a]+(!!a+a )[+!+a]+([!a]+a[a])[+!+a+[+a]]+(a[a]+a)[+!+a]+(+!a+[!a]+(a+a)[(a[(!a+a)[+a]+([!a ]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a ]]+a)[!+a+!+a+!+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a +a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(a[a]+a)[+!+a]+(!a+a)[!+ a+!+a+!+a]+(!!a+a)[+a]+(!!a+a)[+!+a]+(a[a]+a)[+a]+(a[(!a+a)[+a]+([!a]+a[a])[+!+a +[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+ a+!+a]+(!!a+a)[+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a +a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(!!a+a)[+!+a]])[!+a+!+a+ [+a]]](!+a+!+a+!+a+[+!+a])[+!+a]+(!!a+a)[!+a+!+a+!+a])()(a[(!a+a)[+a]+([!a]+a[a] )[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]][(a[ (!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+ a]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a )[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(a[a]+a)[ +!+a]+(!a+a)[!+a+!+a+!+a]+(!!a+a)[+a]+(!!a+a)[+!+a]+(a[a]+a)[+a]+(a[(!a+a)[+a]+( [!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+ !+a]]+a)[!+a+!+a+!+a]+(!!a+a)[+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a )[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(!!a+a)[+ !+a]]((!!a+a)[+!+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+a]+(a[a]+a)[+a]+(!!a+a)[+!+a]+ (a[a]+a)[+!+a]+(+[!a]+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a )[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+!+a]]+(!!a+a)[!+a+!+a+!+a]+(!a +a)[!+a+!+a+!+a]+(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a ]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!a+a)[+!+a]+(+(!+a+!+a+[+ !+a]+[+!+a]))[(!!a+a)[+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+ a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(+!a+(a+a)[(a[(!a +a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+ (!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[! +a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(a[a]+a)[+!+ a]+(!a+a)[!+a+!+a+!+a]+(!!a+a)[+a]+(!!a+a)[+!+a]+(a[a]+a)[+a]+(a[(!a+a)[+a]+([!a ]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a ]]+a)[!+a+!+a+!+a]+(!!a+a)[+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[! +a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(!!a+a)[+!+a ]])[+!+a+[+a]]+(!!a+a)[+a]+(!!a+a)[+!+a]+([!a]+a[a])[+!+a+[+a]]+(a[a]+a)[+!+a]+( +!a+[!a]+(a+a)[(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+ (!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a] )[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+! +a+[+a]]+(a[a]+a)[+!+a]+(!a+a)[!+a+!+a+!+a]+(!!a+a)[+a]+(!!a+a)[+!+a]+(a[a]+a)[+ a]+(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+ !+a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!!a+a)[+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a] )[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+! +a+[+a]]+(!!a+a)[+!+a]])[!+a+!+a+[+a]]](!+a+!+a+!+a+[+!+a])[+!+a]+(!!a+a)[!+a+!+ a+!+a])()((a+a)[([!a]+a[a])[+!+a+[+a]]+(!!a+a)[+a]+(!a+a)[+!+a]+(!a+a)[!+a+!+a]+ ([!a]+a[a])[+!+a+[+a]]+(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a +a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!a+a)[!+a+!+a+!+a]] ()[+a])[+a]+(!+a+!+a+!+a+!+a+[!+a+!+a+!+a+!+a+!+a+!+a+!+a+!+a])+a)+(!!a+a)[!+a+! +a+!+a]+(!a+a)[!+a+!+a]+(!a+a)[!+a+!+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]] +(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+[a] [(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+ a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+( !a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(a[a] +a)[+!+a]+(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+ a)[!+a+!+a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!a+a)[+!+a]+(!!a+a)[+a]]([a])+a+ (+[!a]+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[! +a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+!+a]]+(+(!+a+!+a+!+a+[!+a+!+a]))[(!!a+a)[+a]+ (!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a +!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(+!a+(a+a)[(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[ +a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+ !+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a )[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(a[a]+a)[+!+a]+(!a+a)[!+a+!+a+!+a]+(!! a+a)[+a]+(!!a+a)[+!+a]+(a[a]+a)[+a]+(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[ !+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!!a+a) [+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a )[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(!!a+a)[+!+a]])[+!+a+[+a]]+(!!a+a)[+a] +(!!a+a)[+!+a]+([!a]+a[a])[+!+a+[+a]]+(a[a]+a)[+!+a]+(+!a+[!a]+(a+a)[(a[(!a+a)[+ a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+ a)[+!+a]]+a)[!+a+!+a+!+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+ a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(a[a]+a)[+!+a]+(! a+a)[!+a+!+a+!+a]+(!!a+a)[+a]+(!!a+a)[+!+a]+(a[a]+a)[+a]+(a[(!a+a)[+a]+([!a]+a[a ])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]]+a) [!+a+!+a+!+a]+(!!a+a)[+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+ a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(!!a+a)[+!+a]])[! +a+!+a+[+a]]](!+a+!+a+!+a+[!+a+!+a+!+a])+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a] ]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(! !a+a)[+!+a]+(!a+a)[!+a+!+a]+(a[a]+a)[!+a+!+a]+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a] ]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]][(a[(!a+a)[+a]+ ([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[ +!+a]]+a)[!+a+!+a+!+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+ (!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(a[a]+a)[+!+a]+(!a+a )[!+a+!+a+!+a]+(!!a+a)[+a]+(!!a+a)[+!+a]+(a[a]+a)[+a]+(a[(!a+a)[+a]+([!a]+a[a])[ +!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]]+a)[!+ a+!+a+!+a]+(!!a+a)[+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+ (!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(!!a+a)[+!+a]]((!!a+ a)[+!+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+a]+(a[a]+a)[+a]+(!!a+a)[+!+a]+(a[a]+a)[+! +a]+(+[!a]+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+ a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+!+a]]+(a[a]+a)[+a]+(a[a]+a)[+!+a]+(!!a+a) [!+a+!+a+!+a]+(!a+a)[!+a+!+a+!+a]+(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+ a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!a+a)[+! +a]+(+(!+a+!+a+[+!+a]+[+!+a]))[(!!a+a)[+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+ a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+ (+!a+(a+a)[(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a +a)[!+a+!+a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+! +a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[ +a]]+(a[a]+a)[+!+a]+(!a+a)[!+a+!+a+!+a]+(!!a+a)[+a]+(!!a+a)[+!+a]+(a[a]+a)[+a]+( a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+ !+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!!a+a)[+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+! +a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[ +a]]+(!!a+a)[+!+a]])[+!+a+[+a]]+(!!a+a)[+a]+(!!a+a)[+!+a]+([!a]+a[a])[+!+a+[+a]] +(a[a]+a)[+!+a]+(+!a+[!a]+(a+a)[(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+ !+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!!a+a[(!a+ a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+( !!a+a)[+!+a]])[+!+a+[+a]]+(a[a]+a)[+!+a]+(!a+a)[!+a+!+a+!+a]+(!!a+a)[+a]+(!!a+a) [+!+a]+(a[a]+a)[+a]+(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a) [+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!!a+a)[+a]+(!!a+a[(!a+ a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+( !!a+a)[+!+a]])[+!+a+[+a]]+(!!a+a)[+!+a]])[!+a+!+a+[+a]]](!+a+!+a+!+a+[+!+a])[+!+ a]+(!!a+a)[!+a+!+a+!+a])()(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+( !!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]][(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+ a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+! +a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a) [!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(a[a]+a)[+!+a]+(!a+a)[!+a+!+a+!+a]+(!!a +a)[+a]+(!!a+a)[+!+a]+(a[a]+a)[+a]+(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[! +a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!!a+a)[ +a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a) [!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(!!a+a)[+!+a]]((!!a+a)[+!+a]+(!!a+a)[!+ a+!+a+!+a]+(!!a+a)[+a]+(a[a]+a)[+a]+(!!a+a)[+!+a]+(a[a]+a)[+!+a]+(+[!a]+a[(!a+a) [+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!! a+a)[+!+a]])[+!+a+[+!+a]]+(!!a+a)[!+a+!+a+!+a]+(!a+a)[!+a+!+a+!+a]+(a[(!a+a)[+a] +([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a) [+!+a]]+a)[!+a+!+a+!+a]+(!a+a)[+!+a]+(+(!+a+!+a+[+!+a]+[+!+a]))[(!!a+a)[+a]+(!!a +a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a +!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(+!a+(a+a)[(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]] +(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a] +(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+ a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(a[a]+a)[+!+a]+(!a+a)[!+a+!+a+!+a]+(!!a+a) [+a]+(!!a+a)[+!+a]+(a[a]+a)[+a]+(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+ !+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!!a+a)[+a] +(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+ a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(!!a+a)[+!+a]])[+!+a+[+a]]+(!!a+a)[+a]+(!! a+a)[+!+a]+([!a]+a[a])[+!+a+[+a]]+(a[a]+a)[+!+a]+(+!a+[!a]+(a+a)[(a[(!a+a)[+a]+( [!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+ !+a]]+a)[!+a+!+a+!+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+( !!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(a[a]+a)[+!+a]+(!a+a) [!+a+!+a+!+a]+(!!a+a)[+a]+(!!a+a)[+!+a]+(a[a]+a)[+a]+(a[(!a+a)[+a]+([!a]+a[a])[+ !+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]]+a)[!+a +!+a+!+a]+(!!a+a)[+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+( !!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(!!a+a)[+!+a]])[!+a+! +a+[+a]]](!+a+!+a+!+a+[+!+a])[+!+a]+(!!a+a)[!+a+!+a+!+a])()((a+a)[([!a]+a[a])[+! +a+[+a]]+(!!a+a)[+a]+(!a+a)[+!+a]+(!a+a)[!+a+!+a]+([!a]+a[a])[+!+a+[+a]]+(a[(!a+ a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+( !!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!a+a)[!+a+!+a+!+a]]()[+a])[+a]+(!+a+!+a+[+!+a])+a )+(a+a)[(!a+a)[+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a +a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(a[a]+a)[+!+a]+(!!a+a)[+ a]+(a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+ !+a+!+a]+(!!a+a)[+!+a]]+a)[!+a+!+a+!+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]] +(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(!a +a)[!+a+!+a]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a ]+(!!a+a)[!+a+!+a+!+a]+(!!a+a)[+!+a]])[+!+a+[+a]]+(!!a+a)[+!+a]]()[+!+a+[!+a+!+a ]]+(!!a+a[(!a+a)[+a]+([!a]+a[a])[+!+a+[+a]]+(!a+a)[!+a+!+a]+(!!a+a)[+a]+(!!a+a)[ !+a+!+a+!+a]+(!!a+a)[+!+a]])[!+a+!+a+[+a]])() ``` [Answer] **HQ9+ - 1 char** ``` H ``` :) Has this being a code golf, I won hands down. Is this good enough? But, well. This is good enough for popularity contest. [Answer] # Cobra ``` struct Hello var i struct B var i struct X var i struct M var i struct World var i class Program def main hello = Hello().toString comma = Convert.toString(Convert.toChar(((Convert.toChar(X().toString) to int)-(Convert.toChar(B().toString) to int))+(Convert.toChar(X().toString) to int)-(Convert.toChar(B().toString) to int))) world = World().toString.toLower exclaim = Convert.toString(Convert.toChar(((Convert.toChar(X().toString) to int)-(Convert.toChar(B().toString) to int))+(Convert.toChar(X().toString) to int)-(Convert.toChar(M().toString) to int))) print hello+comma, world+exclaim ``` This uses the default .toString method, and some character code arithmetic. [Answer] # Julia ``` Hello(x)=x world(y)=y k=int(ones())[] show(Hello) print(collect(summary([]))[end-k-k]) print(char((k+k)^(k+k+k+k+k))) show(world) print(!) ``` What it's doing: printing function names, rather than literals. Also, using int(ones())[] to get a 1, which is necessary to get the space without too much hassle (space is character 32, which is being obtained as 2^5), and using summary([]) and then getting the third-last character in order to get the comma. [Answer] ## Python 3.4(.0) If you look in the right places, you can find the string "Hello, world!" somewhere. Note: `None` is a keyword and not a literal in Python, according to the documentation. ``` from test import test_wsgiref for binstring in test_wsgiref.hello_app(None, lambda x, y: None): print(binstring.decode()) ``` [Answer] # JavaScript i did not use any custom literals if it counts. (implying Function.name doesn't exist) ``` function Hello(){} function World(){} var hello_str = uneval(Hello), world_str = uneval(World), _1 = (+new Date())/(+new Date()), _2 = _1+_1, _4 = _2*_2, _8 = _2*_4; alert([ hello_str.substr(_8, _8 - _2), world_str.substr(_8, _8 - _2) + String.fromCharCode(_8 * _4 + _1) ]); ``` try: <http://jsfiddle.net/pykP8/> ]
[Question] [ A string of digits (positive integer) can be converted to plain English in various ways. For instance, 115 can be read as "hundredfifteen", "oneonefive", "elevenfive", "twoonesfive". So question's challenge is to output the shortest string representation for a given digits string. Rules: * The input string can start with a zero and the output should account for that. * Maximum length of input is 18. So you deal with numbers less than a Quintillion. * You should use only the following mathematical words for numbers in your output: zero, one, ..., nine, ten, eleven, ..., twenty, ..., ninety, hundred, million, billion, trillion. You can use their plural forms for sequences (i.e. "fivetens" for 1010101010). No synonyms (i.e. "oh" for 0) or slang (i.e. [legs](https://en.wikipedia.org/wiki/List_of_British_bingo_nicknames) for 11) are allowed. You don't need to include a "one" prefix for cases like 100, just "hundred" is fine. * You don't need to put spaces between different words in your output. * The output shouldn't be ambigous. This means, from the output string one should be able to determine the input unambigously. So for 705 you can't output "seventyfive" since it may be the output of 75 also. You may use "and" if that'll remove ambiguity, otherwise you don't need to include "and" in your output. * Winner is the entry that will have the shortest code length excluding import statements and if not some user finds out a deficit in the code (i.e. a shorter representation than the program spits out for a particular input ). * Please post your output for the following test cases to make evaluation easier: 1234, 00505, 122333, 565577555555666888, 1000010, 10001000, 10101010. * No reading from an input file, so usage of a dictionary or hash map should count towards your code length. **edit1**: Changed the competition type to code-golf per comments and added test cases. **edit2**: Restricted the words that can be used in the output. Thanks to @PeterTaylor for the examples. [Answer] # 4 This is cheeky and a cheat. [I wrote this script about a year ago](https://gist.github.com/dmadisetti/5770850) based off of [this comic](http://wheresmysammich.com/images/34082.jpg) (tad of profanity). The idea goes like this. Given any number as a string, adding the number of characters will eventually condense to 4. `Four` itself is 4 letters long and thus the end of the line. For example: * 10 -> 'ten' * 'ten' -> 3 (letters long) * 3 -> 'three' * 'three' -> 5 (letters long) * 5 -> 'five' * 'five' -> 4 (letters long) I verified up to 100,000. Very hacky but got the job done: ``` to20 = [ 'zero' ,'one' ,'two' ,'three' ,'four' ,'five' ,'six' ,'seven' ,'eight' ,'nine' ,'ten' ,'eleven' ,'twelve' ,'thirteen' ,'fourteen' ,'fifteen' ,'sixteen' ,'seventeen' ,'eighteen' ,'nineteen' ] by10s = ['twenty' ,'thirty' ,'forty' ,'fifty' ,'sixty' ,'seventy' ,'eighty' ,'ninety' ] by10powers = [ 'hundred' ,'thousand' ] def cosmetize(number): # the number is too damn high! if number >= 100000: return "Too high" numstr = str(number) # Do ones if number < 10: return to20[number] # Pshh.. who needs zero anymore? to20[0] = '' # Do tens numstr10 = numstr[-2:] if int(numstr10) < 20: numstr10 = to20[int(numstr10)] else: numstr10 = by10s[int(numstr10[0])-2] + to20[int(numstr10[1])] if number < 100: return numstr10 # Do hundreds numstr100 = numstr[-3] if numstr10 == '': numstr10 = "" numstr100 = to20[int(numstr100)] + by10powers[0] elif int(numstr[-2:]) > 19: numstr100 = to20[int(numstr100)] + by10powers[0] numstr100 += 'and' else: numstr100 = 'and' if number < 1000: return numstr100 + numstr10 # Do thousands numstr1000 = numstr[:-3] if numstr100 == 'hundred': numstr100 = "" if int(numstr1000) < 20: numstr1000 = to20[int(numstr1000)] + by10powers[1] else: numstr1000 = by10s[int(numstr1000[0])-2] + by10powers[1] return numstr1000 + numstr100 + numstr10 i = 0 mx = [] z = 0 while i < 100000: length = cosmetize(i) x = [length] while not len(length) == 4: length = cosmetize(len(length)) i += 1 # No inifinite loop? what magic is this? print "OMG" ``` [Answer] # Python - (191 - 38) = 153 bytes This code has the worst case length of 18 for input of `000000000000000000`. I'm not sure if this is system dependant. If it's not, I could remove a couple characters. ``` from string import* from math import* s=digits+lowercase+uppercase c=raw_input() b=len(s) a=int(c) print'-'*(len(c)-len(c.lstrip('0')))+''.join(s[a/b**i%b]for i in range(int(log(a,b)),-1,-1)) ``` For the last line I have to give credit to [this fellow](https://stackoverflow.com/a/11406745). Example outputs: ``` > 1234 9j > 00505 --3Z > 122333 6Vn > 565577555555666888 5haShÄøŠé > 1000010 êÌõ > 10001000 48Šõ > 10101010 4ewª ``` Disclaimer: This answer is not a serious answer and it's not trying to compete. This is taking advantage of ambiguity of the rules. ]
[Question] [ You have two images (64x64 pixels each): ![saturated picture](https://i.stack.imgur.com/KHEHg.png) ![desaturated picture](https://i.stack.imgur.com/JrxBD.png) Your program must take the file names of each of them as command line arguments and determine which has more average saturation among their pixels. The images are in ImageMagick .txt format. You can download and convert these images using `convert pic.png pic.txt` or download the raw text ([saturated](http://pastebin.com/raw.php?i=5f3B4uxP), [desaturated](http://pastebin.com/raw.php?i=VdjDm9HK)) Ignore the first line of the file (required). Solutions in Assembly get 50% of their characters for free. Brainfuck, whitespace, and close variants, get 25% of their characters for free. (e.g. if it takes 200 characters in Brainfuck; mark it as 200-50=150.) Describe your output. It could be the name of the more saturated image; the index of it (0 for first, 1 for second); true for the first, false for the second, etc. Just let us know. It should be able to take either the saturated or desaturated image first, and accurately report the more saturated (test both ways). The filenames shouldn't be considered when evaluating saturation (e.g. no `if filename contains 'desaturated'...`) Shortest answer wins. Happy coding :-) [Answer] ## bash etc. and Image Magick (136 chars) ``` for x in "$@";do convert "$x" -colorspace HSL -channel G -separate -scale 1x1 t.txt echo `sed "1d;s%.*#\(..\).*%\1%" t.txt` $x;done|sort ``` The way I see it, the easiest way to deal with the complexities of the Image Magick file format is to let Image Magick do it. `t.txt` seems to be the shortest possible filename which guarantees the correct output file format. The first 4 `"` could arguably be removed, but that would decrease robustness in the face of filenames with spaces in. Sample output: ``` $ ./cmpsat.sh img-sat.txt img-desat.txt rose: 24 img-desat.txt 69 rose: FE img-sat.txt ``` [Answer] ## J (~~96~~ ~~94~~ 92) ``` echo/:(+/@:(m%(m=.>./)-<./)"1@:>@:(".&.>)@:((': (\(.*?\))';,1)&rxall)@:(1!:1)@:<)&.>2}.ARGV ``` Takes input from the command line as .txt files. It can take any number of files, and outputs a list of indices from saturated to unsaturated, i.e.: ``` $ jconsole saturated.j saturated.txt desaturated.txt 0 1 $ jconsole saturated.j desaturated.txt saturated.txt 1 0 ``` I've simplified the normal formula a bit: it does not bother to normalize the RGB values to [0..1], it uses the sum of the saturation per pixel rather than the average, and it actually calculates the inverse of the saturation and then sorts up. As long as the images are the same size (which they are), this does not affect the sort order which is what it's about. Explanation: * `2}.ARGV`: the command line minus its first two elements * `&.>`: for each of these, do: * `(1!:1)@:<`: read file * `((': (\(.*?\))';,1)&rxall)`: use a regex to match the pixel values * `(".&.>)`: execute each match as J code. `(1,2,3)` becomes the list `1 2 3` so now we have the pixel values. * `>`: make a matrix from the list of lists * `"1`: operate on the rows of the matrix * `(m%(m=.>./)-<./)`: `MAX / (MAX - MIN)`, the inverse of the saturation * `+/`: sum * `/:`: sort up, so that the images are sorted in `S^(-1)` ascending, which gives the same order as `S` descending. * `echo`: output the list [Answer] ## Mathematica 92 215 **Edit** To work directly with the Magick files I had to make substantial revisions to my first try. --- **Filenames** Stored as variables, *x*, *y*. ``` x = "http://pastebin.com/raw.php?i=5f3B4uxP"; y = "http://pastebin.com/raw.php?i=VdjDm9HK"; ``` --- The following routine sorts image files by average saturation (least to greatest). (Spaces added for readability.) ``` i = Image; d = DigitCharacter; f[t_] := {Mean[Flatten[ImageData[ColorConvert[i[i[Partition[(StringCases[URLFetch[t], "rgb(" ~~ a : d .. ~~ "," ~~ b : d .. ~~ "," ~~c : d .. ~~ ")" :> ToExpression /@ {a, b, c}])/255., 64]]], "RGB" -> "HSB"]], 1][[All, 2]]], t} ``` **Usage** ``` Sort@{f[x], f[y]} ``` **Output** (saturation value, followed by filename). > > {{0.229977, "http://pastebin.com/raw.php?i=VdjDm9HK"}, > > {0.958346, "http://pastebin.com/raw.php?i=5f3B4uxP"}} > > > --- **Explanation** `URLFetch[x]` fetches the Magick textfile, the name of which is stored in `x` `StringCases[URLFetch[t], "rgb(" ~~ a : d .. ~~ "," ~~ b : d .. ~~ "," ~~c : d .. ~~ ")" :> ToExpression /@ {a, b, c}])/255., 64]]], "RGB" -> "HSB"]` finds the RGB values and, along with `Partition` converts them to the format Mathematica expects to find RGB files in. `ColorConvert` converts to `Hue-Saturation-Brightness` values. `Mean` and `[[All,2]]` find the mean saturation values for the file. [Answer] ## Brainf\*\*k, 117 - 25% = 87.75 Requires an interpreter with 8-bit wrapping cells (this is the most common type). ``` >+[,<++++[->--------<]>[>+<]++++[->++++++++<]>]>> >+[,<++++[->--------<]>[>+<]++++[->++++++++<]>]> [-<<<[-]>>>]<<<[.] ``` Just input the text render of the first image and the second image. Make sure the files end with the `NUL` character (ASCII value 0). If the first image is larger, it will output how much larger it is than the second one (in the ASCII value). If the second image is larger, nothing will be printed. ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 9 years ago. [Improve this question](/posts/812/edit) Find the number of [partitions](http://en.wikipedia.org/wiki/Partition_(number_theory)) of a positive integer n. Hope someone uses the explicit finite formula for the partition function defined in Jan Hendrik Brunier and Ken Ono paper [here](http://www.aimath.org/news/partition/brunier-ono). ``` Sample Input 8 Sample Output 22 ``` N is less than or equal to 1000. Write the complete program. More than anything I would like to see the different approaches. [Answer] ## Python (109 89) ``` n=input() s=0 l=[(n,n)] while l:a,i=l.pop(0);s+=a==0;l+=[(a-i,i),(a,i-1)]*(a*i>0) print s ``` [Answer] **Java Solution** ``` public class IntegerPartition { public static void main(String[] args) { int n = 8; //set integer here!! int[][] a = new int[n + 1][n + 1]; int i, j, k; for (i = 0; i < a.length; i++) { a[i][0] = 0; a[0][i] = 1; } for (i = 1; i < a.length; i++) { a[i][1] = 1; for (j = 2; j < a[0].length; j++) { k = i - j; if (k < 0) a[i][j] = a[i][j - 1]; else a[i][j] = a[i][j - 1] + a[k][j]; } } i--; int answer = a[i][i - 1]; System.out.println(answer + 1); } } ``` [Answer] ## Mathematica 11 chars Sorry, no need to implement the algorithm ``` PartitionsP ``` Usage ``` %[8] 22 ``` [Answer] # Ruby - 95 chars Based on Hoa Long Tam's [solution](https://codegolf.stackexchange.com/questions/812/partition-of-a-positive-integer-n/824#824) ``` s=0 l=[[n=gets.to_i,n]] (a,i=l.pop;a>0&&i>0&&l+=[[a-i,i],[a,i-1]];a==0&&s+=1)until l==[] p s ``` [Answer] # Perl, 92 chars Recursive solution using `p(k,n)` = number of partitions of `n` using numbers >= `k`. Uses dynamic programming and partitions 1000 in 2s on my machine. ``` sub p{my($k,$n)=@_;$c{$k,$n}||($c{$k,$n}=$k<$n?p($k+1,$n)+p($k,$n-$k):$n==$k)}print p(1,pop) ``` Ungolfed: ``` sub p { my ( $k, $n ) = @_; $c{$k,$n} || ( $c{$k,$n} = $k < $n ? p($k+1,$n) + p($k,$n-$k) : $n == $k ) } print p( 1, pop ); ``` [Answer] # Perl, 70 chars Since there was no time limit: ``` sub p{my($k,$n)=@_;$k<$n?p($k+1,$n)+p($k,$n-$k):$n==$k}print p(1,pop); ``` Partitions 50 in 2.3 s. [Answer] ## J, 72 Modified from the manual: ``` f=:[:(0<@-."1~>@{:)](,([:<@;(-i.)@#([,.(>:{."1)#])&.>]))@]^:[(<i.1 0)"_ ``` eg ``` #f 8 22 ``` [Answer] # APL, 23 characters [`{⍵=0:1⋄+/⍵(-∇¨⍨⊢⌊-)⍳⍺}⍨`](http://tryapl.org/?a=%7B%u2375%3D0%3A1%u22C4+/%u2375%28-%u2207%A8%u2368%u22A2%u230A-%29%u2373%u237A%7D%u2368%20%A8%u237320&run) [Answer] # Haskell, ~~51~~ 39 ``` f=(%1) 0%k=1 n%k=sum[(n-r)%r|r<-[k..n]] ``` the `%` function gets two parameters - `n` and `k`, and returns the amount of partitions of `n` at which every part is at least `k`. `%`'s definition works by choosing `r` to be the next part of the partition. we compute the amount of possibilities when this is the next part (note that all consequent parts must be bigger or equal to it) by a recursive call and sum all possibilities. ]
[Question] [ For this problem you are given an \$n \times n\$ matrix of integers. The task is to find a pentagon in the matrix with maximum sum. The pentagon must include part (or all) of the x and y axes as two of its sides starting from the top left cell. All the sides except one must be horizontal or vertical. The remaining side is at 45 degrees ( that is it goes up one for each step to the right). This picture shows a matrix with a pentagonal part shaded. [![enter image description here](https://i.stack.imgur.com/As0Oi.png)](https://i.stack.imgur.com/As0Oi.png) Either one or two of the sides can have length zero, as in this example where two zero length sides have turned the pentagon into a triangle. This is an optimal triangular solution for this matrix but may not be an optimal pentagon. [![enter image description here](https://i.stack.imgur.com/1RVRm.png)](https://i.stack.imgur.com/1RVRm.png) Or this example where one zero-length side has turned a pentagon into a rectangle. This happens to be the optimal rectangle but may not be an optimal pentagon. [![enter image description here](https://i.stack.imgur.com/Zwz2E.png)](https://i.stack.imgur.com/Zwz2E.png) ``` [[ 3 0 2 -3 -3 -1 -2 1 -1 0] [-1 0 0 0 -2 -3 -2 2 -2 -3] [ 1 3 3 1 1 -3 -1 -1 3 0] [ 0 0 -2 0 2 1 2 2 -1 -1] [-1 0 3 1 1 3 -2 0 0 -1] [-1 -1 1 2 -3 -2 1 -2 0 0] [-3 2 2 3 -2 0 -1 -1 3 -2] [-2 0 2 1 2 2 1 -1 -3 -3] [-2 -2 1 -3 -2 -1 3 2 3 -3] [ 2 3 1 -1 0 1 -1 3 -2 -1]] ``` The winning criterion is asymptotic time complexity. E.g. \$O(n^2)\$ time. [Answer] # [Python](https://www.python.org), \$\mathcal O(n^2)\$ ``` def best_pentagon(grid): best = float("-inf"), -1, -1, -1 rects = [0] * len(grid[0]) pents = [(0, 0)] * len(grid[0]) for y, row in enumerate(grid): line = 0 lines = [line := line + value for value in row] rects = [rect + line for rect, line in zip(rects, lines)] pents = [ max((rect, y), (pent + line, z)) for rect, (pent, z), line in zip(rects, pents[1:], lines) ] + [(rects[-1], y)] best = max(best, max((pent, x, y, z) for x, (pent, z) in enumerate(pents))) return best ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVRLTsMwEBUsOYXVlQ22lMQsUKWeJLJQoE6JlDqR60Dbq7DpBu7AVTgN9viXllpJ5bHfvPfGnvTzezyYt0GdTl-TadnT7-3jWrboRe7M8yiVaTaDwhvdrcnyDtnhNtAKtf3QGLxgnWoXhCJWxhdAWr6anUXVhUD3qJeewUYEth0vbOOCooJcxbSDRgeK9PCBOoWkmrZSN0bOrbjRd0papuJsAbhhZ7nyiAf03vSTBFY_s6SWW6S8ZNlNLB7SHNzF1Ic259iNGKB-aUcyQ6oqrbixbfYYe46DPSjsUIGeoiMhZ-CsBzgHuCoNUnW5FNFFYhGWu_awmpXCiWaH4e6cJTel3pxX2lN33EcCHvYzA-fHD8ok2NbSTFoBbWiemx93P-kQam7vl6LKNgYPr2sSG4d-KQT1QAjiw2JC5XMhjEgL5PCUnoXn7uMzwszkDZTwW0XwhW6i4ymnuISxMrJEb2UGJyCPOplpZo9VCfjfWfyG-LxcVmWtQBm4gkZCVrGMUNNcNdQi7kbdKYOvfN3E32D8G_gD) Returns a tuple `(sum, x, y, z)` for a pentagon summing to `sum` whose bottom row ends at \$(x, y)\$ and whose rightmost column ends at \$(x + y - z, z)\$. ### How it works A pentagon whose bottom row ends at \$(x, y)\$ is either * the rectangle with corner \$(x, y)\$, or * the union of the partial row \$(0, y)…(x, y)\$ with a pentagon whose bottom row ends at \$(x + 1, y - 1)\$. This leads to a straightforward dynamic programming solution. [Answer] # [Python](https://www.python.org), \$\mathcal{O}(n^2)\$ time (optimal) ``` def solve(n, grid): # Pad the given grid with zeros to form a right triangle. # Note that any pentagonal region in this triangle can be truncated # to a valid pentagonal region within the original grid, # by stripping away the padded zeros, # so if we solve the maximum pentagon problem within this triangle, # we get a valid solution for the grid. # This is done to simplify coding. It adds some constant factor # but doesn't change the overall time complexity. triangle = [row[:] for row in grid] for r in range(n-1): triangle[r] += [0] * (n-1-r) triangle.append([0] * (n-1-r)) m = n * 2 - 1 # size of the triangle # Calculate cumulative sums in two directions: rightward and downward. right_cumsum = [row[:] for row in triangle] down_cumsum = [row[:] for row in triangle] for r in range(m): for c in range(1, m - r): right_cumsum[r][c] += right_cumsum[r][c-1] for r in range(1, m): for c in range(m - r): down_cumsum[r][c] += down_cumsum[r-1][c] # We solve the pentagon problem by first forming a large triangle # containing the upper left corner, and truncating smaller triangles # from the rightmost and downmost ends. ans = float('-inf') for t in range(1, m+1): # From the cumulative sums calculated above, we can get the sums of # horizontal strips and vertical strips that form the triangle. # The cumulative sum of the horizontal strips gives all possible cutaways # from the bottom; that of vertical strips gives those from the right. # vertical_strips[k] == sum of k vertical strips from upper right # horizontal_strips[k] == sum of k horizontal strips from lower left vertical_strips = [0] + [down_cumsum[i][t-1-i] for i in range(t)] horizontal_strips = [0] + [right_cumsum[t-1-i][i] for i in range(t)] for i in range(1, t+1): vertical_strips[i] += vertical_strips[i-1] horizontal_strips[i] += horizontal_strips[i-1] triangle_sum = horizontal_strips[t] # Now, for each possible cutaway from the bottom, we will find the # smallest valid cutaway from the right (so we get the maximum sum # for the given triangle size and bottom cut size). # When k horizontal strips are cut, valid cuts from the right are # zero to t-k vertical strips (inclusive). # Minimum of these values can be preprocessed in O(m) via cumulative minimum. # To make sure that the top left cell is included, k goes up to t-1. for i in range(1, t+1): vertical_strips[i] = min(vertical_strips[i], vertical_strips[i-1]) for k in range(0, t): cur_area = triangle_sum - horizontal_strips[k] max_area = cur_area - vertical_strips[t-k] ans = max(ans, max_area) return ans ``` [Attempt This Online!](https://ato.pxeger.com/run?1=vVfBbuM2EEWv7k8MsAdLjWzEuz3spsipQIEeuu1hgT0YhkFLlMyNRAokFSf5lV5yaf-p_YP2K_pISjJtOUWLomsYsEXOvDccvhlSP__aPtq9ks-__SGaVmlLmslCNbNSq4asaDj14-7_bFbwkiout0K2nU1kejMjfDS3nZa0XgfnpfsR0iaLdxm9S6lUmrYkpMOuOLw2F4YCdttq51hpUfTYzlKrg7N1o2HQfYLlfD2nK5pn8-UnJWRirE4e0qX-1BmbvAnUD55HHVJnuJmnv3S2XLz9_UvuCI2q78GfUUT5in5iBdk9p0rc88BLB2H39MS1MmSVw22IkRbVHqnRAquo-bL3fq8shzuzxOQjtVxaVinJauSpEkq6cOxemNGPciZpBxfdyZxZXvQ44GF0z2qwT0FcPB6Ik0IYwk25QLPeefdISIZoWyErYgf26E1bVhS8COsYLI0iUdKBh1x4s4Y9iKZrRlokW-1q3hxZo_AHHCBU3I4hA62zLlK3Bz6ZiG5I0QcHgG-hJHfrNFBZLcpHyhWUUy3pewAVhQEKJJgraSyTlkqWW6WHFXYW_tzIuaV873QUsnHPNavrIN5cAZc_CPsYmMeU39IakljfbM4FtjmqLtLnYpUelTeArPWGrgB0vaGvyNksdDoxWrIWWSySE6tg1iAKicHXtKCV2wjxhPBLv4rBfdYv9ltW510NcVDeNe4PlEmma4xX00FRITTPXb7NTZDlgekCAiyQo4N0DyEDfm4LEDhfzsJAHTLhvP-F-Vnimihtbio_Tq0yJGBBOrI4jw8JXuc-x5PRxeoinwN9mfISX7S-I93JIKgwPGzEx7hOJvWBqiuFNtY3CF95VDNdRfsZUKBoy4R0Fg6ng0Y01byEkpWWXGd-5_qG4KxMA03DZsAxPVDo04DwGWqUseOe-wdIz4SNZ9JgA8taMXTNhZDlPB0zaE8zeBWr_RV9N3CcSy8fRAmh7VB3mesBrpm5PuAcvJUqI6w9mtWTW3wd2pPx4aJkrciPY755-h4b18IywvkwCWeonCmD6-LgQU9olTFi5zpuZ11PNBHimMmdslY134QgAHoeXIDDqWn4WfqXswhvcNsGt_Xdhm5vh0DvJqgeKejAY13M2QtY0yV7tFodelWNYGdBUeheV7SOFS82a4s2JUKZi6M2bLoZkSZBHbFOijUgrf8e7GwKGrQnGrwQukNEpU5Gh8bwYpy944Xx2HXQ3Db0vam13cSb_V4dMr8KzvL9RGbn2vJ1chAQZCmkv2lEUKHSUbrhGJ1AhDtHglO7P3DjAxvRxpIeTl5_jRnPPn_OuLIL0TgKP5bGBfZxD5dL0mLarys7xmfOg4NJhOQuG-6Mt4up6hMh87oziO-E_Ae0xmYsadQZuDpuhotSqzkabs6NQeeBan7EOUP3gsUdoQkQJz1DIU93rlno_n7mu4tq-87LsSHuWuJCwi0pw_Ir3C9QlSH81fK_CvbWhZVMJ7KLOk5P6O6OdNegOyPLO71F2hkoTqS7uNg9TlyhncF1RFlMAsLunbqF8wTOCf5lI0oavxFgpr9tf_GnhPWbWf-GYDgvktV1OvMvEltMxW8Vs_41IEzi0T-NV_V-OJ3NHObq-vofouIOiReZW38zTF5CzfpppMDb9yyvPwvL15-F5e3_zBK2_Pk5_P4F) This is an art of cumulative operations lol. This is optimal in terms of asymptotic time complexity because you need \$\mathcal{O}(n^2)\$ time just to observe all the elements in the matrix. ]
[Question] [ Write an irreducible proper quine, i.e. a program that prints its own source code, which can't be reduced by removing characters to a shorter program with the same constraints. Eg. the python quine: ``` var='var=%r;print(var%%var)';print(var%var) ``` can be reduced to the quine ``` v='v=%r;print(v%%v)';print(v%v) ``` thus it is not irreducible, although the program below is. [Standard Loopholes apply](https://codegolf.meta.stackexchange.com/q/1061), [this](https://codegolf.meta.stackexchange.com/a/10033) and [this](https://codegolf.meta.stackexchange.com/a/5337) in particular. The longest answer wins. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/blob/version-2), \$25 \times 955 ^ {411 ^ {172 ^ {8743 ^ {10193 ^ {8744 ^ {...}}}}}}\$ bytes ``` ...W:k⟇Cƒeε\‹*`k⟇Cƒe`$+∑$C∑+ ``` The exponentiation tower part of the byte count is the result of evaluating `k⟇Cƒe`, which is equal to reducing the character codes of each character in the vyxal codepage by `**`. The number is too large to compute, but an expression can be found [here](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCJr4p+HQ2AqKmBqIiwiIiwiVzpr4p+HQ8aSZc61XFzigLkqYGvin4dDxpJlYCQrJEPiiJErIl0=). Replace the `...` with `k⟇Cƒe` followed by \$955^{411^{172^{...}}}\ - \text{chr}(x)\$ `‹`s for `x` in `W:k⟇Cƒeε\‹*`k⟇Cƒe`$+∑$C∑+`. --- The idea here is this base quine: ``` 87 58 51 50 67 106 36 67 8721 43W:32Cj$C∑+ ``` It's been modified to have the numbers be replaced with decrementing that big power tower each time. **Irreducibility** Removing any character from `k⟇Cƒe` fails to push a number, and starts performing unexpected behaviour. Removing any of the `‹`s fails to decrement the number adequately. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 80841 bytes ``` […]ẈỌv ``` [Try it online!](https://tio.run/##7dwxDYAwEIZRKwjogJ@mIwvpTIIDBhSBGpQcAwIYGErSlyfgcgK@f55qXSPymAAAAAAAAAAAAAAAAAAAAJorKXd1FwAAAAAAAAAAAAAAAAAAAOBh/QAAAAAAAAAAAAAAAAAAAPgvRTQAAAAAAAAAAAAAAAAAAMCbVmW2IhwAAAAAAAAAAAAAAAAAAABoq6/1g@/fluvYrnNfhogb "Jelly – Try It Online") A full program that is a quine. The `…` above is actually a list of lists of zeros with the following lengths: `[7806, 59, 8318, 7816, 7884, 59, 8318, 118, 32]`. These are then converted to Unicode code points which encode the following: `Ṿ;⁾ẈỌ;⁾v` This is then called with the original list of lists of zeros as its argument. This code unevals the list and appends two two character strings that consist of the bit outside of the list. Note the space at the end of the program (and the last 32 byte member of the list) is needed because of nesting two-character strings within the main string. (`”` would terminate the string.) [Answer] # Charcoal, 7200285678457 bytes ``` ≔...θ´≔θθ⍘Lθ´L´⍘´≔´´´θ ``` `...` represents 7200285678438 `´`s. No online link for obvious reasons. Explanation: ``` ≔...θ ``` Assign 3600142839219 `´`s to the variable. (`´` is Charcoal's quote character, so it needs to be doubled to quote itself.) ``` ´≔ ``` Output the literal string `≔`. ``` θθ ``` Output two copies of the 3600142839219 `´`s. ``` ⍘Lθ´⪫´L´⍘´≔´´´θ ``` Convert 3600142839219 to base 5 using a custom character set, so instead of resulting in 432441043031323334 you get `θ´≔θθ⍘Lθ´L´⍘´≔´´´θ`. [Answer] # Java 7, 172 bytes ``` class M{public static void main(String[]a){String s="class M{public static void main(String[]a){String s=%c%s%1$c;System.out.printf(s,34,s);}}";System.out.printf(s,34,s);}} ``` Takes advantage of the Java version to make things as long as possible. In Java 8+ you can shorten `class M{public static void main` to `interface M{static void main`; in Java 10+ you can shorten `String s=` to `var s=`; and in Java 5 and 6 you can shorten `class M{public static void main(String[]a){` to `enum M{M;{` by abusing a bug. [Try it online.](https://tio.run/##y0osS9TNL0jNy0rJ/v8/OSexuFjBt7qgNCknM1mhuCSxBEiV5WemKOQmZuZpBJcUZealR8cmalZDmArFtkrkaFJNVi1WNVRJtg6uLC5JzdXLLy3RKwDKlaRpFOsYm@gUa1rX1irhlf3/HwA) (This TIO uses Java 8, but in Java 7 it's irreducible.) **Explanation:** ``` class M{ // Class public static void main(String[]a){ // Mandatory main method String s= // String `s`, containing: "class M{public static void main(String[]a){String s=%c%s%1$c;System.out.printf(s,34,s);}}"; // the source code, where the `""` are replace with `%c%s%1$c` System.out.printf(s, // Print String `s` with formatting: 34, // Where the `%c` and `%1$c` are replaced with `"` (codepoint 34) s);}} // and `%s` is replaced with String `s` ``` ]
[Question] [ What general tips do you have for golfing in 1+? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to 1+ (e.g. "remove unnecessary whitespace" is not an answer). Please post one tip per answer. [Answer] # Subroutines can have empty names `(|1+1<)` is a valid definition for a subroutine, invoked as `()`. [Answer] # Instead of pushing 0 and compare, do something to other numbers As 1 is the only literal in 1+ and there's no minus operation, pushing 0 would be expensive (`11+1<`). A better choice would be change other numbers, so 1 becomes a "relative" 0. For example, if you want to flip a bit, instead of `11+1<<`, you can `1+1<`. [Answer] # Use comments for conditionals Found this while exploiting interpreter features. Apparently Parcly Taxel thinks comments and conditionals are similar because both of them begins with "co". The comment indicators `[]` are actually instructions because there's no such thing called parsers in 1+. This trick can sometimes save you and a few bytes from the comparison mess. Found while exploiting interpreter features, then [made a Truth-Machine](https://codegolf.stackexchange.com/a/208961/87986) with it. ]
[Question] [ [Inspired by this game](https://bubmet.itch.io/intercept) # Challenge: Given an ASCII art string representing a number, output that number. Example: ``` Input: &&&& ##### .====.. .&&& $$$$$. %% %% % % . +. . @@@ . @@ . = . = . ???? +++. && &&. % % = = $$$ . @@@@@ # # . ===. .$$$$$ .????. Output: 1306 ``` ``` Input: ==== .$$.. &&&&&&. .@@@@ ????? +++++ &. & $$ %% %% && && $$$ .==. @@ . @@ @@ . ?? . ### . @ @ . == $$$$$$$$ ??. .?? . .@@@. .%%. == .$$ &&&&& . $$$$$. . .% . @@ . Output: 18743 ``` Periods are interference, you can ignore them The complete list of numbers: ``` &&&& % % = = % % # # ???? &&&& $$$$$ @@@ +++ $$$ $$$$$ ##### ++ ++ # ## @@ @@ ??????? ##### %% %% @@ && && @@@@@ @@@@ %% %% @@ @@ $$$$$$$$ $$ @@ ###### $ #### + ? $$$$$ &&& + ???? = = === &&&&&& $$ @@ == == % $$ & & == @ @ %% &&&& @ @ &&&& $ & + ``` # Rules: * Your input is a **string** unless your language doesn't have a string type. * The input is guaranteed to be exactly 6 characters "high." Numbers such as 8 and 3 have a whitespace buffer UNDER the number. * If you write a function, it MUST return a numerical type. * The ASCII art can be composed of ANY printable characters in no particular order (remember, you can ignore periods). * No standard loopholes. * Your program must handle any arbitrary ASCII number of reasonable length (as long as the result fits within a 32-bit signed integer). * Input is guaranteed valid, undefined behavior is allowed with bad input. * This is code-golf, shortest program wins. More tests: ``` $$$$ ###### @@@@ . . .%%%% ##### ##### $ . =====.. . ## ## ++ ++ +++ ####. +++. == == # ## === . + ### . ========. @@ .&&& . . ? . . @@@ ## @@ . %%%%% $$$$$ ##### @@ ??????? > 15142 .&&&&. ?????? @@@@@ .++++ @ @ + . == == %% %% .&&&&. ####.. = == . ++ ++ .. $ & $$ $$$$$$$$. . &. . # && . ## +. . ##### $$$$$$$ .== > 9524 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~35~~ ~~33~~ 34 bytes ``` Ỵe€€⁾ .¬ZḄṣ0§ḟ0%29“h½sØ?X’ḃ26¤iⱮ’Ḍ ``` [Try it online!](https://tio.run/##TY@9CsIwFIX3PsWFJlmES@kgOJT6GOJeUOnm5FZ/Rh9AQXBQcCmC4FARHeKTpC8Sc5P05yMk55Kce08WWZ6vtFbvZ1ZvSlrrL6Asp6raqdclkjdVnSMej@riNJOf5e@QTuriqKptPJTXef2422qvtQZIDEAgY4hWgbDYAscGEilhzgAGhHuHIKCDMdo595sQthUaC90xNyVJsHOY1uiOVoObYmQYhu7WLu/yYZmHniMgeYyFwrrUnLdTvAOaTzb/M0XgGyH0MpG7Vb2Qjj8 "Jelly – Try It Online") When I started writing this, The question didn’t specify that the width of digits was fixed, so my answer doesn’t make that assumption. Input is now a string (which costs a byte over having a list of strings). Output is an integer. Explanation: ``` Ỵ | split at new lines e€€⁾ . | For each character check whether it is a | full stop/space or something else ¬ | invert this Z | transpose Ḅ | convert from binary to decimal (one number per column of input) ṣ0 | split at zeroes (blank columns) § | take the sum of each digit ḟ0 | filter out remaining blank columns %29 | take this number mod 29 “h½sØ?X’ḃ26¤iⱮ | look each digit up in a compressed list | [18, 23, 6, 5, 1, 19, 13, 21, 8, 25] ’ | subtract one Ḍ | convert to decimal ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 34 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` '.ð:.B€SðÊøJC0¡O0K29%•!aˆM©м•₂вskJ ``` Port of [*@NickKennedy*'s Jelly answer](https://codegolf.stackexchange.com/a/181748/52210), so make sure to upvote him! PS: Knowing the width of the digits is pretty useless if the amount of space columns in between digits can vary.. [Try it online.](https://tio.run/##yy9OTMpM/f9fXe/wBis9p0dNa4IPbzjcdXiHl7PBoYX@Bt5GlqqPGhYpJp5u8z208sIeIPtRU9OFTcXZXv//KykpKSioAYECGCiDAIihZwsEenpgJlCWS0EFBMB8VVU4AeYqgES19RT0uIC0g4ODAlgAzAaxbCEESNQeCECKtLW1wUrAtqqp6cFNAgGQUluQKqB9YOtBZoJMBboOSoAMBLqOS0EP7CoFFKAHskUP6C8A) **Explanation:** ``` '.ð: '# Replace all dots with spaces .B # Split on newlines €S # Convert each line to a list of characters ðÊ # Check of each character if it's NOT equal to a space ø # Zip/transpose; swapping rows/columns J # Join each column together C # Convert each from binary to an integer 0¡ # Split on 0s O # Sum each inner list 0K # Remove 0s 29% # Take modulo-29 on each •!aˆM©м• # Push compressed integer 102583844953589 ₂в # Converted to Base-26 as list: # [18,23,6,5,1,19,13,21,8,25] sk # Index the earlier number into this list J # Join everything together (and output implicitly) ``` [See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•!aˆM©м•` is `102583844953589` and `•!aˆM©м•₂в` is `[18,23,6,5,1,19,13,21,8,25]`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 29 bytes ``` ⁾. yỴ=⁶s€⁵ZẎ€Ḅ:434ị“¡£:E’Œ?’¤ ``` A monadic Link accepting a list of characters which yields a list of digits, or a full program accepting a single text argument which prints the digits. (Requires padding on the right with spaces such that each digit has a width of ten characters, including the right-most one, which I believe is OK.) **[Try it online!](https://tio.run/##TZC/CsIwEMb3PsUH/bMUbrFTobSLL@HuIt2curXiJji4CS6io6OKWHAo@CDJi8TLpX/8Anchd798uayWZVkZo5sPoVLtPdPNc603N908Fuq95516bdNklqh2p@tTd@4u6VzXx@8h59hdjTFAwIKVL5JtwQKIFyhkjWXOHqa@wHaIMiuy/ZCaDXEMFzzJ8egyQHxGPT0E36GCZHIC8Yh7RJyp97OW7rlwCEVR1BOEHG6EwpXHCyaCGAmH@YLxI/4GxNCcOwE/ "Jelly – Try It Online")** ...or try the other test case [here](https://tio.run/##TY6xCsIwFEX3fMWFtlkKb7FTIejiT7i7SDenbq24CQ5ugovo6KgiFhwKfkjyIzF5aaRnuLkh992X1bKqamtN@yHUursr0z7XZnMz7WOh33vn9GtbFpNCdzvTnPpzfynnpjl@D1On/dVaC5IOgmPKeIeZhx0odwACfGfJQeENSkVBlgURo8bEQSGrOOe9b/MiXDchRURGk6bDESDBY3LYSUjigPz/g3f5RuTEGV6djHtijtw3fg "Jelly – Try It Online"). ]
[Question] [ > > This proposal had few attention for 8 months (though an answer was posted in the sandbox at that time), so I decided to post it anyway. > > > ## Introduction [Napier's bones](https://en.wikipedia.org/wiki/Napier%27s_bones) is a calculation tool, which helps speeding up the calculation of multiplication, division and digit-by-digit square root extraction by turning n-digit-by-1-digit multiplications into table look-ups. Napier's bones consists of rods marked with the multiples of a single-digit number, and a board with a set of numbers on the left, on which the rods can be arranged. The board and the rods look like this (All appearances of the rods are in the **Sample** section): ``` Rod Board +-----------------------------------------------+ | +------------------------------------------+| +---+ | | || | 4 | | | || +---+ | | || |0 /| | | || | / | | 1 | || |/ 4| | | || +---+ | | || |0 /| | | || | / | | 2 | || |/ 8| | | || +---+ | | || |1 /| | | || | / | | 3 | || |/ 2| | | || +---+ | | || |1 /| | | || | / | | 4 | || |/ 6| | | || +---+ | | || |2 /| | | || | / | | 5 | || |/ 0| | | || +---+ | | || |2 /| | | || | / | | 6 | || |/ 4| | | || +---+ | | || |2 /| | | || | / | | 7 | || |/ 8| | | || +---+ | | || |3 /| | | || | / | | 8 | || |/ 2| | | || +---+ | | || |3 /| | | || | / | | 9 | || |/ 6| | | || +---+ | | || | +------------------------------------------+| +-----------------------------------------------+ ``` ## Challenge This challenge is to write a function or program which receives a natural number as input, and outputs the arrangement of the rods, as if a calculation were in progress, on the board as an ASCII art, according to the input, having the code as short as possible. The top row of the rods will assemble that number you have inputted. ## Requirements * The input can be an argument of the function or program, or an input from STDIN. Please indicate your choice of input format. Accepted formats are as follows: + An integer representing the number; + A string representing the number; or + A list of characters representing the digits of the number. * The output can be directly printed to STDOUT, or returned from the function as a string. Please refer to the **Sample** section. * You can assume that the input will always be a valid representation of the number, i.e. the number matches the regex `[1-9][0-9]*`. * You must support all valid inputs in the range `[1, 2147483648)`. Larger ranges are absolutely welcomed. * You must leave no space around the rods. * Standard loopholes apply. ## Sample Input/Output Input: `1234567890` Output: ``` +-------------------------------------------------------+ | +--------------------------------------------------+| | |+---++---++---++---++---++---++---++---++---++---+|| | || 1 || 2 || 3 || 4 || 5 || 6 || 7 || 8 || 9 || 0 ||| | |+---++---++---++---++---++---++---++---++---++---+|| | ||0 /||0 /||0 /||0 /||0 /||0 /||0 /||0 /||0 /||0 /||| | 1 || / || / || / || / || / || / || / || / || / || / ||| | ||/ 1||/ 2||/ 3||/ 4||/ 5||/ 6||/ 7||/ 8||/ 9||/ 0||| | |+---++---++---++---++---++---++---++---++---++---+|| | ||0 /||0 /||0 /||0 /||1 /||1 /||1 /||1 /||1 /||0 /||| | 2 || / || / || / || / || / || / || / || / || / || / ||| | ||/ 2||/ 4||/ 6||/ 8||/ 0||/ 2||/ 4||/ 6||/ 8||/ 0||| | |+---++---++---++---++---++---++---++---++---++---+|| | ||0 /||0 /||0 /||1 /||1 /||1 /||2 /||2 /||2 /||0 /||| | 3 || / || / || / || / || / || / || / || / || / || / ||| | ||/ 3||/ 6||/ 9||/ 2||/ 5||/ 8||/ 1||/ 4||/ 7||/ 0||| | |+---++---++---++---++---++---++---++---++---++---+|| | ||0 /||0 /||1 /||1 /||2 /||2 /||2 /||3 /||3 /||0 /||| | 4 || / || / || / || / || / || / || / || / || / || / ||| | ||/ 4||/ 8||/ 2||/ 6||/ 0||/ 4||/ 8||/ 2||/ 6||/ 0||| | |+---++---++---++---++---++---++---++---++---++---+|| | ||0 /||1 /||1 /||2 /||2 /||3 /||3 /||4 /||4 /||0 /||| | 5 || / || / || / || / || / || / || / || / || / || / ||| | ||/ 5||/ 0||/ 5||/ 0||/ 5||/ 0||/ 5||/ 0||/ 5||/ 0||| | |+---++---++---++---++---++---++---++---++---++---+|| | ||0 /||1 /||1 /||2 /||3 /||3 /||4 /||4 /||5 /||0 /||| | 6 || / || / || / || / || / || / || / || / || / || / ||| | ||/ 6||/ 2||/ 8||/ 4||/ 0||/ 6||/ 2||/ 8||/ 4||/ 0||| | |+---++---++---++---++---++---++---++---++---++---+|| | ||0 /||1 /||2 /||2 /||3 /||4 /||4 /||5 /||6 /||0 /||| | 7 || / || / || / || / || / || / || / || / || / || / ||| | ||/ 7||/ 4||/ 1||/ 8||/ 5||/ 2||/ 9||/ 6||/ 3||/ 0||| | |+---++---++---++---++---++---++---++---++---++---+|| | ||0 /||1 /||2 /||3 /||4 /||4 /||5 /||6 /||7 /||0 /||| | 8 || / || / || / || / || / || / || / || / || / || / ||| | ||/ 8||/ 6||/ 4||/ 2||/ 0||/ 8||/ 6||/ 4||/ 2||/ 0||| | |+---++---++---++---++---++---++---++---++---++---+|| | ||0 /||1 /||2 /||3 /||4 /||5 /||6 /||7 /||8 /||0 /||| | 9 || / || / || / || / || / || / || / || / || / || / ||| | ||/ 9||/ 8||/ 7||/ 6||/ 5||/ 4||/ 3||/ 2||/ 1||/ 0||| | |+---++---++---++---++---++---++---++---++---++---+|| | +--------------------------------------------------+| +-------------------------------------------------------+ ``` ## Victory Condition This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 78 bytes ``` B⁺⁷×⁵Lθ⁴³↓↘↘P↓⭆⁹◧I⊕ι⁴↗↗B⁺²×⁵Lθ⁴¹↘Fθ«B⁵¦³↘→←ι↙FE⁹×Iι⊕κ«UR⁵↘↘I÷κχ↘↑I﹪κχ↑↙³»M⁵±³⁸ ``` [Try it online!](https://tio.run/##fZBRT4MwFIWf2a/oY0lqMsZwm77pXkyGIVN@QAN30KxrEQqamP12bAtjoujjPbnnnu/cJKdlIilv2wf5gSNeV3hF0Cs7QYUDgnYgMpXjN9d1CVr67v0slA3gu618F6Nhz7JcTSs1V6womVCdTtCL0lMW0gJvCIpouoODwo@0UvhJJCWcQChIMbOROvhyNC7GIdd5QF/8ie5Nsh1kifQG@pw55oZ2mYrO78VeGsao62PICWJjjxGNYo/3LTsq25FpnO89jxrQEjh7SBQVGQccGP8UxiV4EAnqH6e2rGEp4CNB3tx@7d8DcdE7Q5nWXE7Y4uJnYNfWfujcF9Yfe4aMKsD@2pjPbest/GVwu1pv5u1Nw78A "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` B⁺⁷×⁵Lθ⁴³↓↘↘ ``` Draw the outer box. ``` P↓⭆⁹◧I⊕ι⁴↗↗ ``` Pad the digits `1-9` and print them vertically. ``` B⁺²×⁵Lθ⁴¹↘ ``` Draw the inner box. ``` Fθ« ``` Loop over the bones. ``` B⁵¦³↘→←ι↙ ``` Draw the small box at the top of the bone with the current digit. ``` FE⁹×Iι⊕κ« ``` Multiply the current digit with the digits `1-9` and loop over the result. ``` UR⁵↘↘I÷κχ↘↑I﹪κχ↑↙³» ``` Draw a square and insert the digits of the product and the diagonal line. ``` M⁵±³⁸ ``` Move to the start of the next bone. [Answer] # [Python 2](https://docs.python.org/2/), ~~424~~ ~~314~~ ~~304~~ ~~305~~ ~~303~~ 298 bytes ``` n=map(int,input());l=len(n) a,b='+'+'-'*5*-~l+'+','| +'+'-'*5*l+'+|' x='+---+'*l y='| |%s||\n' j=''.join print'\n'.join([a,b,j([(y+'| %s |%s||\n'+y+y)%(j('|%d /|'%(c*i/10)for c in n),i,'| / |'*l,j('|/ %d|'%(c*i%10)for c in n),x),3*y%(x,j('| %s |'%c for c in n),x)][i<1]for i in range(10))+b,a]) ``` [Try it online!](https://tio.run/##XY7bSsRADIbv@xS5GZI5WfcgCjpPUnvR7a46paalW6EDg69eZ4osKLlJPr7kzxjmj4H368rusxnJ82w8j18zSfncu/7CxLJozMmhTmVRPSj73efeYASAG80sYrEk0VqrUfVFcJsSxTXGV8aic4h33eC5GKcUhIltI1UpwHRUUdBpQ1xvKzroIAV1hFGcoYwoqFW@3N3Lt2GCFjwDS@PzKyXElGmyWoI4/6rin7pIc1BB0LKJWxSKFv4qdeVfdnVmPrOp4fcLpUNSn0xTy3XFw/HpcX/EHw "Python 2 – Try It Online") -2 bytes, thanks to Kevin Cruijssen [Answer] # JavaScript (ES8), ~~250~~ 241 bytes Takes input as an array of digit characters of any size. ``` s=>[...'0123'.padEnd(40,2456)+210].map((v,y)=>`+----0-+,| +0+|,71||,72||,73||,| 6 |4||,75||`.split`,`[v].replace(/\d/g,n=>[Y=y>>2,'| |'][n-6]||s.map(X=>`-----+---+| ${X} ||${X*Y/10|0} /|| / ||/ ${X*Y%10}|`.substr(n*5,5)).join``)).join` ` ``` [Try it online!](https://tio.run/##NY/BboMwEETv/QofWmHHxjYESHuAW/8hEUWyAyQiogZhihR1@XZqI3UPs7Nz2Kd56EXbeurGOTRD0263fLN5UXLOAxnFx4CPuvk0DU4ki5M0IzSOZMW/9Yjxwp4kLxQN3ciQMkAIUUmBnSJwEns5OgGUIUj8lQIobse@mxVT5VLxqR17XbdYfDXizowDX/JnUcQs8M8gqEoTZhWA3YlnR/Ow0CMpoNff84oA3DpcRCRBrkgAIOEygfb0LZKrR/5c7Txhc0hZSgh/DJ1R6t@8qK0ejB36lvfDHd/wXt51d3VP7x8yqAjZ/gA "JavaScript (Node.js) – Try It Online") ### How? The board consists of 43 rows of 7 distinct types, which are represented below with an ID in \$[0..6]\$: ``` 00: +---------------+ --> 0 >--- outer board header 01: | +----------+| --> 1 >--- inner board header 02: | |+---++---+|| --> 2 \___ rod header 03: | || X || X ||| --> 3 / 04: | |+---++---+|| --> 2 \ 05: | ||X /||X /||| --> 4 \__ first row 06: | X || / || / ||| --> 5 / 07: | ||/ X||/ X||| --> 6 / .. . . .. . . 36: | |+---++---+|| --> 2 \ 37: | ||X /||X /||| --> 4 \__ last row 38: | X || / || / ||| --> 5 / 39: | ||/ X||/ X||| --> 6 / 40: | |+---++---+|| --> 2 >--- rod footer 41: | +----------+| --> 1 >--- inner board footer 42: +---------------+ --> 0 >--- outer board footer ``` The code `'0123'.padEnd(40,2456)+210` (see [this tip](https://codegolf.stackexchange.com/a/170840/58563)) generates the following string of 43 row IDs over which we are going to iterate: ``` "0123245624562456245624562456245624562456210" ``` Each ID is replaced with a temporary encoded string which, in turn, contains other IDs in \$[0..7]\$: ``` ID | String ----+------------ 0 | "+----0-+" 1 | "| +0+|" 2 | "71||" 3 | "72||" 4 | "73||" 5 | "| 6 |4||" 6 | "75||" ``` Finally, each new ID is replaced with a 5-character string which is appended as many times as there are digits in the input array, except the last two ones which are just inserted as-is: ``` ID | String | Repeated ----+-------------------+---------- 0 | `-----` | Yes where: 1 | `+---+` | Yes X = horizontal digit 2 | `| ${X} |` | Yes Y = vertical digit 3 | `|${X*Y/10|0} /|` | Yes 4 | `| / |` | Yes 5 | `|/ ${X*Y%10}|` | Yes 6 | Y | No 7 | `| |` | No ``` [Answer] # Java 11, ~~352~~ ~~344~~ ~~340~~ 309 bytes ``` a->{int l=a.length,i=0;String Z="+"+"-".repeat(l*5),A=Z+"-----+\n",Y="| ",B=Y+Z+"+|\n",X="||\n",D=Y+="|",C=Y+"+---+".repeat(l)+X,r=A+B+C,t,u,v;for(int d:a)D+="| "+d+" |";for(r+=D+X;i++<9;r+=C+t+X+u+X+v+X){t=v=Y;u="| "+i+" |";for(int d:a){d*=i;t+="|"+d/10+" /|";u+="| / |";v+="|/ "+d%10+"|";}}return r+B+A;} ``` -4 bytes thanks to *@ShieruAsakoto* -32 bytes thanks to *@ceilingcat*. [Try it online.](https://tio.run/##jVHLTsMwELz3K1aWkBLWTVtKKWCM1McVLlxSHgeTBDAEt3KcIJTm28M6BPWKLVvrmR3vavZdVWr4nn60Sa6KAm6UNvUAQBuX2ReVZHDrnwB3zmrzCklAzMMTqFAQ3AzoKpxyOoFbMCChVcPrmlIglyrKM/Pq3riWY9HL7yVD2kMW2WyXKRfkx7OQL@Q9YX7ho2F8I9meKjK@lBskBvcejQntgjWhFDO@ooChVx2@CzHmVi5wiSvueMkr8bK1vmdIL1W49kJgmCKDPesoi3KNsdCIVxeCHit0GGNJp8I4rJ2s5EaUvzJ9kP39WKfHUgvXNYTpaDKmlBHllF2lkU@vfDjyVY88TUjT2MyV1oClPheiaYX3cVc@5@Rjb2e11Sl80jSCX@s6z/tRfBcu@4y2pYt2RLncBCZKApN9QTecesrn/ISf0T6lM@azJuzG9Q/phIRTks1IOOfn/IKPe3EzaNof) **Explanation:** ``` a->{ // Method with digit-array as parameter and String return-type int l=a.length // Amount of digits in the input i=0; // Index-integer String Z="+"+"-".repeat(l*5), // String `Z` for the "+------..." of the four lines A=Z+"-----+\n", // String `A` for the "+---...---+" of the first and last lines Y="| ", // String `Y` for "| " B=Y+Z+"+|\n", // String `B` for the second and next to last lines X="||\n", // String `X` for "||" + newline D=Y+="|", // String `D` starting with "| |" // (and change `Y` to this as well now) C=Y+"+---+".repeat(l)+X, // String `C` for the third and fifth lines r=A+B+C, // Result-String, starting at the first three lines t,u,v; // Three temp Strings, uninitialized for now for(int d:a) // Loop over the input-digits D+="| "+d+" |"; // Append `D` with "| d |" where `d` is the digit for(r+=D+X; // Append `X` to `D`, and then `D` to the result-String i++<9; // Loop `i` in the range [1, 9] r+= // After every iteration, append the result-String with: C // line `C` +t+X // and line `t` with a trailing `X` +u+X // and line `u` with a trailing `X` +v+X){ // and line `v` with a trailing `X` t=v=Y; // Reset `t` and `v` to `Y` u="| "+i+" |"; // and `u` to "| i |" where `i` is the `i` from the loop for(int d:a){ // Inner loop over the input-digits d*=i; // Multiply the current digit with `i` t+="|" // Append `t` with "|" +d/10 // and the first of two digits for the multiplication result +" /|"; // and " /|" u+="| / |"; // Append `u` with "| / |" v+="|/ " // Append `v` with "|/ " +d%10 // and the second of two digits for the multiplication result +"|";}} // and "|" return r // And finally return the result-String, +B+A;} // appended with lines `B` and `A` ``` ]
[Question] [ At the Code-Golf™ Psychological Society, you are delighted to present a new method of measuring mental age: *Abstract Capacity™*. To get the *Abstract Capacity* of a person, you take their actual age divided by 4, take their IQ divided by 9, then add the two values together. Then, round this sum down to find the *Abstract Capacity*. **Challenge** Write a program, given an actual age *A* and an IQ of *I*, produces the *Abstract Capacity* using those values. The program should also print how older (age) or how smarter (IQ) someone should be in order to raise their *Abstract Capacity* by 1. An input will always look something like > > *A* *I* > > > and an output will always look something like > > *AC* *A'* *I'* > > > where AC, A' and I' respectively denote the *Abstract Capacity*, how older someone has to be to raise their *Abstract Capacity*, and how smarter someone has to be to raise their *Abstract Capacity*. **Examples** **Input** ``` 13 43 ``` **Output** ``` 8 4 9 ``` **Input** ``` 92 5 ``` **Output** ``` 23 2 4 ``` **Input** ``` 40 17 ``` **Output** ``` 11 1 1 ``` **Rules** Your code must be able to find the *Abstract Capacity* for any given *A* and *I* when 1 < *A*,*I* < 400. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins! [Answer] # [Python 2](https://docs.python.org/2/), 61 bytes ``` def f(a,i):r=a*9+i*4;print r/36,(r+44-i*4)/9-a,(r+39-a*9)/4-i ``` **[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI1EnU9OqyDZRy1I7U8vEuqAoM69EoUjf2ExHo0jbxEQXKKipb6mbCOIaA2ktS019oOj/NA1DYx0TY83/AA "Python 2 – Try It Online")** [Answer] # [Python 2](https://docs.python.org/2/), 50 bytes -1 byte thanks to Mr. Xcoder (`print` instead of `return`). ``` def f(a,i):x=a*9+i*4;m=x%36;print x/36,4-m/9,9-m/4 ``` **[Try it online!](https://tio.run/##RY07DoMwEAVrOMU2iN8iYuwgGQR3WSk42QKDLArn9I4DBc0U86R5@/f4bLYL4bUYMAUhl4OfqNI1V2pcJ5/Jftwd2wN8K3tUzdpq1JEqmM0BAVtwZN9LISR2ohzS5O/59koiiOcj4lyTq0YIjJA3c47RXc/hBw "Python 2 – Try It Online")** [Answer] # Pyth, 26 bytes ``` /K+*9Q*4E36-4/J%K36 9-9/J4 ``` **[Try it here!](https://pyth.herokuapp.com/?code=%2FK%2B%2a9Q%2a4E36-4%2FJ%25K36+9-9%2FJ4&input=13%0A43+&debug=0)** [Answer] ## JavaScript (ES6), ~~67~~ 50 bytes ``` f= (a,i,r=a*9+i*4)=>[r/36|0,4-(r%36/9|0),9-(r%36>>2)] ``` ``` <div oninput=[ac.textContent,ea.textContent,ei.textContent]=f(a.value,i.value)>Age: <input type=number id=a><br>IQ: <input type=number id=i><br>Abstract Capacity: <span id=ac></span><br>Extra age needed: <span id=ea></span><br>Extra IQ needed: <span id=ei> ``` Edit: Although originally I was trying to verify @Mr.Xcoder's comment I ended up verifying @JonathanAllan's answer instead. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~21~~ ~~19~~ 18 bytes ``` 94S©*O36‰RĆÁ®÷®RαÁ ``` [Try it online!](https://tio.run/##AS0A0v8wNWFiMWX//zk0U8KpKk8zNuKAsFLEhsOBwq7Dt8KuUs6xw4H//1s5MiwgNV0 "05AB1E – Try It Online") **Explanation** Example for `input = [92, 5]` ``` 94 # push the number 94 S© # split to a list of digits and store a copy in register # STACK: [9,4] * # element-wise multiplication with input # STACK: [828, 20] O # sum # STACK: 848 36‰ # divmod 36 # STACK: [23, 20] R # reverse Ć # append the head (the mod result) Á # rotate right # STACK: [20, 20, 23] ®÷ # element-wise integer division with the register # STACK: [2, 5, 23] ®Rα # absolute difference with the register reversed # STACK: [2, 4, 23] Á # rotate right ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~25~~ 22 bytes ``` K9hGy/sktQ3M1YS-b*XkG- ``` -3 bytes thanks to @LuisMendo [Try it online!](https://tio.run/##y00syfn/39syw71Svzi7JNDY1zAyWDdJKyLbXff//2hLIwXTWAA "MATL – Try It Online") [Answer] # Excel, 89 bytes ``` =INT(A2/4+B2/9)&" "&ROUNDUP(4-MOD(A2*9+B2*4,36)/9,0)&" "&ROUNDUP(9-MOD(A2*9+B2*4,36)/4,0) ``` Using @Jonathan Allan's approach. [Answer] # Java 8, ~~77~~ 67 bytes Nicked from @JonathanAllan ``` a->i->System.out.printf("%d %d %d",(i=a*9+i*4)/36,4-i/9%4,9-i/4%9); ``` ]
[Question] [ Note that this is similar to [my other challenge](https://codegolf.stackexchange.com/questions/117894/split-words-split-words), but it is widened to be similar to most challenges (input -> truthy/falsey), instead of asking you all to brute force something. If this makes it a dupe, let me know, but I posted it on Sandbox and asked on chat, and didn't get any negative responses. # Input Input will be a "word" consisting of `a`-`z`, `A`-`Z`, `-`, and `'`. The case is important. Instead of my previous challenge, where you run through all permutations, in this challenge, you will be given a permutation. Your program's response on invalid input does not matter. Input can be taken in reasonable text input formats, and can contain a trailing newline if required. # Output Output will be a standard truthy/falsey values on if the permutation can be split in half. A permutation can be split in half if the width values (see below) of one half of the word equal the point values of the other half, or if the same is true if the middle word is removed. Trailing newlines allowed if required. Please note that "half" does not mean that you have moved halfway into the string. "Half" means that the points on both sides are equal. Examples: `W` is 5 points. `i` is 1 point. Splitting the permutation `Wiiiii` in half will result in `W | iiiii`, with 5 points on each side of the `|`. `T` is 3 points. Splitting the permutation `TTTT` in half will result in `TT | TT`, with 6 points on each side of the `|`. `w` is 4 points. a is 3 points. Splitting the permutation `waw` in half will result in `w (a) w`, with 5.5 points on each side. The points from `a` are distributed to both sides, as `a` is split in half. See the test cases for more clarification. # Letter Scores ``` Width Characters 1 i l I ' 2 f j r t - 3 a b c d e g h k n o p q s u v x y z 4 m w A B C D E F G H J K L N O P Q R S T U V X Y Z 5 M W ``` # Test Cases `( )` indicate that the permutation can be split if the character inside the parantheses is cut in half. `|` indicates that the permutation can be split in between those two letters. Input : Output : Visualization ``` a : truthy : (a) ab : truthy : a|b Ab : falsey AB : truthy : A|B r- : truthy : r|- iiiiw : truthy : iiii|w iiiiiiW : truthy : iiiii(i)W STEPHEN : truthy : STE(P)HEN STEphen : truthy : STE|phen STEpheN : falsey splitwoRdS : truthy : splitw|oRdS ``` And here's a visualization for `splitwoRdS`: ``` s p l i t w | o R d S 3 3 1 1 2 4 3 4 3 4 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~52~~ 50 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Œuðẇ⁾MW+= ẇЀ“fjrt“il-“I'”T_@Ç+3µ€Hx2FŒṖṖLÐṂS€E$€Ṁ ``` **[Try it online!](https://tio.run/nexus/jelly#@390UunhDQ93tT9q3Ocbrm3LBWQenvCoac2jhjlpWUUlQCozRxdIeqo/apgbEu9wuF3b@NBWoAKPCiO3o5Me7pwGRD6HJzzc2RQMFHVVARIPdzb8//9fKTjEtSAj1U8JAA)** (exceeds memory limitations on TIO for the "splitwoRdS" test case) Although slower and more memory hungry than the below 50 byte alternative that borrows the reduction method from [fireflame241's answer](https://codegolf.stackexchange.com/a/119042/53748): ``` Œuðẇ⁾MW+= ẇЀ“fjrt“il-“I'”T_@Ç+3µ€Hx2F+\©ð_ø®ṪHµẠ¬ ``` ### How? ``` Œuðẇ⁾MW+= - Link 1, character index offset helper: character list c (of length one) Œu - to uppercase ð - dyadic chain separation (call that u) ⁾MW - char pair literal ['M', 'W'] ẇ - sublist exists in? (is u in there - True if c is 'm', 'w', 'M', or 'W') = - equal? (vectorised u=c? [1] for uppercase or non-alpha c, [0] for lowercase c) + - add the two results (vectorises) ẇЀ“fjrt“il-“I'”T_@Ç+3µ€Hx2FŒṖṖLÐṂS€E$€Ṁ - Main link: character list w µ€ - for each c in w: “fjrt“il-“I'” - list of character lists: ["fjrt","il-","I'"] ẇЀ - sublist (w) exists in, mapped across right T - truthy indexes (gets [the index at which the character was found] or an empty list) Ç - call the last link (1) as a monad _@ - subtract with reversed @rguments +3 - add 3 H - halve (vectorises) x2 - times two (repeats each list) F - flatten into a single list ŒṖ - partitions (all ways to split the list into contiguous slices) Ṗ - pop (remove the right-most; the only one of length 1) ÐṂ - filter keep those with minimal: L - length $€ - last two links as a monad for €ach S€ - sum €ach E - all (two) equal? (1 for a split, 0 otherwise) Ṁ - maximum (1 if any split was possible, 0 otherwise) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 79 bytes ``` “¡-Ị’b26 “µııẈḟ(µ⁹\fy¦°Ẓ=ȮH@Q0Ẋƈẏ9Ė=ẹṬɗƇ’ðœ?øØa;ØA;⁾'-ð,ø5Rx¢ ¢yHx2+\©ð_ø®ṪHµẠ¬ ``` [Try it online!](https://tio.run/nexus/jelly#AZMAbP//4oCcwqEt4buK4oCZYjI2CuKAnMK1xLHEseG6iOG4nyjCteKBuVxmecKmwrDhupI9yK5IQFEw4bqKxojhuo85xJY94bq54bmsyZfGh@KAmcOwxZM/w7jDmGE7w5hBO@KBvictw7Asw7g1UnjCogrConlIeDIrXMKpw7Bfw7jCruG5qkjCteG6oMKs////aWlpaXc "Jelly – TIO Nexus") [Answer] # [Retina](https://github.com/m-ender/retina), 88 bytes ``` T`MWi\lI'`551 T`-fjrt`2 T`m\wL`4 T`l`3 \d $*1 +`^ ?1(1* 1*( 1*)+)1 ?$ $1 ^ ?(1+) \1? ?$ ``` [Try it online!](https://tio.run/nexus/retina#LUnLCsIwELzvV@QQMQ96WLXnolBU0CI20EuQrVQxUrXUQj6/ruIwL2Ymak2jo30VfLudUpoiOEqu936gGbeHjztacGlpDr4BaVCApZPIUKERaBRLW40ikyAR@FBotfCY8TKONdRnWDJX0CcQGPHnIVRQuvywyYtvdrfL858FvLs2DPF1bMoP "Retina – TIO Nexus") ]
[Question] [ Given a ray with a point and a vector and a plane with a point and a normal vector to the plane. You have to find the intersection point of the plane and the ray.. So your job if you choose to accept is to write a shortest function that will do the job. ``` RULES: The submission must be a complete program And that's all INPUT FORMAT: x y z rx ry rz //gives the ray point and the ray vectors x y z px py pz //gives the point on the plane and the vector normal to plane OUTPUT FORMAT: (x,y,z) //intersection point Test Case: 2 3 4 0.577 0.577 0.577 7 1 3 1 0 0 (7,8,9) ``` The shortest codes in bytes win. References: <https://www.siggraph.org/education/materials/HyperGraph/raytrace/rayplane_intersection.htm> thanks [orlp](https://codegolf.stackexchange.com/users/4162/orlp) for the reference [Answer] # Mathematica, 20 bytes Takes 4 lists as input. The dot product operator `.` has precedence over multiplication and division, so no more parentheses are needed. ``` #+#2(#3-#).#4/#2.#4& ``` Readable version: ``` x + v (r - x).n / v.n ``` where the arguments in order are `x` (ray point), `v` (ray direction), `r` (plane point), `n` (plane normal). [Answer] # Perl, 107 bytes Tested for all test cases (i.e. not tested at all) Run with each input number on its own line on STDIN ``` perl -M5.010 plane.pl 0 1 0 0 0 1 3 3 1 0 0 1 ^D ``` `plane.pl`: ``` #!/usr/bin/perl $$_=<>for a..l;say$a+($t=($j*($g-$a)+$k*($h-$b)+$l*($i-$c))/($j*$d+$k*$e+$l*$f))*$d,$",$b+$t*$e,$",$c+$t*$f ``` This kind of problem is absolutely ***not*** a good match for perlgolf. Perl lacks vector operations and uses too many `$`s [Answer] ## Haskell, ~~137~~ 157/102 bytes Follows both input and output pattern. Program reads input from stdin. 157 bytes. ``` z=zipWith main=do [(p,r),(l,n)]<-map(splitAt 3.map read.words).lines<$>getContents print$(\[a,b,c]->(a,b,c))$z(+)p$map(*(sum(z(*)n(z(-)l p))/sum(z(*)n r)))r ``` With an input file that has format `[[x,y,z],[rx,ry,rz],[x,y,z],[px,py,pz]]` and output of format `[x,y,z]` (102 bytes): ``` z=zipWith main=do [p,r,l,n]<-read<$>getContents print$z(+)p$map(*(sum(z(*)n(z(-)l p))/sum(z(*)n r)))r ``` [Answer] # R, 88 bytes ``` x=scan() v=scan() r=scan() n=scan() C=cat C("(");C(x+v*sum((r-x)*n)/sum(v*n),sep=", ");C(")") ``` Adapted from the [Mathematica answer](https://codegolf.stackexchange.com/a/95234/59052). Takes the following values from stdin, `x` (ray point), `v` (ray direction), `r` (plane point), `n` (plane normal). Outputs `(7, 8, 9)` for the test case. [Answer] ## JavaScript (ES6), 157 bytes This could probably be shorter. The test case is subject to rounding errors, but otherwise it respects the challenge. ``` P=prompt;[a,b,c,d,e,f,g,h,i,j,k,l]=(P()+' '+P()).split` `.map(e=>+e);alert('('+(a+(t=(j*(g-a)+k*(h-b)+l*(i-c))/(j*d+k*e+l*f))*d)+','+(b+t*e)+','+(c+t*f)+')') ``` [Answer] # JavaScript (ES6), 93 bytes ``` (a,b,c,A,B,C,x,y,z,X,Y,Z)=>`(${t=X*(x-a)+Y*(y-b)+Z*(z-c)/(X*A+Y*B+Z*C),[a+t*A,b+t*B,c+t*C]})` ``` ``` f= (a,b,c,A,B,C,x,y,z,X,Y,Z)=>`(${t=X*(x-a)+Y*(y-b)+Z*(z-c)/(X*A+Y*B+Z*C),[a+t*A,b+t*B,c+t*C]})` console.log(f(2, 3, 4, 0.577350269, 0.577350269, 0.577350269, 7, 1, 3, 1, 0, 0)) ``` ]
[Question] [ The challenge is to assign people to tasks randomly~. From stdin you get 2 lines. Line one is a comma-separated list of names. Line 2 is a comma-separated list of jobs. The output required is one line per task person combo. The line should be formatted as Name:task. If there are not enough people for jobs or vice verse then they will not be output. ~ Randomly is defined as each run with the same input has a reasonably different output. Example Input: ``` Bob,John,Susan,Josie,Kim,Tom Bins,Floor,Windows ``` Example Output: ``` Bob:Windows Susan:Bins Kim:Floor ``` [Answer] ## 05AB1E, 7 bytes **Code:** ``` .r².r)ø ``` [Try it online](http://05ab1e.tryitonline.net/#code=LnLCsi5yKcO4&input=WyJCb2IiLCJKb2huIiwiU3VzYW4iLCJKb3NpZSIsIktpbSIsIlRvbSJdClsiQmlucyIsIkZsb29yIiwiV2luZG93cyJd) **Following the input/output spec strictly (16 bytes):** ``` .r².r)øvy`r?':?, ``` **Explained:** ``` .r # radomize first input ².r # randomize second input )ø # merge the lists to an array of pairs cutting out extras vy`r?':?, # format output ``` [Try it online](http://05ab1e.tryitonline.net/#code=LnLCsi5yKcO4dnlgcj8nOj8s&input=WyJCb2IiLCJKb2huIiwiU3VzYW4iLCJKb3NpZSIsIktpbSIsIlRvbSJdClsiQmlucyIsIkZsb29yIiwiV2luZG93cyJd) [Answer] # Java 7, ~~240~~ ~~239~~ 238 bytes ``` import java.util.*;class M{public static void main(String[]a){String[]p=a[0].split(",");List j=new ArrayList(Arrays.asList(a[1].split(",")));for(int i=0;j.size()>0;)System.out.println(p[i++]+":"+j.remove((int)(Math.random()*j.size())));}} ``` Can most likely be golfed more with some arrays magic, instead of `List j=new ArrayList(Arrays.asList(a[1].split(",")));`.. **Ungolfed:** [Try it here](https://ideone.com/XTygsY) ``` import java.util.*; class M{ public static void main(String[] a){ String[] p = a[0].split(","); List j = new ArrayList(Arrays.asList(a[1].split(","))); for(int i = 0; j.size() > 0;){ System.out.println(p[i++] + ":" + j.remove((int)(Math.random() * j.size()))); } } } ``` [Answer] # Jelly, 13 bytes ``` Œ!€X€ZL’$ÐfŒṘ ``` [Try it online!](http://jelly.tryitonline.net/#code=xZIh4oKsWOKCrFpM4oCZJMOQZsWS4bmY&input=&args=W1snQm9iJywgJ0pvaG4nLCAnU3VzYW4nLCAnSm9zaWUnLCAnS2ltJywgJ1RvbSddLCBbJ0JpbnMnLCAnRmxvb3InLCAnV2luZG93cyddXQ) [Answer] # Pyth, 6 bytes ``` CmO.pd ``` [Try it online!](http://pyth.herokuapp.com/?code=CmO.pd&input=%5B%5B%27Bob%27%2C+%27John%27%2C+%27Susan%27%2C+%27Josie%27%2C+%27Kim%27%2C+%27Tom%27%5D%2C+%5B%27Bins%27%2C+%27Floor%27%2C+%27Windows%27%5D%5D&debug=0) ### How it works: ``` CmO.pd (implicitly) takes the evaluated input m d for each "line": .p generate all permutations O choose one randomly C truncating transpose ``` # Following strictly the input/output format: (16 bytes) ``` jjL\:CmO.pcd\,.z ``` [Try it online!](http://pyth.herokuapp.com/?code=jjL%5C%3ACmO.pcd%5C%2C.z&input=Bob%2CJohn%2CSusan%2CJosie%2CKim%2CTom%0ABins%2CFloor%2CWindows&debug=0) ### How it works: ``` jjL\:CmO.pcd\,.z .z takes all lines m d for each line: c \, split by "," .p generate all permutations O choose one randomly C truncating transpose jL\: join every pair by ":" j join all pairs by newlines ``` [Answer] # Mathcad, [tbd] bytes [![enter image description here](https://i.stack.imgur.com/ZgI9P.jpg)](https://i.stack.imgur.com/ZgI9P.jpg) csort(M,n) sorts matrix M on column n. augment joins two arrays columnwise. runif(n,a,b) returns a vector of n uniformly-distributed numbers over the range a..b. concat(a,b) concatenates strings a and b. With due apologies to Messrs Gilbert and Sullivan. --- Mathcad scoring system yet to be determined (must get round to posting something on Meta ...). However, this solution clearly wouldn't be a contender for anything other than a Programming Language specific leaderboard. Taking a rough keyboard equivalence, and noting that Mathcad uses keyboard shortcuts for entering programming and some other operators, it takes around 100 "bytes". [Answer] ## Q, 38 Bytes ``` t:{$[n:&/#:'x:{(-#x)?x}'x;+n#/:x;0N]} ``` NOTE.- input and output format not exactly as proposed (see test) **Test** ``` ."\\S ",$7h$.z.t /To accomplish a random output we mofify seed based on internal clock t(`Bob`John`Susan`Josie`Kim`Tom; `Bins`Floor`Windows) /generates (`Susan`Windows;`Kim`Bins;`John`Floor) (a different result each run) ``` **Explanation** `(-seqLen)?seq` Shuffles the sequence `x:{(-#x)?x}'x` shuffles each sequence of x (argument with sequence of names and sequence of works) and reassign to x `n:&/#:'x` Assigns to n the minimum over (&/) each sequence lengths (#:'x) `$[n;+n#/:x;0N]` If n (if n is not 0), executes flip n take of each seq, Else returns null [Answer] # Ruby, 69 bytes ``` n=gets.split(/,|\n/).shuffle;puts gets.split(',').map{|j|n.pop+':'+j} ``` **Ungolfed:** ``` names = gets.split(/,|\n/).shuffle jobs = gets.split(',') jobs.each do |job| name = names.pop puts "#{name}:#{job}" end ``` [Answer] ## JavaScript (Firefox 30-57), 82 bytes ``` (a,b,s=a=>a.sort(_=>Math.random()-.5),c=s(b))=>[for(x of s(a))if(c[0])[x,c.pop()]] ``` Uses bogus sort to shuffle. Version which accepts two string parameters of comma-separated names and returns lines of colon-separated matchups for 110 bytes, where `\n` represents the literal newline character: ``` (a,b,s=a=>a.sort(_=>Math.random()-.5),c=s(b.split`,`))=>[for(x of s(a.split`,`))if(c[0])x+':'+c.pop()].join`\n` ``` ]
[Question] [ # Scenario: Imagine a situation where you wish to share a unique alphanumeric code. Perhaps it is a one-time-use coupon code you hand write on business cards, or some other scenario where it is desirable to have a code where mis-keying the entry is unlikely to produce valid result and the another valid code is not readily guessed. However, when you are issuing these codes you do not have access to the list of codes that have already been issued. Rather, you know only *how many* have been issued before. # Challenge: Write a function that generates a unique string of length n, subject to the following constraints: * **Available Characters**: Each character in resultant string shall be from a configurable list of allowed values, which may be "hard-coded" into the algorithm. + Sample List: A, B, C, D, E, F, G, H, J, K, L, M, N, P, Q, R, S, T, U, V, W, X, Z, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 (A-Z and 0-9, omitting "I" and "J") * **Configurable Length Output**: The length n of the generated string shall be configurable within the algorithm, for n<=8. * **Input**: A seed is available (unique sequential positive integer >=1 and up to 10 digits) * **Stateless**: The algorithm has no memory of previously generated strings (no database calls) * **Repeatable**: The same seed shall yield the same result * **Unordered Output**: Sequential seed values shall not generate strings in any obvious order (that is to say, results should superficially "appear" random) + *For example,* `1:"AAAA", 2:"AAAB", 3:"AAAC", ...` *would NOT qualify, while* `1:"RR8L", 2:"1D9R", 3:"TXP3", ...` *is on the right track.* + ***Note:*** While this criterion is admittedly subjective, "degree of randomness" is not intended to be the core aspect of this function. Given the *Popularity Contest* format, I'll leave it up to the community to decide whether a pattern is too obvious. * **Unique Output**: String shall be unique, at least within limitations of available characters and requested string length. Therefore, each possible permutation is to be used exactly once before any combination may be reused. + *For example, if configured to generate a string of length n=5 and the available characters include A-Z and 0-9 except for "O", "I" (34 possible characters), then the string may not repeat between seed>=1 and seed<=45,435,424.* + *However, if length n=4 with 34 available characters, then the same string need only be unique on seed>=1 and seed<=1,336,336* # **Winning Criteria:** ***Popularity Contest*** - Submission with the most upvotes will be selected as the winner no sooner than two weeks after the first valid solution. Please upvote any and all submissions you feel adequately meet the above criteria. [Answer] # C(++) - we don't need no friggin' primes The problem is to generate a different permutation of **n** characters taken from an **a** size alphabet for each seed value. There are **an** such permutations, and they can be represented as values of a **n** digits number in base **a**. The number of bits necessary to represent all these values is **log2(an)**, rounded up. We have at most 8 characters per code, and the alphabet contains at most 256 characters, so a 64 bits word is just what we need to cover all possible codes with all possible alphabets. Now we just need something that maps all possible 232 seed values to the possible range of code values (and looks random enough). I settled for a basic 32 bits reversal, which gives highest variability for low seed values. If the possible codes range is smaller than the seed's, there will be duplicates anyway, and the codes will be like the n first digits of a greater number. If the 232 seed values are not enough to cover all code values, the scrambled seed is extended to the smallest power of two inferior to code max value, by injecting 0s in the lower bits. This should spread the range of code values while guaranteeing no duplicates. However, the last digit will have a slightly lower frequency due to the rounding to a power of 2. If alphabet size is much greater than 2, the difference will be hardly noticeable. The scrambled seed is then converted as a number in base a, the digits being the symbols of the alphabet. ## A few (pseudo) random thoughts The big weakness of this method is that it won't work well with alphabets whose size is a power of two. The apparent randomness is due to the non-integer number of bits needed to encode a digit. On second thought maybe we *do* need some friggin primes after all... At any rate, even the most magnificent pseudo-random repartition is useless as far as data protection is concerned, since the encryption method is stateless and could be easily cracked by brute-force. ## The code I used the excellent [bit shuffling generator](http://programming.sirrida.de/calcperm.php) of Mr. Jasper Neumann to produce the bit reverser, though other solutions are possible. I compiled with g++4.8 under MinGW/Win7, but the code is nothing but glorified C and should work with any C++ compiler. ``` #include <cstdlib> // atoi #include <cstdio> // printf #include <cmath> // pow #define Alphabet "ABCDEFGHKLMNOPQRSTUVWXYZ0123456789" #define Length 8 unsigned bit_permute_step_simple(unsigned x, unsigned m, unsigned shift) { return ((x & m) << shift) | ((x >> shift) & m); } unsigned shuffle (unsigned x) { x = bit_permute_step_simple(x, 0x55555555, 1); // Bit index complement 0 x = bit_permute_step_simple(x, 0x33333333, 2); // Bit index complement 1 x = bit_permute_step_simple(x, 0x0f0f0f0f, 4); // Bit index complement 2 x = bit_permute_step_simple(x, 0x00ff00ff, 8); // Bit index complement 3 x = bit_permute_step_simple(x, 0x0000ffff, 16); // Bit index complement 4 return x; } #define Base (sizeof(Alphabet)-1) typedef char Code[Length+1]; void gen_code (unsigned seed, Code code) { // shuffle seed bits (the inversion is to avoid zero value for seed = 0) unsigned long long scrambled = shuffle(~seed); // if maximal code size is less than seed max value, there will be duplicates anyway int extra_bits = floor(Length * log(Base)/log(2)) - 32; if (extra_bits > 0) scrambled <<= extra_bits; // basic base conversion. // The last code digit might have a slightly lower frequency than others int i; for (i = 0 ; i != Length ; i++) { int digit = scrambled % Base; code[i] = Alphabet[digit]; scrambled /= Base; } code[i] = '\0'; } int main (int argc, char * argv[]) { if (argc != 2) exit(-1); unsigned seedm = atoi(argv[1]); Code code; for (unsigned seed = 0 ; seed != seedm ; seed++) { gen_code (seed, code); printf ("code (%u) = %s\n", seed, code); } return 0; } ``` The `main()` prints a specified number of codes for consecutive seeds. Sample output: n=8, alphabet = `ABCDEFGHKLMNOPQRSTUVWXYZ0123456789` ``` code (0) = 215GVK7B code (1) = MPPT46CX code (2) = 4AF2E28Y code (3) = GLGGAS6W code (4) = U3MSPN2Y code (5) = CR42Y97H code (6) = WCWB943L code (7) = CZW2XAAB code (8) = UBHMSV6C code (9) = CZ0W1HCY code (10) = WMS5BD8Z code (11) = 8UTL725X code (12) = MDYVMY1Z code (13) = 40F6VM7K code (14) = OO7E6F3M code (15) = U5L28BA5 code (16) = 08GMUH56 code (17) = KW0W35AS code (18) = 2HS5D16T code (19) = ESTL9Q4R ``` n=4, alphabet = `ABCDE` ``` code (0) = AEBD code (1) = CEAE code (2) = BEDD code (3) = DECE code (4) = DBAB code (5) = ACEB code (6) = EBCB code (7) = BCBC code (8) = ECDE code (9) = BDCA code (10) = ADAA code (11) = CDEA code (12) = CACC code (13) = EABD code (14) = DAEC code (15) = ABDD code (16) = CDCB code (17) = EDBC code (18) = DDEB code (19) = AEDC ``` [Answer] # Python 3: The main task of this challenge is to find a bijection between `[0, 1, ..., #alphabet^length-1]` to itself, which appears to be random. I stumbled about linear congruential generators, which generate a permutations of the numbers, when the parameters of it satisfy some properties. But interestingly the resulting strings didn't looked random at all. So I decided to do some own stuff. One obvious bijection is the function `f(x) = (a * x + c) % m`, where `m = #alphabet^length`, `a` and `m` are random numbers with `gcd(a,m) = 1`. Since the function has to be repeatable, I used the fixed values `a = 0.4 * m` and `c = 0.3 * m`. Of course this is nowhere near random. The second bijection is based on primitive roots. When `p` is a prime (or 4, or (prime>2)^alpha, or 2\*(prime>2)^alpha), then there exists values `g`, where `g^i` generates a permutation of all numbers. Therefore I search for next primes smaller than `m` and `g` is approximately `m/3`. Since `p` is smaller than `m`, not all numbers are effected by this approach, I have to use it twice, once for the first `p` numbers and once for the last `p` numbers. My program first applies the first and than the second bijection. And the result looks quite random to me. E.g. the output for the alphabet `ABC` and length `3` is: `BCB, ACA, BCC, BBC, CCA, ABC, CAA, ABB, CAB, AAC, AAA, BAC, BBB, CBC, BAB, ACB, BBA, BCA, CBA, CCC, AAB, ABA, CAC, BAA, ACC, CCB, CBB`. ``` from fractions import gcd from numbthy import is_prime, is_primitive_root def random_linear_congruence(length, seed): multiplier = int(length * 0.4) while gcd(multiplier, length) > 1: multiplier += 1 start_value = int(length * 0.3) return (start_value + seed*multiplier) % length def random_primitive_root(length, seed): prime = length while not is_prime(prime): prime -= 1 prim_root = prime // 3 while not is_primitive_root(prim_root, prime): prim_root = (prim_root - 1 ) % prime random_number = seed if 0 < seed < prime: random_number = (prim_root ** seed) % prime t = length - prime if random_number > t: random_number = ((prim_root ** (random_number - t)) % prime) + t return random_number def unique_nonsenquential_string(alphabet, length, seed): alphabet = sorted(alphabet) modulus = len(alphabet)**length random_number = seed random_number = random_linear_congruence(modulus, random_number) random_number = random_primitive_root(modulus, random_number) # convert to base len(alphabet) word = [] for i in range(length): word.append(random_number % len(alphabet)) random_number //= len(alphabet) return ''.join(map(lambda x: alphabet[x], word)) outputs = set() alphabet = "ABC" length = 3 for seed in range(len(alphabet)**length): random_string = unique_nonsenquential_string(alphabet, length, seed) outputs.add(random_string) print("Seed {:2d}: {}".format(seed, random_string)) if len(outputs) == len(alphabet)**length: print("Unique output") ``` You can find `numbthy.py` here: [Basic Number Theory functions implemented in Python](http://userpages.umbc.edu/~rcampbel/Computers/Python/lib/numbthy.py) [Answer] # Simplicity (python 2) This may not be in the spirit of the challenge, but it works, and is far simpler than the other algorithms. ``` import random from string import uppercase def unique_code(n, seed, alphabet): pre_state = random.getstate() #so we don't interfere outside scope random.seed(seed) code = ''.join([random.choice(alphabet) for _ in xrange(n)]) random.setstate(pre_state) return code length = 4 for i in range(20): print '{} [seed {:d}]'.format(unique_code(length, i, uppercase), i) ``` Running this code gives: ``` VTKG [seed 0] DWTG [seed 1] YYBC [seed 2] GOJP [seed 3] GCKE [seed 4] QTUY [seed 5] UVMG [seed 6] IDQB [seed 7] FZDS [seed 8] MJDW [seed 9] OLPF [seed 10] LOYM [seed 11] MRRD [seed 12] GRRW [seed 13] CSQY [seed 14] ZATE [seed 15] JMKL [seed 16] NUYH [seed 17] ERIF [seed 18] RUNN [seed 19] ``` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 7 years ago. [Improve this question](/posts/20338/edit) Isolated prime definition from [Wikipedia](http://en.wikipedia.org/wiki/Twin_prime#Isolated_prime): > > An isolated prime is a prime number p such that neither p − 2 nor p + 2 is prime. In other words, p is not part of a twin prime pair. For example, 23 is an isolated prime since 21 and 25 are both composite. > > > Consider strings which consists of character `x` repeated n times, where n ≥ 0. You shall write a regex which matches strings whose length is an isolated prime, and rejects strings whose length is not an isolated prime. Same rule as my previous question [Match strings whose length is a fourth power](https://codegolf.stackexchange.com/questions/19262/match-strings-whose-length-is-a-fourth-power): * Any (ir)regular expression syntax is allowed, except for arbitrary code execution (to Perl users). * Your solution should logically1 work correctly for large number. This means that an answer that lists out all the lengths within certain range is disqualified. * Please also include a short explanation about your approach to the problem (something like [this](https://codegolf.stackexchange.com/a/19413/6638)). 1 Some engine implements `*` with an upper limit. This question assumes that `*` doesn't have an upper limit (and the only limit is the length of the input string). This question on SO might be useful as a starting point. [How to determine if a number is a prime with regex?](https://stackoverflow.com/questions/2795065/how-to-determine-if-a-number-is-a-prime-with-regex) **Do you know?** If you can solve this problem, with trivial modification, you can check whether a number is part of a [twin prime](http://en.wikipedia.org/wiki/Twin_prime), since isolated prime has opposite definition of a twin prime. [Answer] # Perl, 54 ``` /^(?!(..+)\1+$)(?=..(?:|(..+)\2+)$)(?=(..(.*))\4\3*$)/ ``` I think this is not possible without the Perl look-ahead expression... Firstly, there is no positive regex to match the prime number. You can only match a non-prime by simulating multiplication: `(..+)\1+`. To negate it, I use negative look-ahead: `/^(?!(..+)\1+$)/` matches prime numbers (neglecting the 0, 1 case). The beauty of the look-ahead is that it is zero-width, i.e. eats no characters. This means you can actually AND those conditions! My regex is composed of 3 look-aheads, corresponding to AND-ing 3 conditions: * `(?!(..+)\1+$)` - N (length of the string) is the prime number * `(?=..(?:|(..+)\2+)$)` - N-2 is a non-prime - this is a trival modification of the basic non-prime expression - `(..+)\1+`) - just add two characters. The `(?:|...)` is included to also match an empty string (case N=2 should match too). * `(?=(..(.*))\4\3*$)` - N+2 is a non-prime - again, trivial modification of the basic non-prime expression - cut two characters out of one repetition. Test: ``` $ perl -E'($"x$_)=~/^(?!(..+)\1+$)(?=..(?:|(..+)\2+)$)(?=(..(.*))\4\3*$)/&&say for(2..200)' 2 23 37 47 53 67 79 83 89 97 113 127 131 157 163 167 173 ``` ]
[Question] [ **Challenge:** A cipher (which is a positive integer) which has any substring not divisible by 2, or has a substring divisible by 11 (other than 0), is defined as 'bad'. All other ciphers are defined as 'good'. Find the kth cipher, in ascending order, which is 'good'. **Input format** The first line of input has a single integer T, the total number of test cases. The next T lines each have an integer k on them. **Output Format** The output should contain T integers on T different lines, the kth good cipher. **Sample Input** 2 1 136 **Sample Output** 2 4008 [Answer] ## Perl, ~~75~~ 74 characters ``` map{map{1while++$n=~/[13579]|(.+)(?(?{$^N<1|$^N%11})!)/}1..<>;$n=say$n}1..<> ``` I should point out that the character count is taking advantage of Perl's bizarre feature of allowing a special variable of the form `$^X` to be spelled with a literal ctrl-*X* character. The regex extensions being utilized are also terrifying, but boy do they come in handy. [Answer] ## Haskell, 187 ``` import Data.List d=drop 1 e=[]:d e>>=(\z->map(\y->z++[y])"02468") f=filter g=f(all((>0).(`rem`11)).f(>0).map(read.('0':)).(>>=inits).tails)e main=interact$unlines.map((g!!).read).d.lines ``` Could save 4 characters by inlining `g`, but then the code wouldn't be quite as nice. If the input wasn't preceded by a test case count (like in the Ruby submission), then could save 6 more characters. ``` & runhaskell 13166-Cipher.hs 2 1 2 136 4008 ``` [Answer] ## APL (70) ``` ⍪{⎕{⍺⍺<Z←⍺+∧/{~2|⍵,0=11|⍵~0}⍎¨⊃,/{↑∘⍵¨⍳⍴⍵}¨↓∘Z¨0,⍳⍴Z←⍕⍵:⍵⋄Z∇⍵+1}⍨0}¨⍳⎕ ``` [Answer] ## Ruby, ~~231~~ ~~227~~ 219 ``` gets s=[] l=[] while(g=gets.to_i)>0 s.push g end z=2 until l.size>=s.max a=z.to_s.split'' l.push z if(1..a.size).flat_map{|n|a.each_cons(n).map{|x|x.join.to_i}}.all?{|x|x<1||x%11>0&&x%2<1} z+=1 end puts s.map{|x|l[x-1]} ``` Input is terminated with an empty line. If the input was just a list of indeces without the length, I could save 5 characters. Sample run: ``` c:\a\ruby>goodc 2 1 136 2 4008 c:\a\ruby> ``` [Answer] ## Sage Notebook, ~~167~~ 166 ``` for k in list(file(DATA+'i'))[1:]: j=n=0 while j<int(k):n+=1;j+=not[t for t in[int(`n`[i:j])for i in[0..len(`n`)]for j in[i+1..len(`n`)]]if(t%11==0)*t+t%2] print n ``` Sample run ... **Input** (in data file named 'i'): ``` 2 1 136 ``` **Output**: ``` 2 4008 ``` ## Python 2, ~~180~~ 179 ``` for k in[input()for i in[0]*input()]: j=n=0 while j<int(k):n+=1;j+=not[t for t in[int(`n`[i:j])for i in range(len(`n`))for j in range(i+1,len(`n`)+1)]if(t%11==0)*t+t%2] print n ``` Sample run ... ``` >>> 2 >>> 1 >>> 136 2 4008 ``` ]
[Question] [ I am working on making a minimalistic personal testing website to conduct various experiments for my role at work. I'd like to add a couple of bells and whistles to it, particularly a slideshow that cycles between several images. I could just as easily grab a plug-in, but I'd like to promote this Stack Exchange beta site and offer a simple challenge with concrete rules. Rules: * [JavaScript](http://en.wikipedia.org/wiki/JavaScript) and [jQuery](http://en.wikipedia.org/wiki/JQuery) are allowed. The jQuery library is assumed to be included. * The function of the code is to take three images and fade-cycle through each of them at regular intervals of five seconds indefinitely. Fade time is one second. * Must be compatible with Internet Explorer 9 (and later), Chrome, and Firefox. * The code golf submission is the total number of characters between the inline script. Characters in externally referenced files are also included. HTML is the following, pretty-printed as it's not part of the challenge: ``` <html> <head> <title>JS Slideshow code golf</title> <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> <script type="text/javascript"> /* CODE GOLF SUBMISSION HERE */ </script> </head> <body> <div class="s"> <img id="a" src="img1.png" /> <img id="b" src="img2.png" /> <img id="c" src="img3.png" /> </div> </body> </html> ``` Full attribution will be given to the author on any code I end up using. [Answer] # ~~70~~ 68(JS) + 22(CSS) characters ``` setInterval('$(".s").append($(".s :first").hide().fadeIn(1e3))',5e3) ``` CSS: ``` img{position:absolute} ``` jsfiddle: <http://jsfiddle.net/QACAY/> pure jQuery. The only browser-stuff is `setInterval`, which dates as far back as IE4. jQuery support doesn't reach that far. Javascript syntax here is ancient as well. Of course, in practice, **do not pass strings to** `setInterval`! It is ten characters shorter (fewer with es6 arrow functions), but it's unreadable (madness? This is code golf!), it forces you into the global scope (which we don't mind here), it's slower (but we are far from being concerned with performance of calling jQuery code) and it won't pass any decent [code review](http://codereview.stackexchange.com). Works best if all images have the same shape. But, it will work just as fine with semitransparent images as long as visible stacking counts as fine and no more background is visible when any single image is removed. Since this does not wait for DOM ready, there's a tiny chance that only some of the image elements inside a gallery are loaded when an interval fires. In this case, the stack of images will get reordered. I don't think it's a problem. In fact, I kinda like it. After slight tweaking, it looks like code that could easily pass through a code review and get into production (also, be sure to modify the CSS to not be too aggressive): ``` $(function(){ $(".s").each(function(_, s){ setInterval(function(){ $(":first", s).hide().appendTo(s).fadeIn(1000); }, 5000); }); }); ``` ]
[Question] [ I am constantly frustrated by how complicated it is to write graphical programs that would have been only a few lines of code 20+ years ago. Since the invention of the mouse this has become even worse it seems. I was hoping someone could put me out of my misery and show the shortest code to do the following really basic "modern" operations. The code will read in an image in any sensible format of your choosing (png, jpg, etc.), display it on the screen, allow you to choose a rectangular region *with your mouse* and then just save the selected region as an image file. You are free to use any programming language and any library which hasn't been written especially for this competition. Both should be freely (in both senses) online. The code should be runnable in linux. To start things off.... here is a very lightly golfed solution in **python** modified from code to Andrew Cox from <https://stackoverflow.com/questions/601874/digital-image-cropping-in-python> which takes **1294** **1101** characters. ``` import pygame, sys from PIL import Image pygame.init() def displayImage( s, px, t): s.blit(px, px.get_rect()) if t: pygame.draw.rect( s, (128,128,128), pygame.Rect(t[0], t[1], pygame.mouse.get_pos()[0] - t[0], pygame.mouse.get_pos()[1] - t[1])) pygame.display.flip() def setup(path): px = pygame.image.load(path) s = pygame.display.set_mode( px.get_rect()[2:] ) s.blit(px, px.get_rect()) pygame.display.flip() return s, px def mainLoop(s, px): t = None b = None runProgram = True while runProgram: for event in pygame.event.get(): if event.type == pygame.QUIT: runProgram = False elif event.type == pygame.MOUSEBUTTONUP: if not t: t = event.pos else: b = event.pos runProgram = False displayImage(s, px, t) return ( t + b ) s, px = setup(sys.argv[1]) left, upper, right, lower = mainLoop(s, px) im = Image.open(sys.argv[1]) im = im.crop(( left, upper, right, lower)) im.save(sys.argv[2]) ``` I believe it is traditional to give a time limit, so I will accept the best answer in exactly one week's time. **Current count** * **Octave - 44 + 15 = 59** characters * **R - 305** characters * **Python - 343** characters * **Java - 560** characters [Answer] # Octave - 59 chars ``` pkg load image;imwrite(imcrop(imread(input(''))),input('')) ``` # MATLAB - 44 chars (not free, out of the contest) ``` imwrite(imcrop(imread(input(''))),input('')) ``` MATLAB seemed spot-on for this. Requires the Image Processing Toolbox (or package `image 2.0.0` from Octave Forge). Usage: 1. Write at prompt 'input-filename' (single quotes included) 2. **MATLAB:** Drag from top-left to bottom-right corner and double click the rectangle. **Octave:** Click top-left and bottom-right corner 3. Write 'output-filename' (between single quotes too) [Answer] ## Java (580 560 559) ``` import java.awt.*;import javax.imageio.*;public class R extends Frame{static java.awt.image.BufferedImage i;int x,y,w,h;{setSize(i.getWidth(),i.getHeight());setUndecorated(0<1);show();}public static void main(String[]a)throws Exception{i=ImageIO.read(System.in);new R();}public boolean handleEvent(Event e){if(e.id==501){x=e.x;y=e.y;}if(e.id==502){w=e.x-x;if(w<0)x-=w=-w;h=e.y-y;if(h<0)y-=h=-h;try{ImageIO.write(i.getSubimage(x,y,w,h),"png",System.out);System.exit(0);}catch(Exception E){}}return 0<1;} public void paint(Graphics g){g.drawImage(i,0,0,this);}} ``` Takes input image from stdin and writes cropped image to stdout. You can drag in whichever direction you choose and it will automatically flip the coordinates as required. Input in GIF, PNG, JPEG, TIFF, probably one or two others; output in PNG. With whitespace and a couple of comments: ``` import java.awt.*; import javax.imageio.*; // Extending Frame is the simplest and ugliest way of showing a GUI. public class R extends Frame { // static so that we can read it in main() and save a try/catch block static java.awt.image.BufferedImage i; int x,y,w,h; // Instance initialiser ~= constructor without the signature { setSize(i.getWidth(),i.getHeight()); // Don't show frames. This saves handling inset dimensions everywhere setUndecorated(0<1); show(); } public static void main(String[]a) throws Exception { i=ImageIO.read(System.in); new R(); } // This is deprecated, but it's the shortest way of handling events. // I learnt this trick from the Java4k Game Competition public boolean handleEvent(Event e) { if (e.id == 501) { // MOUSE_DOWN x=e.x; y=e.y; } if (e.id == 502) { // MOUSE_UP w = e.x - x; // If the second click was to the left of the first one, flip them. if (w < 0) x -= w = -w; h = e.y - y; // Similarly. if (h < 0) y -= h = -h; try { ImageIO.write(i.getSubimage(x,y,w,h), "png", System.out); System.exit(0); } catch(Exception E){ } } return 0<1; } public void paint(Graphics g) { g.drawImage(i,0,0,this); } } ``` [Answer] **R - ~~325~~ 305 characters** ``` f=scan(,"");l=locator;r=round;i=as.raster(png::readPNG(f));n=nrow(i);m=ncol(i);x11(h=7,w=7*m/n);p=function(X){par(mar=rep(0,4));m=ncol(X);n=nrow(X);plot(c(1,m),c(1,n),xaxs="i",yaxs="i");rasterImage(X,1,1,m,n)};p(i);a=l(1);b=l(1);j=i[r(n-a$y):r(n-b$y),r(a$x):r(b$x)];png(w=ncol(j),h=nrow(j));p(j);dev.off() ``` Or fully developed: ``` f=scan(,"") l=locator r=round i=as.raster(png::readPNG(f)) n=nrow(i) m=ncol(i) x11(h=7,w=7*m/n) p=function(X){ par(mar=rep(0,4)) m=ncol(X) n=nrow(X) plot(c(1,m),c(1,n),xaxs="i",yaxs="i") rasterImage(X,1,1,m,n) } p(i) a=l(1) b=l(1) j=i[r(n-a$y):r(n-b$y),r(a$x):r(b$x)] png(w=ncol(j),h=nrow(j)) p(j) dev.off() ``` Tested on a Mac, untested on Linux but should work. Package [png](http://cran.r-project.org/web/packages/png/index.html) needs to be installed. At prompt, should be provided with path to png file to crop. Then when the picture appears, click twice: once for the left upper corner of selection rectangle and a second time for the right lower corner. Create a cropped png file in working directory with default name ("Rplot001.png"). [Answer] # Java (Applet), 706 698 590 By no means is Java ever considered terse, and it certainly doesn't have the most elegant handling of image display or mouse interaction, but this really isn't that bad. I'm wondering if a solution using Swing or some other library might be shorter. ``` import java.awt.event.*; import java.io.*; import java.util.*; import javax.imageio.*; public class R extends java.applet.Applet{ Scanner s=new java.util.Scanner(System.in); java.awt.image.BufferedImage i; int x,y; { try{ i=ImageIO.read(new File(s.nextLine())); }catch(Exception e){} addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent e){ x=e.getX();y=e.getY(); } public void mouseReleased(MouseEvent e){ try{ ImageIO.write(i.getSubimage(x,y,e.getX()-x,e.getY()-y),"png",new File(s.nextLine())); }catch(Exception z){} } }); } public void paint(java.awt.Graphics g){ g.drawImage(i,0,0,this); } } ``` [Answer] # Python/PyGame (343C) Usage: ``` python this.py image.png result.png ``` which read from `image.png` and write to `result.png`. ``` import pygame as P import sys D=P.display I=P.image D.init() f,g=sys.argv[1:3] m=I.load(f) s=D.set_mode(m.get_size()) r=k=0 c=1 while c: for e in P.event.get(): t=e.type if t==5:x,y=e.pos;k=1 if t==4 and k:i,j=e.pos;r=(x,y,i-x,j-y) if t==6:c=0 s.blit(m,(0,0)) if r and c:P.draw.rect(s,0,r,1) D.flip() q=s.subsurface(r) I.save(q,g) ``` [Answer] I know the time limit is up, but here's how to do it in 34 characters using Bash: ``` display $1&K=$!;import $2;kill $K ``` Call it like this: 'script.sh input.png output.png'. This uses the ImageMagick tools/library to first display the image. Then it lets you select an area to take a screenshot of using the mouse. This screenshot is effectively a crop of the image. Finally, the display is closed. ]
[Question] [ I wanted to make a challenge to do the full [DES](http://en.wikipedia.org/wiki/Data_Encryption_Standard) encryption algorithm, but that may be a bit too involved to get a ton of participation. This challenge is to simply generate the 16 48-bit subkeys used to encrypt data: ![key schedule](https://i.stack.imgur.com/trK7y.png) The algorithm is described well enough on [wikipedia,](http://en.wikipedia.org/wiki/Data_Encryption_Standard) and all relevant shift tables and such data are on [this page.](http://en.wikipedia.org/wiki/DES_supplementary_material) Your task is to write a program or function that accepts 64 bits of input, and outputs the 16 48-bit keys. I am not picky about input or output formats, but hex coded is fairly standard. You can check your results against the examples on [this page,](http://people.eku.edu/styere/Encrypt/JS-DES.html) or [this page](http://page.math.tu-berlin.de/~hess/krypto-ws2006/des.htm) Shortest code wins. [Answer] ## GolfScript (175 chars) I assume input and output in MSB-first upper-case hex. For want of good test cases, I don't guarantee that this implementation is correct. I've worked to a test case which I derived from Rivest's [simple test for implementations of DES](http://people.csail.mit.edu/rivest/pubs/Riv85.txt): given his test input of `9474B8E8C73BCA7D` I think that the expected output is ``` BE23F4265E76 63FD57CA5952 6DEDC3C5E33C 73E5BBF11EC8 FD8593D8923F 778A9F177EAC 3FB0963839F1 3E0CFEA3E837 41FFD1A34BCB 55FDE796B313 F3E5C3F70764 79C7A758ABCA F1919F74F41D 3582F76B34EA B758B6ACF92B 44FF4B3F4D29 ``` To that caveat I must add another, which is that I use a lot of base conversion including some of strings with non-printable characters. As usual, I'll give the program in a couple of ASCII-safe formats. xxd output: ``` 0000000: 312f 7b31 302c 2727 2a37 312c 3635 3e2b 1/{10,''*71,65>+ 0000010: 3a5e 5c3f 3136 2b32 7b62 6173 657d 3a42 :^\?16+2{base}:B 0000020: 7e28 3b7e 7d25 607b 3d7d 2b5b 3536 5b5b ~(;~}%`{=}+[56[[ 0000030: 2d38 5d32 342a 372f 2e2b 2739 3939 1b37 -8]24*7/.+'999.7 0000040: 3717 275d 7a69 705b 5d2a 5b5d 2a7b 3124 7.']zip[]*[]*{1$ 0000050: 2b7d 2f5d 2534 3932 3831 2032 427b 2129 +}/]%49281 2B{!) 0000060: 7b32 382f 7b28 2b7d 257e 2b7d 2a27 1d3c {28/{(+}%~+}*'.< 0000070: f9df 2a9b 7079 2030 dea2 83df 3bca a82f ..*.py 0....;../ 0000080: 50ec 11f8 e55c 74d2 f104 b2ae 130e ac5c P....\t........\ 0000090: d627 27ff 3827 7b42 7d2f 7b31 243d 7d25 .''.8'{B}/{1$=}% 00000a0: 342f 7b32 425e 3d7d 256e 2b5c 7d2f 3b 4/{2B^=}%n+\}/; ``` Base-64 encoded: ``` MS97MTAsJycqNzEsNjU+KzpeXD8xNisye2Jhc2V9OkJ+KDt+fSVgez19K1s1NltbLThdMjQqNy8u Kyc5OTkbNzcXJ116aXBbXSpbXSp7MSQrfS9dJTQ5MjgxIDJCeyEpezI4L3soK30lfit9KicdPPnf KptweSAw3qKD3zvKqC9Q7BH45Vx00vEEsq4TDqxc1icn/zgne0J9L3sxJD19JTQvezJCXj19JW4r XH0vOw== ``` And with the magic strings substituted with a printable (but longer) version using escape characters and some unnecessary line-breaks: ``` 1/{10,''*71,65>+:^\?16+2{base}:B~(;~}%`{=}+ [56[[-8]24*7/.+'999\e77\027']zip[]*[]*{1$+}/] %49281 2B{!){28/{(+}%~+}* '\035<\371\337*\233py 0\336\242\203\337;\312\250/P\354\021\370\345\\t\322\361\004\262\256\023\016\254\\\326' '\3778'{B}/{1$=}%4/{2B^=}%n+\}/; ``` This is a pretty literal translation. The vaguely interesting bits are: 1. Permutation PC1 turns out to have a lot of structure. If you take first differences, all but 6 of them are `-8`. The second line of the reformatted version reconstructs it from these differences in 39 characters. For comparison, representing it by base conversion would require 44 characters for the string literal; and representing a generic permutation of numbers 1 to 63 requires 36 base-256 digits (i.e. a 38-character string literal plus code to convert it). 2. `49281 2B{!) ... }` encodes the shift lengths. This is the most obvious place to attempt further optimisation. 3. Permutation PC2 doesn't seem to have any usable structure, so that's a straight double base conversion. (Not to be confused with a double bass conversion). [Answer] ## Perl - 384 314 chars input is in decimal (from STDIN), output in binary. includes all necessary tables. feel free to improve anything ``` use Math'BaseConvert b10; @_=sprintf("%064b",<>)=~/./g; $s=b10 cG4xqQ8GMvUpZSqYtTAVVCZyBjrZs7FkNdowNTFBipcmG28UIKQKyfLYHWWjdq; $s=~s/../$_[$&-1]/g; map{ $n=28-$_; $s=~s/(.{$_})(.{$n})(.{$_})(.+)/$2$1$4$3/; $_=b10"G._NqruyC5whI_KjAHzrS3ZgLTX7BzGp0.zML.AaubJCuwPtzPomq"; s|..|($s=~/./g)[$&-1]|eg; say$_ }b10("3_AUuKOqD")=~/./g ``` ]
[Question] [ This question [may not be that creative](https://codegolf.stackexchange.com/questions/5839/convert-infix-expressions-to-postfix-notation), but I believe that it is different enough to pose a new challenge. ## The Challenge Your challenge is to write the shortest program possible that can take any valid expression in Reverse Polish Notation and convert it to infix notation that obeys the order of operations and has the necessary parentheses. ## Input Your program will receive a valid RPN expression on STDIN. This expression will consist of numbers and operators. There can be an arbitrary number of spaces between each item, but there will always be a space between two numbers. Likewise, there will never be a space within a number. Here is a formal grammer description, stolen and modified from the linked question above. ``` expression := expression expression operator | number operator := "+" | "-" | "*" | "/" | "^" number := digit number | digit digit := "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ``` Here are some simple examples ``` 2 3 -10000 + 16 4 12 3 / * - 1 2 +2 3 +^ ``` In the first example, that is not a negation sign, it is a subtraction operator. ## Output Your program should output an equivalent infix expression to STDOUT, which should be a valid infix expression, with numbers, operators, and parentheses. Here is a formal grammer description, again stolen. ``` expression := number | subexpression | expression operator expression subexpression := "(" expression ")" operator := "+" | "-" | "*" | "/" number := digit | digit number digit := "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ``` With infix notation, there must be an order of operations and a way to group subexpressions. The order of operations will be this: ``` Expressions inside parentheses Exponents right to left Multiplication and division (of equal importance) left to right Addition and subtraction (of equal importance) left to right ``` As an example, 2^3^2-(2^3)^2 should equal 448. The output should not contain any unneeded parentheses. ((2+1))-1 should reduce to 2+1-1. Also, you should not evaluate any expression. You should also not assume the commutative or associative properties. This means that, while the operators will move around, the numbers will always remain in the same order. Here are the outputs for the above inputs. Note that what would normally be unneeded parenthesis are in the second example: removing them would invoke the associative property. ``` 2-3+10000 16-4*(12/3) (1+2)^(2+3) ``` I will add more examples later. ## Rules, Regulations, and Notes This is code golf, standard rules apply. [Answer] ## C, 305 chars A good challenge! I'm finding this much harder to golf than the previous one. But here's what I have so far: ``` char*p,b[99];l[99],o[99],r[99],s[99],h,t; q(e,a,d){int n=o[e]%47%2+(o[e]<48),f=a-n?a>n:d-!n; l[e]?printf("("+f),q(l[e],n,1),q(r[e],n,!putchar(o[e])), printf(")"+f):printf("%d",o[e]);}main(){for(p=gets(b);*p;) *p%24>9?l[++h]=s[t-2],r[h]=s[--t],o[s[t-1]=h]=*p++: *p-32?o[s[t++]=++h]=strtol(p,&p,10):++p;q(*s,3);} ``` [Answer] ## Clojure - 282 279 271 268 characters ``` (dorun(map pr((reduce(fn[s v](let[p '{e 2,* 1,/ 1,+ 0,- 0}[t z](rseq s)a #(if(and(seq? %)(<=(p v)(p(nth % 1))))%`(~%))](if(p v)(conj(pop(pop s)) `(~@(a z)~({'e(symbol"^")}v v)~@(a t)))(conj s v))))[](map read-string (re-seq #"\d+|[e+*/-]"(.replace(read-line)\^\e))))0))) ``` (line breaks are totally optional, only included for clarity, if removed ensure there is a single space between `a` and `#(` between the first two lines. all other spaces between the lines may be removed). Assumes input will end after the first line, passes the example programs (outputs more spaces sometimes, but the right number of parentheses :) Program can be tested here: <http://ideone.com/gxykA> Ungolfed: ``` (defn stackify [s v] (let[p '{e 4,* 3,/ 3,+ 2,- 2} [t n] (rseq s) a #(if (and (coll? %) (<= (p v) (p (nth % 1)))) % `(~%))] (if (p v) (conj (pop (pop s)) `(~@(a n) ~({'e(symbol"^")} v v) ~@(a t))) (conj s v)))) (defn read-postfix [s] "takes a string instead of reading from *in*" (->> (.replace s \^ \e) (re-seq #"\d+|[e+*/-]") (map read-string) (reduce stackify []) first (map pr) dorun)) ``` (woo, first stackexchange post) [Answer] ## Flex - 326 288 chars ``` *s[99],**p=s,q[99],*n=q,t;main(){yylex();} #define W(c) p--;if(*--n c t)asprintf(p,"(%s)",*p); #define X asprintf(p++,"%s%s%s",*p,yytext,*(p+1));*n++=t; #define Z W(<=)W(<)X %% [0-9]+ *p++=strdup(yytext);*n++=9; \+ t=1;Z - t=1;Z \* t=2;Z \/ t=2;Z \^ t=3;W(<)W(<=)X \n puts(*--p); . ; ``` trailing newline is needed Compile with `flex makeinfix.l && gcc lex.yy.c -lfl` Edit: fixed for new spec about `4 12 3 / * => 4*(12/3)` and made quite a bit shorter [Answer] # Regex (PCRE2), ~~140~~ 146 bytes `s~(\d++|\((?1)(?3)(?1)\)) *((?1)) *([*-/^])|(?<=[*/^]()|[+-]|())\(((?1)(?>\^()|[+-]()|.)(?1))\)(?!\^|(?!\7)\4|\8(?!\5($|[+-])))~${1:+($1$3$2):$6}~` [Try it online!](https://tio.run/##hVZtU@JIEP7Or2hcSzJJUF7U9QhoIUTljhcrJLe6IqkQAqYWApWE01XYn35ezySB8LbHB5Lp6ae783RPT5vTaXpomp9f@tbAdiy4ryhyTq@0qrKuNWuq/q1WVe/gIvHFdszRrG9BcWq6Vu745TJhvhgu6NOnZyiBcnD9@vqjl589/vz5oL6cv75wn94vrtMXhHmH466yhLvKE/rsEAI8k9DnE58@6T6TOXdVLD3x@MqR@ZOQfp5zhCAuAF52uqEYH8fMCprhrpKd7pz@fyWd03nngr6ecYdMkRDy6/AjWxC4w@xh/jBHCofni1@fZDPKAxH4aUmfSrEP9Py@PaEfGBe5tjNcl9kTlFrGeFvvMmE7Pkzx1dct1524nDlxPB8YYfzY8jxjaJEP9FMomKgAxSKEUvrK5JbTH0ngWv7MdSArLYCa9H46vvEW2iQf4W7c0UGbqQBbHRBpsRUKXZuTvkXgIwH4Y0GF3p9yZ@fPEhPbA@BYpvWhFUL1UIujcBG4oFS0yl1ZueBJuCmCZ79bkwEXfSacRJKYPqaHeaG/NRoOmFIQfgEO9jLD0Et2EougGPvWyB6XMhL0JpMRMuYaDg2XbjkiexjBo7ckb4Z8XOg@56QNAsXSct3DtRSa5fFk9HVmPDDGexF7g4kLnCR5ghBJIvKSVCl00tTqdWm5a408i6nwXqmU6nRSCA0QgrCBWewGsVCWml5gepEIkj02bIeLomEIQZgmSykvNZ8nuYAiKiIrA2tlJTEQ0ytm5vOIRSYQTy/EswuyIZ3nc@IfX8Vs7gx38AiYL1iIhxzhhePi5VX3QAziXfpbK9ia848xsvtB7mzfolULGJ60qk7eww4Ty8E0jDHp7f0EHjOC3GZScTODdTNeZGaw38xgzQwtjnxO92FSymChT9BeUNRt7bqt1lRNlXX5QZWbVbkK8@09rdmWVV1u3KuPUqx80A3mp@OkJBjQQvJebd98wcQNlofUwOynhqkCdTrf4fW23rou1yVU7WFP@iHFUGVEQQxVblbuWopclSD220LJm6h6vfUtCF2v1Mvt9soXnJyAOfP8yRjSYIxGk1fAO8Fw@vDUfYaR/cMCudIot03XnvoxFw9bLlT9uq097AhszYXlGL2RBZ0ZdDTmBlk0rT7k0n17aPvQeYs5qexwUqkpFa1xU5cjVzuc2A6cjGHMOl238x2tOXiyMC0x2/aG7Uq5LdflgJr9zFY3UNVWvV5WdCyaVrP@KO1BeVsoFVOy5mkH6s9NlHbfLDfk/4nwbQMVlfTvUc0NVKOsVu7Ckr8uV/5S5BtpF9PN@8qtB4bp/6ZUxpu2tbpaq9easvS7iJwNVLOllzW1hXm6VzUlxG6hZhsorXK/PMuaerMHpW2imreKLFcf93GG45YxG/mFjetPDi6@qCkORsYwuAWxee0bDZi94K6mNzPwriWFa1axKHV8683H0SO@lNhI4VoehiEGN64UNZbad5lJBgPPws3JzB9ZztB/kSB2ifNU3psNossYu2EUxXhqjywuvPHb96pCpmII/S4rLV2VlUatWVblKhoX4Yh5D5@hzwxZDSJJ19p5ebD/UG/9U0u7CNBRZPgWF5lmbAYjG3Ixnfmxpky5eaejBFPCGWiE0zEXJMt2xECfSPFbf8kSemfbx3TwwWswJ2RXt384McSBS/HyfrFLWx2@9bes3NAeXJebt@rdtoUwBEwI@o8PWzzhbLhCgrA1m9wySgIF5HQpRFws0YRIW8aDUllS6816nm/7MyTUXY2DLNnB15s6cssRcY0MTCwKQMCLjL2uJWjdire/ZMJwj1bxbodLCycM@bKE5RQ/fZt6NhwdRd@XXLY9RWkp2DQacqOlPO4swACyx3nSjnxiPjPrOovEnlCL@0JlJCL5saLl2DTKk4COWBSLtUn0nQBCqSpHhwwca95L8YJ8dXHs2i4BEbIi9TahdQ4D14p0SDRvrvrO@jFjumsiIsUaVLCPR3rZxJCcxWcO8pDOZvAHQiJ7DqfUfJZKT4CHdCILORDoUugmgv1sjs@fpBM5@Ar5tJDN8FRHyHdPu@w9A9Ey3IDTLu5khGAl5M74f03aYb3P9IiFl774Dw "C++ (gcc) – Try It Online") This is a single regex substitution to be repeatedly applied until it has nothing to match (or until there is no change, which has the same effect though slightly less efficient). The assumption is made that there is no leading or trailing space, only possible space between items. This seems a reasonable interpretation of the challenge's rules as stated. In the following explanation, `␣` represents a space: ``` s~ # Begin substitution - match the following: # Match an expression that shall be converted to infix, with parentheses # added. ( # Define subroutine (?1) as an argument to an operator, and # on the outermost level, capture this in $1: \d++ # Any number of digit characters, minimum one; force all of # them to be consumed (prevent backtracking). | # or... \( # An opening parenthesis (?1) # An argument (?3) # An operator (?1) # An argument \) # A closing parenthesis ) ␣* # Any number of spaces, minimum zero. ( # $2 = the following: (?1) # second argument ) ␣* # Any number of spaces, minimum zero. ([*-/^]) # Define subroutine (?3): Match an operator. The use of a # range means "," and "." can be matched, but that's okay # since they're guaranteed not to be in the input. | # Or, match an expression from which the surrounding parentheses shall be # removed. This can only match once everything matchable by the above has # already been processed. (?<= # Atomic lookbehind [*/^]() # \4 = set if preceded by '*' or '/' or "^" | [+-] # set nothing if preceded by "+" or "-" | () # \5 = set if not preceded by any operator ) \( # An opening parenthesis (to be deleted) ( # $6 = the following: (?1) # An argument (?> # Atomic group – lock in the match once this expression # completes. \^() # \7 = set if the operator is "^" | [+-]() # \8 = set if the operator is "+" or "-" | . # set nothing if the operator is "*" or "/"; it's fine to # use ".", because nothing besides an operator can be # between two arguments (we've removed all the spaces by # this point) and this expression is in an atomic group. ) (?1) # An argument ) \) # A closing parenthesis (to be deleted) (?! # Negative lookahead – assert the following can't match: \^ # Followed by the operator "^" | (?!\7) # Not using the operator "^", and: \4 # Preceded by the operator "*" or "/" or "^" | # or... \8 # Using the operator "+" or "-", and: (?! # Not matching the following: \5 # Not preceded by any operator, and: ( $ # Followed by nothing | # or [+-] # Followed by the operator "+" or "-" ) ) ) ~ # Replace with the following: ${1 # Conditional upon whether \1 is set: :+($1$3$2) # if \1 is set, concatenate $1 + $3 + $2 and surround that # with parentheses. :$6 # otherwise, replace with $6 (which is what was matched in # the second alternative, minus its parentheses). } ~ # No flags, not even global, which means each substitution # will only make one match, and then the next one will # start its search for a match from the beginning of the # string again. This is slightly less efficient, and done # for golf purposes. ``` This uses `PCRE2_SUBSTITUTE_EXTENDED`, which provides a syntax for conditional replacement. Sadly, neither PHP, R, nor Julia support this, even though the option has existed in PCRE2 for nearly 7 years now. This allows almost anything to be done in a single substitution, where before it would have required multiple substitutions. Without it, this problem would not have been possible in a single substitution, because its first stage inserts parentheses into a string that has none to begin with, but the second stage needs to remove parentheses without adding any. Some things may still be impossible with a single substitution. The entire state is represented by the current value of the string, and if a later stage needs to go pass through a state that intersects with the possible states of an earlier stage, it would be processed by that earlier stage rather than the later one. # Regex (Boost), ~~144~~ 146 bytes `s~(\d++|\((?1)(?3)(?1)\)) *((?1)) *([*-/^])|((?<=[*/^]()|[+-])|())\(((?1)(?>\^()|[+-]()|.)(?1))\)(?!\^|(?!\8)\5|\9(?!\6($|[+-])))~?1\($1$3$2\):$7~` [Try it online!](https://tio.run/##fVTbjuI4EH3PVxQMGuxcugn0bRLSSCPtw0qjfdiLtKvOEIXEgWhCEsVh@xb605ct24EOzDARwnZVnVPlqnJFZWkto2j3Ic2jbBMzmC6KgteXFVuyp4tVWd5r0SqsICgfvoIHv/c/Pz5@W0w2/zw///3n6uZxRXb8jfixYTQ@ITObktmEitWnFHQpEeuDbl3Ov9IGBVPvQcc9oc2DYQkRpYhU0Ht/3spxuZA8SERmPX/eiP876l83/iexvSEDRUDp28z2ycAeTAZjnzqD27cdPY2yb4JeekHpau8XTfGeFQvX91qa11BW@B@wqioqEhU5r0HeW18zzsMlo6@8jh0nQgOYTqGViq2UszzOXKhYvalysN0tCEr@nNfhU8tJX1tt11H/D2kC8tSn7lYlO2ZZuvZGLmAtMqSqwnzJiFTlplxCtSwOrBskvQtqklshhal3OC/wvKfVkzSPA0muyHRO4VUD/JKiAuK63DD2EvGlCZCeMGqd/PbXly/uQcsyzqSJzj1v6PtDhCqEYZxgtj8GyVAOllxRb7WtLMg6THOyj0YiDKPseUM@bJoeUSkSIvpOcJRvV4Kk3XTUNPssSoF5dWde39ETaTMZm59uTXt8jRrsjWiFFRoQqhsX0/vZvG@qeA/@jir5a/5vmKWxql1aM1FOwPDUpdp04wvq1KBsY@zxs1fQsSKY29GwS5Mc0/A9TXKeJjmiEc0xGQc1FMgk37vjyAfvOHkRrIs4WLsQbuoCeMcCe2Qd1kGSVrwOijx7huZEFWaZ22kndIv18vOhC4loLP6Y1tEKC5nsyxqF2A3DdOgAhtJ4cBJMKvSuapwFPtVvbgfFz6FE/Pwc6ulnqKdzqLVCffTg7Vy6foBaIoofob5LodtFxSwJN1ntwNGo6f8iqujAvsGSLFxCX2iwEc7NHxWFHGPdgNGClCYU2BIShk2e5kucMOWm7lROPL8XMX@k0ZLVWZozoqJKc1PZU/d0VLxQQLnoUSKqjk5ePPt9XrQzposSXzeQYlOfdGRQsTILI0akTxMvYALHH17hiEX4l2ivja6b2IOR0KCDYn9bNW@OIokEC6a1kxNl0SZ35Grb3RgmYNkj/MDQ7Bu4Ega2kF6CDpZmwxgMcTTmmtLbY31yaWljuIWJZdgjXdgYk/nVXO5HsD@2Criao2ZkqJMxvtb/i0Tl@c7KZH4CmZ7/AQ "C++ (gcc) – Try It Online") Ported to Boost's syntax, which uses parentheses, thus those in the replacement expression need to be backslash-escaped. Boost does not support alternatives of different widths in one lookbehind, so the `|(?<!\))()` alternative was moved outside. It also does not support bare backreference syntax with `\10` or higher (it'd have to be done as `\k<10>` instead), but that ended up not mattering (no non-capturing groups had to be used). [Answer] ## Python3, 140 chars Difficult to golf, but I've got it sub 200, so I guess it will do. ``` s=[] for k in input().split(): if k in ['+','-','*','/']:p=len(s);s=s[0:p-2]+['('+s[p-2]+k+s[p-1]+')']; else:s.append(k) print(s[0]) ``` Pushes and pops data to the stack and converts to infix ]
[Question] [ I'm a code golf novice, but I'm eager to give it a go. My challenge is: Write the shortest program in C which takes in a date `D` as input and outputs the date `D + 1 day` **Rules:** * program must compile only with `gcc progname.c -o progname` So no compiler/makefile tricks (if there are any) - compiler warnings don't matter * The input and output format must be `day/month/year` zero padding of single digit values does not matter: `1/3/1998` is equal to `01/03/1998` * It doesn't matter how you give the the program it's input date, it can be a program argument, `scanf` whatever. Output must be to `stdout` however * February has 29 days when the year is divisible by 4 * No date validation necessary, i.e. assume the input is always a valid date. * any integer year should be supported, i.e. `INT_MIN -> INT_MAX` Shortest code length wins, and there are extra points for extra bastardised C. ## My solution uses 126 123\* 121 characters Good luck ``` *s="%i/%i/%i",m,d;main(y){scanf(s,&d,&m,&y);printf(s,d,m,(d=d%((m>7^m&1)+27+(m-2?3:y%4?1:2))+1)-1?y:(m=m%12+1)-1?y:y+1);} ``` \*because of an idea Gareth's code gave me [Answer] Okay, it's been a while since I wrote any C but I'll give it a go: ``` m,y,*q="%d/%d/%d"; main(d){ scanf(q,&d,&m,&y); ++d>30+(m+(m>7))%2-(m^2?0:2-!(y%4))?(m+=d=1)>12?y+=m=1:0:0; printf(q,d,m,y);} ``` **120 characters**. With a bit of formatting(not that it makes it any more readable any more...): ``` m,y,*q="%d/%d/%d"; main(d) { scanf(q,&d,&m,&y); ++d>30+(m+(m>7))%2-(m^2?0:2-!(y%4))?(m+=d=1)>12?y+=m=1:0:0; printf(q,d,m,y); } ``` The compiler throws out warnings like nobody's business, but it works. I'm not sure I can get it any smaller than this now without stealing a couple of tricks from Griffin. With those tricks I can get to **116 characters**: ``` m,y,*q="%d/%d/%d"; main(d){ scanf(q,&d,&m,&y); printf(q,d,m,++d>30+(m>7^m&1)-(m^2?0:2-!(y%4))?(m+=d=1)>12?y+=m=1:y:y);} ``` [Answer] ## C, 112 chars Many months late, but I just saw it and decided to improve it. The leading `*` isn't needed for 32bit platforms (and some 64bit platforms), so it can perhaps be removed. ``` *s="%d/%d/%d"; main(y,m,d){ scanf(s,&d,&m,&y); d++>29+(m-2?m+m/8&1:!(y%4)-2)?d=m++<12||(y+=m=1):0; printf(s,d,m,y); } ``` Lots of similarity to Gareth's solution, but honestly - I didn't look. The only thing I did borrow was saving the format string in a variable (which is kind of obvious, but I missed it). I do fix a problem with Gareth's solution - it relies on the evaluation order of `printf` parameters. [Answer] ## C (in a way), ~~97~~ 71 I will lose fifty rep for this but it was necessary. The *actual* rule violation is that it doesn't quite do `INT_MIN..INT_MAX`; the range instead seems to be `0..1410065407` (on 64-bit Ubuntu 11... I'm saying nothing about portability :P). ``` main(){system("read a;date -d@$((`date -d$a +%s`+86400)) +%m/%d/%Y");} ``` (old version:) ``` d,e[9];main(){sprintf(e,"date -d@$((`date -d%s +%%s`+86400)) +%%m/%%d/%%Y",gets(&d))&system(e);} ``` [Answer] # C - 293 ``` #define w(x) while(*(i++)!='/');x=atoi(i); main(){char x[99];scanf("%s",x);f(x);} f(char* i){ int a=atoi(i),b,c,m[]={0,1,0,1,0,1,0,1,1,0,1,0,1}; w(b);w(c); if(b==2)if((a==28&&c%4)||a==29){a=1;b=3;}else a++;else if(a-m[b]-30==0)if(b==12){a=b=1;c++;}else{a=1;b++;}else a++; printf("%d/%d/%d",a,b,c);} ``` I've never really tried to golf C (and I am by no means an expert in C), but I feel this is pretty good. Basically it goes like this: get input from scanf, convert days, shift pointer, convert months, shift pointer, convert years (latter two have a #define to help), do logic with calendar logic. year%4 was a cool trick, and I have a month hash table indicating if the month is 30 or 31 days (kinda big to declare, but I think it was worth it). Finally, print. I'm sure there is a neat way to refactor using ternary (?:), but again, I'm no expert. EDIT: fixed some typos. [Answer] # 106 100 characters Another entry that breaks the year rule by supporting only the years 1 to 9999, and also implements correct leap year handling instead of following requirements. The code simply uses POSIX libraries while abusing the type system: ``` t[9],b[9],*f="%d/%m/%Y";main(){gets(b);strptime(b,f,t);t[3]++;mktime(t);strftime(b,99,f,t);puts(b);} ``` ]
[Question] [ # What am I? As a plant cell, your program/function/etc. must undergo photosynthesis: When the input is `6CO2+6H2O+light` in any order, output `C6H12O6+6O2` in any order. It does not have to be the same for each arrangement of the input. When the input is just `r`, replicate (i.e. output your own code). [quine](/questions/tagged/quine "show questions tagged 'quine'") rules apply. When input is anything else, output the input (i.e. cat program) (so your cell doesn't expend energy by trying to process useless chemicals) # Rules without the cell's whole life story When the input is any of the following: ``` 6CO2+6H2O+light 6CO2+light+6H2O 6H2O+6CO2+light 6H2O+light+6CO2 light+6CO2+6H2O light+6H2O+6CO2 ``` Output either `C6H12O6+6O2` or `6O2+C6H12O6`. You do not have to output the same one for each of the 6 inputs. When the input is just `r`, be a quine (output the source code). When the input is anything else (or empty), be a cat program (output the input). Your answer/submission may be a full program, or a function, etc. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default/) apply (as always); especially [this.](https://codegolf.meta.stackexchange.com/a/10033/) ## Python, *ungolfed noncompeting example* Noncompeting as it breaks quine rules. ``` inp = input() s = input.split('+') # List of chemicals a = '6CO2' in s # Has CO2 b = '6H2O' in s # Has H2O c = 'light' in s # Has light d = len(s) == 3 # Only those 3 output_sugar = a and b and c and d if output_sugar: print('C6H12O6+6O2') # output text elif inp == 'r': print(open(__file__).read()) # quine else: print(inp) # cat program ``` # Scoring [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") - i.e. lowest byte count 'wins' (as bigger ~~programs~~ cells will have less surface-to-volume ratio and thus make it harder to intake energy) ### Cell`s Life: S̵̲̿̈́ę̴̬̓r̷͈͑͜i̵̝̔̇ė̴̛̯̹s̶̢͋̓ ?̶̦͓̰̻̀ ̶̳͇͚̆Ŝ̸̭̤̱̅̔̚t̷̜̩̯̀̿à̶͑͝y̴͚̼͇͊͒̚ ̷̍ͅt̶̮̥̥͌̂ͅủ̵͎n̸͔̉ē̷̊̕d̴̟̭͎͐̈́͝ ̸̗͇̓͗̚?̸̡̗̲͑͛͌ [Answer] # [Ruby](https://www.ruby-lang.org/) `-p`, ~~96~~ 87 bytes ``` eval q="$_=%w[6CO2 6H2O light]-$_.split(?+,3)==[]?'C6H12O6+6O2':/^r$/?'eval q=%p'%q:$_" ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpclm0km6BUuzS5Iz83IKlpSVpuhY3w1PLEnMUCm2VVOJtVcujzZz9jRTMPIz8FXIy0zNKYnVV4vWKC3IySzTstXWMNW1to2Pt1Z3NPAyN_M20zfyN1K3044pU9O3VocaoFqirFlqpxCtBjF-mEq9tq6IP4Sy42QIyXhtkvDbYeC4wH8wEi3KBpRCCXAilYFEuBBOiHqEVIl_EVVTEhWaJNlQAJgpxDAA) The code is an extension of the Ruby quine ``` eval q="$><<'eval q=%p'%q" ``` The optional second argument to `split` is needed to avoid false positives on inputs like `6CO2+6H2O+light+`. The check for an input of `r` uses a [bare regex literal as a conditional](https://codegolf.stackexchange.com/questions/363/tips-for-golfing-in-ruby#comment496182_5050), saving a byte over the more obvious `$_==?r` but provoking a warning from the interpreter. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~77~~ 70 bytes ``` “+“6CO2+6H2O+light r“C6H12O6+6O2“ḣ2œṣṢjɗḲi¥@ƭƒ³ị3ị,Ṿ;⁾0ị,⁾vƊƊƲ³ṭƊ”0ịvƊ ``` [Try it online!](https://tio.run/##y0rNyan8//9RwxxtIDZz9jfSNvMw8tfOyUzPKFEoAoo5m3kYGvmbaZv5GwF5D3csNjo6@eHOxQ93Lso6Of3hjk2Zh5Y6HFt7bNKhzQ93dxsDsc7DnfusHzXuMwCxgXTZsS4g3ASU37n2WNejhrkgCaDg////EVZpg6wGAA "Jelly – Try It Online") A full program link taking a string argument and printing a string argument. This currently feels a little verbose for a Jelly answer! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 98 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 1"D34çýU'rQiXë“6CO26H2O“2ä'‡Žªœ'+ýIåi“C6H12O6+6O2"D34çýU'rQiXë“6CO26H2O“2ä'‡Žªœ'+ýIåi“C6H12O6+6O2 ``` Outputs the `C6H12O6+6O2` with two instead of one trailing newlines. Could be fixed in +2 bytes by adding `“` after both `C6H12O6+6O2` in the program. [Try it online.](https://tio.run/##yy9OTMpM/f/fUMnF2OTw8sN7Q9WLAjMjDq9@1DDHzNnfyMzDyB/INDq8RP1Rw8Kjew@tOjpZXfvwXs/DSzOB4s5mHoZG/mbaZv5GFBvA9f8/SLF2TmZ6Rok2SC8A) **Explanation:** ``` 1 # Push a 1 "..." # Push the program's source code D # Duplicate it 34ç # Push 34, and convert it to a character with this codepoint: '"' ý # Join the stack with '"'-delimiter U # Pop and store this quine-string in variable `X` 'rQi '# If the (implicit) input is "r": X # Push quine-string `X` # (which is output implicitly with trailing newline) ë # Else: “6CO26H2O“ # Push string "6CO26H2O" 2ä # Push it into two equal-sized parts: ["6CO2","6H2O"] '‡Ž '# Push dictionary word "light" ª # Append it to the pair œ # Get all six permutations of this triplet '+ý '# Join each inner triplet with "+"-delimiter Iåi # If the input is in this list: “C6H12O6+6O2 # Push string "C6H12O6+6O2\n" # (which is output implicitly with trailing newline) # (implicit else) # (implicitly output the implicit input with trailing newline) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 79 bytes ``` f=x=>x.split`+`.sort().join`+`=='6CO2+6H2O+light'?'6O2+C6H12O6':x=='r'?'f='+f:x ``` [Try it online!](https://tio.run/##fYyxCsMgFEX3/shTpEId3hCwHbJk8xcS0pgaxBdUin9vzdQlZLyHc@42fac0R7fne6D3UqvVRT@LTLt3eRSjTBQz43IjF9rUGrA3SuCgjPBu/WR4ATbQ4/BQBqErTYkNWg3CdqXOFBL5RXpamWXwD8VxBJzfLo0TIR6s/gA "JavaScript (Node.js) – Try It Online") Nothing special [Answer] # Google Sheets, 109 bytes `=ifs(""=A1,,"6CO2+6H2O+light"=join("+",sort(tocol(split(A1,"+")))),"C6H12O6+6O2","r"=A1,formulatext(F1),1,A1)` Put the input in cell `A1` and the formula in cell `F1`. Uses a `cat $0` type quine, so non-competing. [Answer] # Python 3, ~~164~~ 142 bytes ``` m=r'm=%r;a=input();print("C6H12O6+6O2"if{"6H2O","6CO2","light"}==set(a.split("+"))else"m=r\x27"+m+"\x27;exec(m%%m)"if a=="r"else a)';exec(m%m) ``` Here is a Python quine that meets all the requirements. ]
[Question] [ Your program should take two lists, where each entry (a positive integer) represents the number of members of some group, as input. These lists will have the same sum but may have different lengths. Your mission, should you choose to accept it, will be to pair up members of the first list with members of the second, outputting a list of triples of the form `(i, j, n)` where `i` is an index into the first input list, `j` is an index into the second input list, and `n` is the number of members of group `i` from the first list who are paired up with a member of group `j` from the second list. Every member of both lists should be paired up in this way. In pseudocode, `∀i, sum(n for (i1, _, n) in output if i1 == i) == first_list[i]`, and `∀j, sum(n for (_, j1, n) in output if j1 == j) == second_list[j]`, `all(n > 0 and is_integer(n) for (_, _, n) in output)`, where `first_list` and `second_list` are the two input lists, and `i` and `j` range over valid indices into the respective inputs. Your output list must have minimal length among all valid solutions. Zero-based and one-based indexing are both acceptable. Shortest answer wins. ### Example Input: `[3, 4, 5] [5, 6, 1]` Possible optimal output: `[(0, 1, 3), (1, 1, 3), (1, 2, 1), (2, 0, 5)]` ``` list 1 list 2 i j n [ 3 0 0 ] [ 0 3 0 ] (0, 1, 3) + [ 0 3 0 ] [ 0 3 0 ] (1, 1, 3) + [ 0 1 0 ] [ 0 0 1 ] (1, 2, 1) + [ 0 0 5 ] [ 5 0 0 ] (2, 0, 5) --------------------- = [ 3 4 5 ] [ 5 6 1 ] ``` ### Test cases The test cases use zero-based indexing. ``` [3, 4, 5] [5, 6, 1] -> [(0, 1, 3), (1, 1, 3), (1, 2, 1), (2, 0, 5)] (length 4 optimal) [4, 3, 1, 5] [2, 1, 3, 7] -> [(1, 2, 3), (2, 1, 1), (0, 3, 4), (3, 3, 3), (3, 0, 2)] (length 5 optimal) [1, 7, 5] [4, 5, 4] -> [(0, 0, 1), (1, 2, 4), (1, 0, 3), (2, 1, 5)] (length 4 optimal) [4, 5, 5] [3, 7, 4] -> [(0, 2, 4), (1, 1, 5), (2, 0, 3), (2, 1, 2)] (length 4 optimal) [4, 3] [3, 1, 3] -> [(0, 0, 3), (0, 1, 1), (1, 2, 3)] (length 3 optimal) [4, 3, 2] [4, 5] -> [(0, 0, 4), (1, 1, 3), (2, 1, 2)] (length 3 optimal) [] [] -> [] (length 0 optimal) ``` [Answer] # [Scala](https://www.scala-lang.org/), ~~222..187~~ 180 bytes *-7 bytes thanks to [user](https://codegolf.stackexchange.com/users/95792)!* ``` x=>y=>{var(a,b,r)=(x,y,Set[Any]()) while(a.sum>0){var?,m=a.max min b.max var p,q= -1 while(p<0|q<0){if(p<0)p=a indexOf? if(q<0)q=b indexOf? ? +=1} a(p)-=m b(q)-=m r+=Seq(p,q,m)} r} ``` [Try it online!](https://tio.run/##fZDLbsIwEEX3/ooRK1sYRKAUCeEgllVbdYG6Ql04YIqrxDiJoUlpvj11HkBAhZXnce7M9cRL7vN8632JpYFnEIkRahXDTGs4IIA99yGQSgbc749hFkU8XTwp8wHMvcrmwixmKrVxnjA3Ze5hzyPMqUcjwnBCU3okMCHoeyN9gXk33gVujxTolAaMdwOeFPvAKyJky6BpyKDj1Ao96f2GE6uQ6yImmnGQaiWSt/UU2VrRC5l3rk2hzZwMcaxJhwXIw2H5Rm02FyG2w2lAMhRlOcBKrI9/xUnzsxTSZkqAnW6CE4JTgupL6Ugq81q1xoCbEy7kLrwraYBZGYC9DaRl8VDm1ajtzuidOW@qqBoo9/gKV9B1tfUi1KfZjKEF7XpON5Y/4pqr8qww3zRe2cYDCg8UhqS2jocUHik4hPyPW9YqnKaiX@a2Orolsu1RU1EstGvv7Bg28UEpv4cPmmxh5r79/oWTW@wJsgDK8j8) [Answer] # JavaScript (ES6), 137 bytes ``` a=>g=(b,k=O=0,o=[],n,c)=>O=O&&!O[k]||a.map((p,i)=>b.map((q,j)=>b[a[i]-=n=p<q?p:q,b[j]-=n,n&&g(b,k+1,[...o,[i,j,c=n]]),a[i]=p,j]=q))|c?O:o ``` [Try it online!](https://tio.run/##jc/BbsMgDADQ@76CXSLQXNo0zSpVc/sJ@QDEgbA0C82ArNVO@fcM0lRTqx7CyTZ@Nhj1q876p/GXhXWf1XDEQeG@RlrCCQtcgUMhwYJmuC@wSJLXQpxk3yv@rTylHppwUV6TDkxMhBKNXKBF/9Ed/K6DUpiYg02SOs59S0Fwzh2IBgxotFIyiAg9GIkdY70@FDs3aGfPrq1462p6pCIDsgGSS0ZFDuQdSCoZI9ezXJK2svXli2xeHlgwQaaTXI9hKGwj/mf5Iwtd28nErWH33G35xLJxwmyWTSYdw5u5Y9nzv61vj5zLYv9dL3nGVsMf "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // outer function taking the 1st list a[] g = ( // inner function taking: b, // the 2nd list b[] k = O = 0, // k = length of current solution, O = output o = [], // o[] = current solution n, // n is a local variable c // c is a flag telling whether both lists are cleared ) => // O = // update O: O && // abort if an output is already defined !O[k] || // and it's shorter than the current solution a.map((p, i) => // otherwise, for each value p at position i in a[]: b.map((q, j) => // for each value q at position j in b[]: b[ // a[i] -= // subtract n from a[i] n = p < q ? p : q, // where n = min(p, q) b[j] -= n, // subtract n from b[j] n && g( // if n > 0, do a recursive call: b, // pass b[] unchanged k + 1, // increment k [ ...o, // update the solution o[] [i, j, c = n] ] // with the triplet [i, j, n] // and set the flag c ), // end of recursive call a[i] = p, // restore a[i] j // ] = q // restore b[j] ) // end of inner map() ) | c ? // end of outer map(); if c is set: O // leave O unchanged : // else: o // update O to o ``` ]
[Question] [ Chat room: <https://chat.stackexchange.com/rooms/106513/easter-bunny-challenge> Git repo: <https://github.com/AJFaraday/easter_bunny_hunt> The garden is a 2-dimensional grid with 49 rows and 49 columns. The Easter Bunny™️ is in the center of the garden, minding his own business, holding on to 100 Easter eggs. He'll hop away from where the most people are. When the Easter Bunny™️ hops, we all know he'll leave behind an Easter egg. Grab an Easter egg for 1 point. Grab the Easter Bunny for 10 points. The game starts with 4 kids, one in each corner of the garden. The kids can take 1 step each turn, in one of the 4 cardinal directions (North, South, East or West). When they've each taken a step (or decided not to), the bunny will take a move. The bunny can hop to any position up to 4 spaces away in both the x and y axes. It will decide where it will hop to by the position of the kids. The bunny can see kids within 5 spaces of it in any direction (I'm using square distances for simplicity). For each axis, (ignoring the kids in a line with it) it will move away from the most kids it can see. e.g. * If it can see 1 kid to the right, and none to the left. it will hop 1 step to the west. * If it can see 3 below, and 1 above, it will hop 2 step north. * If there are 2 north, 1 south, and 2 west. it will hop directly to a space 1 step south and 2 steps west. Important quirks: * The bunny ignores kids on the same row when working out it's north/south hop, and in the same column for it's east/west. * If it can't see any kids, it will stay still until it can. * If the left/right and up/down counts are equal, it will reamin rooted to the spot, like a rabbit in the headlights. The game ends when: * The Easter Bunny™️ leaves the garden. * The Easter Bunny™️ drops his last egg. * The kids catch the bunny. * The game reaches the configurable turn limit ## Config You can edit conig.js to change two things about the run: * `match_limit` will allow you to end the game when you decide (competition will use 1,000 turns) * `turn_time` (ms) will set the interval when the game is rendering. ## How to hunt the bunny? Your code will take the form of an array of 4 JS functions, which will each control a kid starting in these positions (in this order): * North West (0, 0) * North East (0, 48) * South East (48, 48) * South West (48, 0) The functions should each have this fingerprint: ``` function(api) { } ``` api is your function's interface to the game (see below). ### The API The api object presents these four movement functions: * `api.north()` * `api.east()` * `api.south()` * `api.west()` If any of these are called during your function, the kid will take one step in that direction (or the last called of these four directions). If none of thess are called during your function, the kid will stand still. It also provides information about the state of the game with these methods: * `api.my_storage()` - an object you can use to store data and functions for just this kid. * `api.shared_storage()` - an object you can use to store data and functions for the whole team. * `api.turn()` - Returns a number of turns taken in this game so far. * `api.bunny()` - Returns an object of bunny-related info { x: 24, y: 24, eggs\_left: 100 } * `api.kids()` tells you where all the kids are [ {x: 0, y: 0, me: true}. ... ] * `api.eggs()` tells you qhere all the eggs are [ {x: 25, y: 25} ] ### Template Teams.push( { name: 'template', shared\_storage: {}, functions: [ function(api) { // NW kid }, function(api) { // NE kid }, function(api) { // SE kid }, function(api) { // SW kid } ] } ); * `name` must be a single-word identifier, if you want to run just a single entry. * `shared_storage` sets the initial state of `api.shared_storage`, it can be used to set data and functions for your team. * The array `functions` is the behaviour of the 4 kids chasing the bunny. ### How to participate Change my\_entry to your own team name. * `git clone https://github.com/AJFaraday/easter_bunny_hunt.git` * `cd easter_bunny_hunt` * `npm install -g terser` * `cp template.js teams/my_entry.js` * (Write your team code) * `script/run.sh my_entry` to watch the game * `script/run.sh` to see all results (if you import more entries) When you're happy with the result, copy it in to an answer like so: ``` # my_entry - 10 points Any description you want to add goes here Teams.push( { name: 'template', shared_storage: {}, functions: [ function(api) { // NW kid }, function(api) { // NE kid }, function(api) { // SE kid }, function(api) { // SW kid } ] } ); ``` ### Competition rules Official scoreboard will be updated roughly once a day. This will run until the 19th of April, one week after Easter Sunday (in the traditions which celebrate Easter Sunday on the 12th of April this year). [Answer] # The Run of Doom, score 109 ``` var kid_api = function (api) { var bunny = api.bunny(); var kids = api.kids(); for (var i = 0;i<kids.length;i++) { if(kids[i].me) { var me = kids[i]; if (me.x < 24) { return api.east(); } else if (me.x > 24) { return api.west(); } else { var s = api.shared_storage(); var my_data = s[i]; if (!my_data) { return; }else if (my_data.backaway == bunny.eggs_remaining) { return; }else if(bunny.y == me.y + my_data.y && bunny.eggs_remaining != 1) { s[2] = Object.assign({}, s.opposites[my_data.func]) s[0] = Object.assign({}, s.opposites[my_data.func]) s[2-i].backaway = bunny.eggs_remaining; s[i].backaway = 1; api[s[i].func](); } else if (me.y + my_data.y < 0 || me.y + my_data.y > 49) { s[i] = null; } else { api[my_data.func](); } } } } } Teams.push( { name: 'the_run_of_doom', shared_storage: { 2: {"func": "north", "y": -1}, 0: null, "opposites": { "south":{"func": "north", "y":-1}, "north":{"func":"south", "y":1} }, }, functions: [ kid_api, function(api) { // NE kid }, kid_api, function(api) { // SW kid } ] } ); ``` Uses only two kids: one that starts on the north side, and one that starts on the south side (this version uses NW and SE, but it could be rewritten to use NE and SW, or NE and SE, or NW and SW fairly easily). With a little more effort, one could do this with any combination of two kids. A score of 110 isn't possible, since the game always ends immediately after the bunny drops the last egg, so I believe this answer is unbeatable. [Answer] # random - 0 to 33 points Totally random kids! ``` Teams.push( { name: 'random', shared_storage: { sequence: 'abcd', take_step: function(api) { var char = api.shared_storage().sequence[Math.floor(Math.random() * 5)]; if(char) { api[api.my_storage()['key'][char]](); } } }, functions: [ function(api) { // NW kid if(!api.my_storage()['key']) { api.my_storage()['key'] = {'a': 'east', 'b': 'south', 'c': 'west', 'd': 'north'} } api.shared_storage().take_step(api); }, function(api) { // NE kid if(!api.my_storage()['key']) { api.my_storage()['key'] = {'a': 'east', 'b': 'south', 'c': 'west', 'd': 'north'} } api.shared_storage().take_step(api); }, function(api) { // SE kid if(!api.my_storage()['key']) { api.my_storage()['key'] = {'a': 'east', 'b': 'south', 'c': 'west', 'd': 'north'} } api.shared_storage().take_step(api); }, function(api) { // SW kid if(!api.my_storage()['key']) { api.my_storage()['key'] = {'a': 'east', 'b': 'south', 'c': 'west', 'd': 'north'} } api.shared_storage().take_step(api); } ] } ); ``` ]
[Question] [ **This question already has answers here**: [Evaluate the nth hyperoperation](/questions/11520/evaluate-the-nth-hyperoperation) (15 answers) Closed 5 years ago. # Introduction > > In mathematics, the hyperoperation sequence is an infinite sequence of arithmetic operations (called hyperoperations) that starts with the unary operation of successor (n = 0), then continues with the binary operations of addition (n = 1), multiplication (n = 2), and exponentiation (n = 3), after which the sequence proceeds with further binary operations extending beyond exponentiation, using right-associativity. > > > ([Source](https://en.wikipedia.org/wiki/Hyperoperation)) --- # Challenge Your challenge is code this sequence, given 3 inputs, *n*, *a*, and *b*, code a function such that $${\displaystyle H\_{n}(a,b)={\begin{cases}b+1&{\text{if }}n=0\\a&{\text{if }}n=1{\text{ and }}b=0\\0&{\text{if }}n=2{\text{ and }}b=0\\1&{\text{if }}n\geq 3{\text{ and }}b=0\\H\_{n-1}(a,H\_{n}(a,b-1))&{\text{otherwise}}\end{cases}}}$$ (Also from Wikipedia.) --- # Input 3 positive decimal integers, *n*, *a*, and *b*, taken from STDIN, function or command line arguments, in any order. Make sure to specify this in your answer --- # Output The result of applying \$H\_{n}(a,b)\$ with the inputs --- # Example inputs and outputs Input: `0, 6, 3` Output: `4` --- Input: `4 5 2` Output: `3125` --- # Restrictions * Your program/function should take input in base 10 * Don't use any built in function that already provides H(n, a, b) * Standard loopholes apply --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! [Answer] # Dyalog APL, 35 bytes ``` {⍺=0:⍵+1⋄⍵=0:⍺⍺⍵1⊃⍨3⌊⍺⋄(⍺-1)∇⍺∇⍵-1} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3@NR24TqR727bA2sHvVu1TZ81N0CpMG8XWC01fBRV/Oj3hXGj3q6QALdLRpAStdQ81FHO4gPIrfqGtb@//@od65CnoJGooKHpkISl6GGIZBhyGWgYQakjblMNEyBtBEA "APL (Dyalog Unicode) – Try It Online") [Answer] # JavaScript (ES6), ~~49~~ 47 bytes Takes input as `(a)(b,n)`. ``` a=>g=(b,n)=>n*b?g(g(b-1,n),n-1):-~[b,a-1,-1][n] ``` [Try it online!](https://tio.run/##VchLDkAwEADQvZPMyIyo30JSDiIWrU9DZCqIpauXreV7q7nNORzLfrH4cQqzDkY3ToMlQd1IbFsHDiyrzySssOans2S@YNV30ofBy@m3Kdm8gxkqhJxSxOjfJUJGBWJ4AQ "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // main function taking a g = (b, n) => // g = recursive function taking b and n n * b ? // if neither n nor b is equal to 0: g( // go recursive: g(b - 1, n), // b = g(b - 1, n) n - 1 // decrement n ) // end of recursive call : // else: -~[ // this is a leaf node: b, // if n = 0, return b + 1 a - 1, // if n = 1, return (a - 1) + 1 = a -1 // if n = 2, return -1 + 1 = 0 ][n] // if n > 2, return -~undefined = 1 ``` [Answer] # [Elixir](https://elixir-lang.org/), 86 bytes (assumes functions can take a reference to itself as an argument) ``` fn 0,_,b,_->b+1 1,a,0,_->a 2,_,0,_->0 _,_,0,_->1 n,a,b,f->f.(n-1,a,f.(n,a,b-1,f),f)end ``` [Try it online!](https://tio.run/##hU09C8IwEN3zK45MCV5CW3S0u5ODqxBSTdpAiSWN4L@PF7HgJhzH@@I9N4dXSGU6Fh@hQYMDGtUPu5a1aLGpxLKO9A9smNlgyyIFBvSq91pEVeMVVJGIl3Qu3svosgkxu9ElOAKNqB4uOYU46vzYHPFVkltme3MmJxtmEsTprKlgFZxLBH6NnD6XEqiZkbc88wqTFj8jWlDyH59k2bMD694 "Elixir – Try It Online") ]
[Question] [ A game of 2048 goes like this: * Every move you get another piece - either `2` 90% of the time, or `4` 10% of the time * for each 2 equal pieces combined you get a piece of the sum of the two and the sum gets added to your score # Your task given a board of a 4x4 game, give the average score of what A game like that would result in. To calculate it, go the other way around of the game. For example, if there's an `8` piece, it's made from `4`s. The average score of a 4 piece is 4\*90% (90% of the time it's made from combining two `2` pieces together and it the other 10% a `4` isn't made, but ) = 3.6. As to make an `8` you need two `4`s, and then you need to combine them to an `8`, the result is 3.6\*2 + 8 = 15.2. In pseudocode a calculation for one number could be this: ``` function value (x) { if (x > 4) return value(x / 2) * 2 + x else if (x == 4) return 4*90% else return 0 } ``` but you're free to choose any approach as long as it works the same. ## Clarifications * The input board will always be from a 4x4 board. * You can take in the board as an array of the 16 values, as 16 different inputs or even a 2D array if that somehow helps you. * The input numbers will always be zero or 2 to the power of a positive integer. * You can discard any errors due to floating point operations (but theoretically the program must implement a correct algorithm). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code wins! ## Test-cases ``` [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] -> 0 [2,4,2,4,4,2,4,2,2,4,2,4,4,2,4,2] -> 28.8 [4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4] -> 57.6 [0,0,0,4,0,0,0,8,0,0,0,16,2,2,0,2048] -> 20340.4 [2,16,2048,4096,4,32,1024,8192,8,64,512,16384,16,128,256,32768] -> 845465.2 [8,8,4,4,0,0,0,0,0,0,2,2,2048,65536] -> 996799.2 ``` [Answer] # [Python 3](https://docs.python.org/3/), 51 48 bytes -3 bytes thanks to [Mr. Xcoder!](https://codegolf.stackexchange.com/users/59487/mr-xcoder) ``` lambda b:sum(n*max(0,len(bin(n))-4.1)for n in b) ``` [Try it online!](https://tio.run/##lU5BDoIwELz7ig2n1hTTllILiX4EOUCUSFIKQUz09dgWIXDTZNLMTHd2tnsP99ZEY3W6jLpoymsBZfp4Nsjsm@KFKNE3g8raIINxKA4MV20PBmoDJR4d145nGSXwB3ICGScgCEzvQviKbHyXELP3E1xiaRSrdrXiTM6dVnAq1Pcy71tpkzSRPh85m3LLFEu4XyOtiJkfj5SYUozbDx5LFzhKv0/5YbG9YsFUP5XJOI5knqc76PraDEgTCMJzQKBCGuPxAw "Python 3 – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 101 100 bytes ``` n=>{double k=0,l=0;for(int i=0,j;i<n.Length;l+=k,++i)for(j=4;j<=n[i];j*=2)k=j>4?k*2+j:3.6;return l;} ``` [Try it online!](https://tio.run/##jVDBToQwEL3zFT3CUgmUUllL8WDiaT0YDx42e1jZioVaElo0hvDtWCAazZpIMpnMvM68ea@Fviialo@dFqoEDx/a8FfqFPKoNbjvHW2ORhTgrREncHcUyvV657ZTRSaU2R/gqemeJM9LNiqW90sHahZCyUL63LSuHQPC9hUVmQp2XJXmhUqf1dD3hTdNVAzTKmNqLw602jDk1azK8XW9QX51FQeEttx0rQKSDiN1bhqlG8mDx1YYvhOKu6Wr@DuY5fQIAgzBkr8L9KP4hQ@e9x8h/lpZFSsIQwjOI/0LnGIFofUSEWsmxJYFh1syS4knOES2SqMtmi8Q2yTRPB6neNmKkH1ACZkWLkm64lw6cy1@zwUvX71oIUkSk5lxGMZP "C# (.NET Core) – Try It Online") Lambda function. Takes in an array for the board, and returns a double for the score [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 18 bytes ``` +/{⍵×0⌈2.1-⍨≢⊤⍵}¨⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97b@2fvWj3q2Hpxs86ukw0jPUfdS74lHnokddS4CitYdWPOqbClL3P40LyPIK9vdTUI820MELY9UB "APL (Dyalog Extended) – Try It Online") or [Verify all test cases](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97b@2fvWj3q2Hpxs86ukw0jPUfdS74lHnokddS4CitYdWPOqbClL3P40LyPIK9vdTUI820MELY9W5kFUb6ZjogDCENNJB46OpNtHBC9FUQ2w0gdpsAaUNzcDWGOgYGZhYYLgGJAsU1zExsDQDajUGihgYmehYGFoaAU0wM9ExNQQpMrYwASk1NLLQMTI1AyozN0M3ywKo3gRuOwSCLAYbb2ZqamwWqw4A "APL (Dyalog Extended) – Try It Online") Full program submission. Port of the Python answer. ## Explanation ``` +/{⍵×0⌈2.1-⍨≢⊤⍵}¨⎕ ¨⎕ to each element of the input: ⊤⍵ convert to base 2 digits 2.1-⍨≢ length - 2.1 0⌈ maximum with 0 ⍵× times the element +/ sum the resulting array ``` [Answer] # JavaScript (V8), 58 bytes ``` b=>b.reduce((a,n)=>a+(z=x=>x>4?z(x/2)*2+x:x-4?0:3.6)(n),0) ``` ]
[Question] [ I'm always forgetting Pokemon type matchups. This is a challenge to print the pokemon type chart! ``` Attacking Type No Fi Fl Po Gr Ro Bu Gh St Fr Wa Gr El Ps Ic Dr Da Fa Normal 1.0 2.0 1.0 1.0 1.0 1.0 1.0 0.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 Fighting 1.0 1.0 2.0 1.0 1.0 0.5 0.5 1.0 1.0 1.0 1.0 1.0 1.0 2.0 1.0 1.0 0.5 2.0 D Flying 1.0 0.5 1.0 1.0 0.0 2.0 0.5 1.0 1.0 1.0 1.0 0.5 2.0 1.0 2.0 1.0 1.0 1.0 e Poison 1.0 0.5 1.0 0.5 2.0 1.0 0.5 1.0 1.0 1.0 1.0 0.5 1.0 2.0 1.0 1.0 1.0 0.5 f Ground 1.0 1.0 1.0 0.5 1.0 0.5 1.0 1.0 1.0 1.0 2.0 2.0 0.0 1.0 2.0 1.0 1.0 1.0 e Rock 0.5 2.0 0.5 0.5 2.0 1.0 1.0 1.0 2.0 0.5 2.0 2.0 1.0 1.0 1.0 1.0 1.0 1.0 n Bug 1.0 0.5 2.0 1.0 0.5 2.0 1.0 1.0 1.0 2.0 1.0 0.5 1.0 1.0 1.0 1.0 1.0 1.0 d Ghost 0.0 0.0 1.0 0.5 1.0 1.0 0.5 2.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 2.0 1.0 i Steel 0.5 2.0 0.5 0.0 2.0 0.5 0.5 1.0 0.5 2.0 1.0 0.5 1.0 0.5 0.5 0.5 1.0 0.5 n Fire 1.0 1.0 1.0 1.0 2.0 2.0 0.5 1.0 0.5 0.5 2.0 0.5 1.0 1.0 0.5 1.0 1.0 0.5 g Water 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 0.5 0.5 0.5 2.0 2.0 1.0 0.5 1.0 1.0 1.0 Grass 1.0 1.0 2.0 2.0 0.5 1.0 2.0 1.0 1.0 2.0 0.5 0.5 0.5 1.0 2.0 1.0 1.0 1.0 T Electric 1.0 1.0 0.5 1.0 2.0 1.0 1.0 1.0 0.5 1.0 1.0 1.0 0.5 1.0 1.0 1.0 1.0 1.0 y Psychic 1.0 0.5 1.0 1.0 1.0 1.0 2.0 2.0 1.0 1.0 1.0 1.0 1.0 0.5 1.0 1.0 2.0 1.0 p Ice 1.0 2.0 1.0 1.0 1.0 2.0 1.0 1.0 2.0 2.0 1.0 1.0 1.0 1.0 0.5 1.0 1.0 1.0 e Dragon 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 0.5 0.5 0.5 0.5 1.0 2.0 2.0 1.0 2.0 Dark 1.0 2.0 1.0 1.0 1.0 1.0 2.0 0.5 1.0 1.0 1.0 1.0 1.0 0.0 1.0 1.0 0.5 2.0 Fairy 1.0 0.5 1.0 2.0 1.0 1.0 0.5 1.0 2.0 1.0 1.0 1.0 1.0 1.0 1.0 0.0 0.5 1.0 ``` It has to take an optional parameter that specifies a single type and then prints the dual type chart for that type, which looks like: ``` Attacking Type No Fi Fl Po Gr Ro Bu Gh St Fr Wa Gr El Ps Ic Dr Da Fa Electric/- 1.0 1.0 0.5 1.0 2.0 1.0 1.0 1.0 0.5 1.0 1.0 1.0 0.5 1.0 1.0 1.0 1.0 1.0 Electric/Normal 1.0 2.0 0.5 1.0 2.0 1.0 1.0 0.0 0.5 1.0 1.0 1.0 0.5 1.0 1.0 1.0 1.0 1.0 D Electric/Fighting 1.0 1.0 1.0 1.0 2.0 0.5 0.5 1.0 0.5 1.0 1.0 1.0 0.5 2.0 1.0 1.0 0.5 2.0 e Electric/Flying 1.0 0.5 0.5 1.0 0.0 2.0 0.5 1.0 0.5 1.0 1.0 0.5 1.0 1.0 2.0 1.0 1.0 1.0 f Electric/Poison 1.0 0.5 0.5 0.5 4.0 1.0 0.5 1.0 0.5 1.0 1.0 0.5 0.5 2.0 1.0 1.0 1.0 0.5 e Electric/Ground 1.0 1.0 0.5 0.5 2.0 0.5 1.0 1.0 0.5 1.0 2.0 2.0 0.0 1.0 2.0 1.0 1.0 1.0 n Electric/Rock 0.5 2.0 0.3 0.5 4.0 1.0 1.0 1.0 1.0 0.5 2.0 2.0 0.5 1.0 1.0 1.0 1.0 1.0 d Electric/Bug 1.0 0.5 1.0 1.0 1.0 2.0 1.0 1.0 0.5 2.0 1.0 0.5 0.5 1.0 1.0 1.0 1.0 1.0 i Electric/Ghost 0.0 0.0 0.5 0.5 2.0 1.0 0.5 2.0 0.5 1.0 1.0 1.0 0.5 1.0 1.0 1.0 2.0 1.0 n Electric/Steel 0.5 2.0 0.3 0.0 4.0 0.5 0.5 1.0 0.3 2.0 1.0 0.5 0.5 0.5 0.5 0.5 1.0 0.5 g Electric/Fire 1.0 1.0 0.5 1.0 4.0 2.0 0.5 1.0 0.3 0.5 2.0 0.5 0.5 1.0 0.5 1.0 1.0 0.5 Electric/Water 1.0 1.0 0.5 1.0 2.0 1.0 1.0 1.0 0.3 0.5 0.5 2.0 1.0 1.0 0.5 1.0 1.0 1.0 T Electric/Grass 1.0 1.0 1.0 2.0 1.0 1.0 2.0 1.0 0.5 2.0 0.5 0.5 0.3 1.0 2.0 1.0 1.0 1.0 y Electric/Psychic 1.0 0.5 0.5 1.0 2.0 1.0 2.0 2.0 0.5 1.0 1.0 1.0 0.5 0.5 1.0 1.0 2.0 1.0 p Electric/Ice 1.0 2.0 0.5 1.0 2.0 2.0 1.0 1.0 1.0 2.0 1.0 1.0 0.5 1.0 0.5 1.0 1.0 1.0 e Electric/Dragon 1.0 1.0 0.5 1.0 2.0 1.0 1.0 1.0 0.5 0.5 0.5 0.5 0.3 1.0 2.0 2.0 1.0 2.0 Electric/Dark 1.0 2.0 0.5 1.0 2.0 1.0 2.0 0.5 0.5 1.0 1.0 1.0 0.5 0.0 1.0 1.0 0.5 2.0 Electric/Fairy 1.0 0.5 0.5 2.0 2.0 1.0 0.5 1.0 1.0 1.0 1.0 1.0 0.5 1.0 1.0 0.0 0.5 1.0 ``` The best dual type charts I've found is [here](http://pokemondb.net/type/dual), don't forget to list even the non-existent combinations, by clicking 'Show all types'. Types combine by multiplication, except for the same time (eg. electric/electric which is actually electric/-). White space in the output is only important between columns and rows (to remain legibility). This is code golf so shortest bytes wins. [Answer] ## JavaScript (ES6), 666 bytes ``` p=>(a=[18611524949,21853721688,27323097365,27406984278,23191686421,37066245461,26177987925,66127746385,37356070566,22827115926,22906831253,21627185429,23913388373,27196216913,18594420117,22906579204,18608379736,26936956281].map(n=>[...n.toString(4)].map(c=>(4>>c)/2)),t=`Normal,Fighting,Flying,Poison,Ground,Rock,Bug,Ghost,Steel,Fire,Water,Grass,Electric,Psychic,Ice,Dragon,Dark,Fairy`.split`,`,n=t.indexOf(p),w=` `.repeat(l=n<0?16:24),w+` `.repeat(28)+`Attacking Type `+w+t.map(s=>s[0]+s[1]).join` `+` `+t.map((s,i)=>(` Defending Type `[i]+` `+(n<0?s:n-i?p+`/`+s:p+`/--------`)+w).slice(0,l)+a[i].map((e,j)=>(i==n|n<0?e:e*a[n][j]).toFixed(1)).join` `).join` `) ``` Explanation: ``` a=[18611524949, 21853721688, 27323097365, 27406984278, 23191686421, 37066245461, 26177987925, 66127746385, 37356070566, 22827115926, 22906831253, 21627185429, 23913388373, 27196216913, 18594420117, 22906579204, 18608379736, 26936956281].map(n=>[...n.toString(4)].map(c=>(4>>c)/2)), ``` These are base 4 encoded numbers where each base 4 digit represents the effectiveness. The mapping is 0 - super effective, 1 - normally effective, 2 - not very effective, 3 - immune. This mapping is chosen because Normal is not super effective against any type and therefore each number will have 18 digits in base 4, but also allowing the effectiveness to be relatively easy to compute. `t` is just an array of types (split from a string to save bytes). `n` is the index of the passed-in type, this is the easiest way to detect whether a type has been passed in but also saves a byte when checking the current row. `l` is the indentation of the main array, and `w` a string of spaces of length `l`. The first line is therefore just `w` plus a further 28 spaces plus the phrase "Attacking Type". The second line is `w` plus the first two characters of each type, with each pair separated by two spaces. Each row of the array is then generated. The header column is calculated using the appropriate character of phrase "Defending type", three spaces, the relevant types, and enough spaces to pad to length `l`. The columns are then calculated and formatted to 1 decimal place and joined with a single space as required. There are probably further golfing opportunities but I stopped at 666 bytes because I have spent too much time on this already today. [Answer] # Python 2 - ~~2163~~, ~~1648~~, ~~1642~~, ~~1580~~, ~~1560~~, ~~1490~~, 1390 bytes ``` s=[[1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,1,2,1,1,.5,.5,1,1,1,1,1,1,2,1,1,.5,2], [1,.5,1,1,0,2,.5,1,1,1,1,.5,2,1,2,1,1,1], [1,.5,1,.5,2,1,.5,1,1,1,1,.5,1,2,1,1,1,.5], [1,1,1,.5,1,.5,1,1,1,1,2,2,0,1,2,1,1,1], [.5,2,.5,.5,2,1,1,1,2,.5,2,2,1,1,1,1,1,1], [1,.5,2,1,.5,2,1,1,1,2,1,.5,1,1,1,1,1,1], [0,0,1,.5,1,1,.5,2,1,1,1,1,1,1,1,1,2,1], [.5,2,.5,0,2,.5,.5,1,.5,2,1,.5,1,.5,.5,.5,1,.5], [1,1,1,1,2,2,.5,1,.5,.5,2,.5,1,1,.5,1,1,.5], [1,1,1,1,1,1,1,1,.5,.5,.5,2,2,1,.5,1,1,1], [1,1,2,2,.5,1,2,1,1,2,.5,.5,.5,1,2,1,1,1], [1,1,.5,1,2,1,1,1,.5,1,1,1,.5,1,1,1,1,1], [1,.5,1,1,1,1,2,2,1,1,1,1,1,.5,1,1,2,1], [1,2,1,1,1,2,1,1,2,2,1,1,1,1,.5,1,1,1], [1,1,1,1,1,1,1,1,1,.5,.5,.5,.5,1,2,2,1,2], [1,2,1,1,1,1,2,.5,1,1,1,1,1,0,1,1,.5,2], [1,.5,1,2,1,1,.5,1,2,1,1,1,1,1,1,0,.5,1]] e=["Normal ","Fighting","Flying ","Poison ","Ground ","Rock ","Bug ","Ghost ","Steel ","Fire ","Water ","Grass ","Electric","Psychic","Ice ","Dragon ","Dark ","Fairy "] x="\t" t="No Fi Fl Po Gr Ro Bu Gh St Fi Wa Gr El Py Ic Dr Da Fa" r=range for i in r(0,18): n="" for b in r(0,18):n+=str(float(s[i][b]))+" " print e[i],x,n c=s[input()] print x*6+"Attacking Types" print x*3+t for i in r(0,18): a=e[s.index(c)] n=a+"/"+e[i]+x if e[i]==a:n=a+"/--------"+x if c!=s[i]:z=[round(float(a*b),1)for a,b in zip(c,s[i])] else:z=c for b in r(0,18):n+=str(float(z[b]))+" " print n ``` [Try it here!](https://repl.it/EzQ6/8) **This program has 765 bytes from hard-coding the data of the effectiveness of each type down in `s`**. Example Output: The chart with single types (last line is where you type in the input): [![enter image description here](https://i.stack.imgur.com/J622d.png)](https://i.stack.imgur.com/J622d.png) The chart with dual types: [![enter image description here](https://i.stack.imgur.com/XixmS.png)](https://i.stack.imgur.com/XixmS.png) **Explanation** `s` holds the effectiveness stats in list per defending element (first is for the effectiveness against Normal, next against Fighting, etc.) ``` s=[[1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,1,2,1,1,.5,.5,1,1,1,1,1,1,2,1,1,.5,2], [1,.5,1,1,0,2,.5,1,1,1,1,.5,2,1,2,1,1,1], [1,.5,1,.5,2,1,.5,1,1,1,1,.5,1,2,1,1,1,.5], [1,1,1,.5,1,.5,1,1,1,1,2,2,0,1,2,1,1,1], [.5,2,.5,.5,2,1,1,1,2,.5,2,2,1,1,1,1,1,1], [1,.5,2,1,.5,2,1,1,1,2,1,.5,1,1,1,1,1,1], [0,0,1,.5,1,1,.5,2,1,1,1,1,1,1,1,1,2,1], [.5,2,.5,0,2,.5,.5,1,.5,2,1,.5,1,.5,.5,.5,1,.5], [1,1,1,1,2,2,.5,1,.5,.5,2,.5,1,1,.5,1,1,.5], [1,1,1,1,1,1,1,1,.5,.5,.5,2,2,1,.5,1,1,1], [1,1,2,2,.5,1,2,1,1,2,.5,.5,.5,1,2,1,1,1], [1,1,.5,1,2,1,1,1,.5,1,1,1,.5,1,1,1,1,1], [1,.5,1,1,1,1,2,2,1,1,1,1,1,.5,1,1,2,1], [1,2,1,1,1,2,1,1,2,2,1,1,1,1,.5,1,1,1], [1,1,1,1,1,1,1,1,1,.5,.5,.5,.5,1,2,2,1,2], [1,2,1,1,1,1,2,.5,1,1,1,1,1,0,1,1,.5,2], [1,.5,1,2,1,1,.5,1,2,1,1,1,1,1,1,0,.5,1]] ``` `e` holds the names of the types. There are spaces put in to maximize the usage of `\t` in later parts of the code. ``` e=["Normal ","Fighting","Flying ","Poison ","Ground ","Rock ","Bug ","Ghost ","Steel ","Fire ","Water ","Grass ","Electric","Psychic","Ice ","Dragon ","Dark ","Fairy "] ``` This part prints the attacking types (literally too!) ``` print "\t\t\t\t\tAttacking Types" print "\t\tNo Fi Fl Po Gr Ro Bu Gh St Fi Wa Gr El Ps Ic Dr Da Fa" ``` This prints out the defending type and its respective stats according to the pre-made table and uses `\t` for uniform spacing: ``` for i in range(0, 18): n="" for b in range(0, 18): n+=str(float(s[i][b]))+" " print e[i],"\t",n ``` Take input. The input is an integer from 0 to 17 since there are 18 lists (one for each element). `0` returns `s[0]` which is the list for Normal type, `1` returns `s[1]` which is the list for Fighting type, etc. Notice how in the screenshot, 12 is used since `s[12]` is the list for the Electric type: ``` c = s[int(raw_input())] ``` Print out the attacking types (literally as well) again for second table: ``` print "\t\t\t\t\t\tAttacking Types" print "\t\t\tNo Fi Fl Po Gr Ro Bu Gh St Fi Wa Gr El Ps Ic Dr Da Fa" ``` This is where the second table starts to take place. To get the dual types' results, we must loop through every single list and prepare the string with the two types used: ``` for i in range(0, 18): n=e[s.index(c)] + "/"+e[i]+"\t" if e[i]==e[s.index(c)]: n=e[s.index(c)]+"/--------"+"\t" ``` Then we actually do the math. If the input matches the type the list belongs to, do nothing really. Else, start multiplying: ``` if c!=s[i]: z=[round(float(a*b), 1) for a,b in zip(c, s[i])] else: z=c ``` Finish the table by printing out the string, `n`, for each dual type possibilty: ``` for b in range(0, 18): n+=str(float(z[b]))+" " print n ``` **Thanks @DJMcMayhem for saving 515 bytes!** **Thanks @Rod for saving 20 bytes!** **Thanks @Qwerp-Derp for saving 70 bytes!** ]
[Question] [ # Introduction There are often times that we have challenges which require communication of some sort (such as in team KOTH), where density of information may be more important than density of code. There are a number of compression techniques that can allow us to convey more information in less space, but for simple data flags, sometimes flipping bits themselves can be a great way to achieve desired data density. # Challenge Write a program or function in the language of your choice that can take an integer to be manipulated (must handle at least 32 bit), a start bit position (integer), a number of bits to manipulate (integer), and a manipulation mode (integer), and returns the original integer manipulated in the way specified below. In addition, write a second program or function that serves as a bit reader, taking in an integer, a start bit position (integer), and a number of bits to read (integer), and returns an integer consisting of just that group of bits shifted down, and every other bit as `0`. Some further details and rules are as follows: * The first argument will be an integer, signed or unsigned. * The second argument will be the bit position to start from (counting from least significant bit, zero-indexed). * The third argument will be the number of bits to be read/manipulated, moving up in bit significance from the start bit. If not given as an argument, the value should default to `1`. * The fourth argument (manipulator only) will be the manipulation mode: + When passed a `0` or null value, the behavior will be to flip (xor) all of the specified bits (default if no value given). + When passed a positive value, the behavior will be to set all of the specified bits to `1`. + When passed a negative value, the behavior will be to set all of the specified bits to `0`. * The return value of the manipulator function should be the initial integer with the above bit manipulations applied. * The return value of the reader function should be the start bit shifted to the least significant bit, and every bit beyond the length of bits set to `0`. * Assume that only valid input will be used. Don't worry about error handling. The winner will be determined by the shortest sum of the length of both programs/functions. They will be selected in at least 7 days, or if/when there have been enough submissions. In the event of a tie, the answer that came earlier wins. # Examples Here's a few examples of input and output that your code should be able to handle. I've golfed both functions in JavaScript that I can release if people want to test their results, but otherwise I'll probably wait a few days before I post it up. ### Manipulator ``` F(0, 2) => 4 (0 => 100) F(4, 2) => 0 (100 => 0) F(0, 2, 4) => 60 (0 => 111100) F(170, 2, 4, 0) => 150 (10101010 => 10010110) F(170, 2, 4, 1) => 190 (10101010 => 10111110) F(170, 2, 4, -1) => 130 (10101010 => 10000010) F(0, 31) => (+/-)2147483648 (0 => 10000000000000000000000000000000) ``` ### Reader ``` F(0, 2) => 0 (0 => 0) F(4, 2) => 1 (100 => 1) F(60, 2, 4) => 15 (111100 => 1111) F(170, 2, 4) => 10 (10101010 => 1010) F((+/-)2147483648, 0, 32) => (+/-)2147483648 (10000000000000000000000000000000 => 10000000000000000000000000000000) ``` [Answer] # JavaScript (ES6), 75 bytes *Saved 4 bytes thanks to @Mwr247* **Manipulator: (47 bytes)** ``` (a,b,c=1,d=0,z=(1<<c)-1<<b)=>d?d<0?a&~z:a|z:a^z ``` **Reader: (28 bytes)** ``` (a,b,c=1)=>a>>b&(1<<c-1)*2-1 ``` ## How it works **Manipulator** The first thing we need to do is figure out the number that has `c` bits set, starting at the `b`th bit. Possibly the best way to do this is `z=(1<<c)-1<<b`, which works like so: ``` b c 1<<c -1 <<b z 2 1 10 01 0100 4 2 2 100 011 01100 12 2 3 1000 0111 011100 28 1 4 10000 01111 011110 30 ``` Now we take into account `d`. For case `0`, we flip the bits with `a^z`; for case `1`, we set the bits to 1 with `a|z`; for case `-1`, we set the bits to 0 with `a&~z`. [Answer] # Python 2, 89 bytes Done in a method similar to ETH. Python lambdas aren't as short as in JS. Also, default parameter values can't depend on other parameters. **Manipulator, 63 bytes** ``` def f(a,b,c=1,d=0): z=2**c-1<<b;return[a^z,a|z,a&~z][cmp(d,0)] ``` **Reader, 26 bytes** ``` lambda a,b,c=1:a>>b&2**c-1 ``` [**Try it online**](http://ideone.com/hSvIYn) ]
[Question] [ Note: all array references in this post are zero-indexed. When playing the piano, two notes on the same key must be pressed with two different fingers. You *could* use the same finger, but it doesn't sound as good. At least, according to my piano teacher. I can't hear any difference. The challenge is to take a space-separated list of 3 integers: Starting finger, ending finger, and length of repeating notes, and output the optimal sequence of finger numbers to match the input. All piano jargon aside, output a string of numbers based on the input, where each number is `+1`/`-1` the one before it, all numbers are between 1 and 5, the sequence is `args[2]` digits long, starting with `args[0]` and ending with `args[1]`, and is formatted as below. The input can be command line arguments, values on the stack (for ><> users), STDIN, or any other conventional method. Output will be a list of numbers, with these being valid outputs. * `[1, 2, 3, 4, 5]` * `(1 2 3 4 5)` * `"12345"` * `12345`\* * `1-2-3-4-5`\*\* * `1 2 3 4 5`\*\* For each asterisk on the style above, compute the following to calculate your score: ``` final-score = code.length * (1.00 - (asterisks * 0.05)); ``` You can assume the first two params will be between 1 and 5, but if it handles at least 0-9, multiply your code by 95%. If the last digit is less than 2, or the input parameters are impossible, error **however you like**, or just exit. --- Finger numbers on the piano work like this, however this is not integral to the challenge. ``` 1 | Thumb 2 | Index finger 3 | Middle finger 4 | Ring finger 5 | Pinky (finger) ``` --- Sample input and output: Input: `1 2 2` Output: `1 2` Input: `1 4 8` Output: `1 2 3 2 3 2 3 4` Input: `2 3 10` Output: `2 3 2 3 2 3 2 3 2 3` Input: `5 2 1` Output: `Error` Input: `1 2 5` Output: `Error` Input: `5 1 5` Output: `5 4 3 2 1` Input: `1 1 1` Output: `1` --- These do *not* have to be handled correctly. Input: `1 6 6` Output: `1 2 3 4 5 6` Input: `0 9 8` Output: `Error` [Answer] # Pyth, 36 \* .95 \* .90 = 30.78 ``` jd+JrFAQ<*vz,H.xeJhH?&%K-vzlJ2>K0K.q ``` [Test suite](https://pyth.herokuapp.com/?code=jd%2BJrFAQ%3C*vz%2CH.xeJhH%3F%26%25K-vzlJ2%3EK0K.q&test_suite=1&test_suite_input=2%0A1%2C2%0A8%0A1%2C4%0A10%0A2%2C3%0A1%0A5%2C2%0A5%0A1%2C2%0A5%0A5%2C1%0A1%0A1%2C1&debug=0&input_size=2) Outputs space separated integers and can handle arbitrary integer inputs, so it qualifies for both bonuses. Input format: ``` length starting finger, ending finger ``` The output is constructed by starting with a range from the starting finger to the ending finger, then repeating the end of that range and the ending finger the necessary number of times. Exiting is done via explicit checks for the length of the second step being odd and positive, or else `.q`, Pyth's exit function is called. [Answer] # Javascript (ES6), ~~148~~ 146 \* 0.95 \* (1.00 - (0 \* 0.05)) = 138.7 ``` (a,b,c)=>c<(m=Math.abs(a-b))?0:eval('l=a,q=Array(m+1).fill().map(_=>a<b?l++:l--);while(q.length-c)q=q.concat(q.slice(-2,-1));q[q.length-1]-b?0:q') ``` Note: My way of indicating an "error" is returning 0 (chosen to save bytes of course). The normal return type is a Javascript array. I'm not sure if that's an acceptable output format. If it isn't, I guess I'll have to add `JSON.stringify(...)`. I think I get the 5% reduction since this can technically handle any range of numbers you want. **Edit:** Saved 2 bytes thanks to @Ypnypn [Answer] # CJam, 50 bytes \* 0.9 \* 0.95 = 42.75 ``` q~_$_@<\~),>@1$,-_0<1$2%e|{];}{2/1$-2>*+S*\{W%}&}? ``` [Try it online](http://cjam.aditsu.net/#code=q~_%24_%40%3C%5C~)%2C%3E%401%24%2C-_0%3C1%242%25e%7C%7B%5D%3B%7D%7B2%2F1%24-2%3E*%2BS*%5C%7BW%25%7D%26%7D%3F&input=8%20%5B1%204%5D) Code length is 50 bytes. If I understand them correctly, it qualifies for all bonuses. It outputs space separated values (-10%), and works for values outside the range 1 to 5 (-5%). The input format is: ``` length [startValue endValue] ``` The sequence produced is first the range from start value to end value, then the last 2 values repeated until the specified length is reached. Explanation: ``` q~ Get and interpret input. _$ Copy and sort start/end value pair. _@< Copy and compare sorted and unsorted start/end values. Will use the sorted one, but reverse the entire sequence at the end if the start value was larger than the end value. \~ Get sorted start/end value to top, and unwrap it. ), Generate range [0 .. endValue]. > Slice off values to get range [startValue .. endValue]. @ Get specified number of values to top. 1$, Get list length of values we already generated. - Subtract. This gives the number of values that still need to be generated. _0< Check if number is less than 0. 1$2% Check if number is odd. e| Logical or. If one of the two conditions is true, there is no solution. { If branch for no solution. ]; Clear stack. Will produce empty output for no solution. } End of branch for no solution. { If branch for producing solution. 2/ Divide remaining count by 2. Will repeat last two values this many times. 1$ Copy already produced values to top. -2> Slice off last 2 values. * Repeat them. + Add to already produced sequence. S* Join with spaces. \ Swap condition for start value greater than end value to top. {W%}& Reverse sequence if needed. }? End of if for solution vs. no solution. ``` ]
[Question] [ **This question already has answers here**: [Make a slow error quine maker!](/questions/51007/make-a-slow-error-quine-maker) (13 answers) Closed 5 years ago. We've been twice challenged to make 'error quines' (see [Make an error quine!](https://codegolf.stackexchange.com/questions/36260/make-an-error-quine) and [Make a slow error quine maker!](https://codegolf.stackexchange.com/questions/51007/make-a-slow-error-quine-maker)), so why don't we try the opposite? ## Instructions 1. Write a "program" that, when run, produces an error. 2. Copy the error message into a new program, and run it. 3. Repeat Step 2 until the program runs without producing an error. ## Rules * All of your programs must be run in the same language. * None of your programs can be shorter than 1 byte long. * The error(s) should be printed to STDERR. ## Winning criteria Your score is the **number of programs run** minus **the length in bytes of your initial program**. Highest score wins. --- An example in monochrome TI-83+/84+ BASIC: *Initial program:* `{"` This creates a list with a string inside it, throwing an `ERR:DATA TYPE`. *Program 2:* `ERR:DATA TYPE` The space causes the interpreter to throw an `ERR:SYNTAX`. *Program 3:* `ERR:SYNTAX` The letters are treated as variable multiplication, and the colon as a newline. This runs successfully. This chain's score is **3** (number of programs) **minus 2** (length in bytes of `{"`, the initial program), totaling `1`. [Answer] # [Pip 0.15.05.29](https://github.com/dloscutoff/pip/commit/063bf12392a59c64c129cfb973204b69a10f0b32), over 10100,000 (Subtracting the 51 bytes of source code is negligible for such a large number.) This is a version of [my answer to Make a slow error quine maker](https://codegolf.stackexchange.com/a/51017/16766). Requires the `-w` flag for warning output. ``` i:5**6**7d:"i:1d: Ssi?dRo--iRsRPdx"Ssi?dRo--iRsRPdx ``` The exact number of steps depends only on the value assigned to `i`, so it could be arbitrarily large (until the Python interpreter runs out of memory). Also, it would take longer than the age of the universe to complete the above sequence. **Explanation:** Example here uses an `i`-value of `5` for purposes of explanation. ``` i:5d:"i:1d: Ssi?dRo--iRsRPdx"Ssi?dRo--iRsRPdx ``` After setting `i`, store a string in `d` and then attempt to execute the `S`wap statement. Swap expects two variables (more accurately, lvalues). `s` is fine, but the second expression is `i?dRo--iRsRPdx`. If `i` is true (nonzero, for our purposes), the ternary evaluates to `dRo--iRsRPd`, which uses `d` from earlier to form a near-quine--only with `i` decremented. This expression is not an lvalue, so Pip complains: ``` Attempting to swap non-lvalue i:4d:"i:1d: Ssi?dRo--iRsRPdx"Ssi?dRo--iRsRPdx ``` ... which then starts the whole thing over again. (`Attempting to swap non-lvalue` is a bunch of no-ops: `At` calculates the ASCII value of `t = 10`, `n-l` subtracts newline minus each value of an empty list, and all the lowercase letters are just variables.) The process continues in like fashion all the way down to: ``` Attempting to swap non-lvalue i:0d:"i:1d: Ssi?dRo--iRsRPdx"Ssi?dRo--iRsRPdx ``` When this is run, `i` is now false. The ternary expression evaluates to the else branch `x`--which is an lvalue. Thus, swap simply swaps the values of `s` and `x`. The program then exits with no output. (The only thing that's changed from the previous answer is using `x`, which is a predefined variable, instead of `a`, which is undefined if there were no command-line arguments and thus triggers a different error when `i` gets down to zero.) [Answer] # Bash, 9223372036854775809 - 75 = 9223372036854775734 This is a previous broken version of [my answer to Make a slow error quine maker](https://codegolf.stackexchange.com/a/51012/25180), which in fact works as what this question have specified. ``` a='"2>/dev/null;(((i=$((i-1)))>0))&&$(declare -p a)&&$a" #' i=2**63 eval $a ``` It should be run with `bash < file.sh`, or use the same file name for each program, to get rid of the different file names in the error messages. The first few errors are (with `LANG=C`): ``` bash: line 3: 2>/dev/null;(((i=9223372036854775807)>0))&&declare -- a="\"2>/dev/null;(((i=\$((i-1)))>0))&&\$(declare -p a)&&\$a\" #"&&"2>/dev/null;(((i=$((i-1)))>0))&&$(declare -p a)&&$a" #: No such file or directory ``` ``` bash: line 1: 2>/dev/null;(((i=9223372036854775806)>0))&&declare -- a="\"2>/dev/null;(((i=\$((i-1)))>0))&&\$(declare -p a)&&\$a\" #"&&"2>/dev/null;(((i=$((i-1)))>0))&&$(declare -p a)&&$a" #: No such file or directory ``` ``` bash: line 1: 2>/dev/null;(((i=9223372036854775805)>0))&&declare -- a="\"2>/dev/null;(((i=\$((i-1)))>0))&&\$(declare -p a)&&\$a\" #"&&"2>/dev/null;(((i=$((i-1)))>0))&&$(declare -p a)&&$a" #: No such file or directory ``` [Answer] # SmileBASIC, 2 - 6 = -4 Code must be run in the console so a line number isn't printed in the error message. Initial program: ``` WHILE. ``` Program 2: ``` WHILE without WEND ``` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 9 years ago. [Improve this question](/posts/5409/edit) This challenge is to calculate how to measure 4 liters of water with just two unevenly sized buckets, one of 3 liters and another of 5 liters, in minimum number of steps. To extend and generalize this, write a program to evaluate the minimum number of steps to measure “X” liters of water, with “Y” buckets each having a separate denomination. Assumptions: 1. Each bucket used for measuring water should be unique in denomination and the number of buckets will be <= 3 2. The target amount to be reached has to finally reside in a single bucket (at the end of the measuring activity). 3. The bucket capacities and target amount will be <= 99 4. If there are multiple ways to measure the same amount, only one single way, having the minimum number of steps is required. 5. Ties will be broken by the smallest program. **Examples:** > > 2,3,5,4 > > Implies that there are 2 buckets of capacity 3 and 5 each and the target amount desired is 4. > > > 3,4,6,9,7 > > Implies that there are 3 buckets of capacity 4, 6 and 9 each and the target amount desired is 7. > > > **Answers:** > > 2,3,5,4 > > Fill 5 > > Move 5 to 3 > > Empty 3 > > Move 5 to 3 > > Fill 5 > > Move 5 to 3 > > > 3,4,6,9,7 > > Fill 4 > > Move 4 to 6 > > Fill 9 > > Move 9 to 6 > > > [Answer] ## Python, 363 chars Golfed it, not sure if it is golf or not. The map `P` maps a reachable state to the instructions used to get to that state. Keeps enumerating reachable states until it finds one with the target amount of water in it. ``` I=input() B=I[1:-1] R=range(I[0]) P={(0,)*I[0]:""} while P: Q={} for s in P: if I[-1]in s:print P[s];P=Q={};break for i in R: Q[s[:i]+(0,)+s[i+1:]]=P[s]+"Empty %d "%B[i];Q[s[:i]+(B[i],)+s[i+1:]]=P[s]+"Fill %d "%B[i] for d in R:m=min(s[i],B[d]-s[d]);Q[tuple(s[j]-[0,m][j==i]+[0,m][j==d]for j in R)]=P[s]+"Move %d to\ %d "%(B[i],B[d]) Q.update(P);P=Q ``` [Answer] ### Ruby The following code gives a ruby implementation of the task described above. The specification is as follows: **Input:** A list of integers on STDIN, where the first one is the number *n* of buckets available, followed by *n* distinct bucket denominations, followed by the target amount of water. **Output:** A list of operations needed to reach the target amount in any bucket or a corresponding message if that is not possible. **Task:** Start with *n* empty buckets each of different integer denomination. In each step you can do one of the following: * *Fill X*: fills the bucket with denomination *X* with water such that it contains exactly *X* water * *Empty Y*: empty the bucket with denomination *Y*, i.e. no water inside after this operation * *Move A to B*: take any water in bucket with denomination *A* and put it into bucket with denomination *B* up to the point where bucket *B* is full. (Example: Bucket 5 has 4 liters in it and bucket 3 has 2. Then Move 5 to 3 will transfer 1 liter leaving bucket 5 with 3 liters while bucket 3 is full afterwards.) The algorithm used is quite straightforward. On a list of bucket configurations (i.e. a list of buckets with their corresponding fill levels) perform all possible operations. Each one will lead to a new configuration. Keep those which you didn't had already in previous steps (i.e. those that are really novel). This way we get a list of configurations reachable be 1 step, 2 steps, ... . Whenever we reach a configuration where one bucket is filled with exactly the target amount we are done. Since we have a constructive algorithm, i.e. we know in each step which operation we perform, we can simultaneously build the list of operations in textual representation for any bucket configuration. Example: 3 buckets with denominations 7, 9 and 11. Target amount of water is 1. **Input:** ``` 3, 7, 9, 11, 1 ``` **Output:** ``` Solution found with 7 steps: Fill 7 Move 7 to 11 Fill 7 Move 7 to 11 Move 7 to 9 Fill 7 Move 7 to 9 ``` **Code:** ``` # get input as list of integers input = gets.split(/,/).map{|s| s.to_i} count = input.shift start = (1..count).map{[input.shift, 0]} target = input.shift # a bucket configuration is a list of buckets, each represented as # array [denomination, fill level], i.e. initial configurations # is e.g. [[3, 0], [5, 0]] for empty buckets of size 3 and 5 configurations = {start => ""} step = 0 solution = nil current = configurations.keys while current.size > 0 do # debug output (each configuration rechable within step) puts "- #{step} ------------------------------------------" current.each{|k| puts "#{k.to_s} #{configurations[k]}"} puts # test current configurations if target amount is included solution = current.select{|k| k.any?{|b| b[1] == target}}[0] break if solution step += 1 new_configurations = {} # for all configurations for all buckets current.each{|k| k.size.times{|i| # do a fill operation on this bucket kn = Marshal.load(Marshal.dump(k)) # make deep copy # increase fill level to bucket denomination kn[i][1] = kn[i][0] new_configurations[kn] = "#{configurations[k]} Fill #{kn[i][0]}" # do an empty operation on this bucket kn = Marshal.load(Marshal.dump(k)) # make deep copy # set fill level to zero kn[i][1] = 0 new_configurations[kn] = "#{configurations[k]} Empty #{kn[i][0]}" # do a move operation on any other bucket k.size.times{|j| kn = Marshal.load(Marshal.dump(k)) # make deep copy # amount movable is current amount or space left in other bucket h = [kn[i][1], kn[j][0]-kn[j][1]].min kn[i][1] -= h kn[j][1] += h new_configurations[kn] = "#{configurations[k]} Move #{kn[i][0]} to #{kn[j][0]}" } } } # remove any configuration already reachable with less steps new_configurations.keep_if{|conf| !configurations[conf]} # merge new configurations configurations.merge!(new_configurations) current = new_configurations.keys end if solution puts "Solution found with #{step} steps:" puts configurations[solution] else puts "Impossible to reach target" end ``` ]
[Question] [ Consider some arbitrary polynomial with integer coefficients, $$a\_n x^n + a\_{n-1}x^{n-1} + \cdots + a\_1x + a\_0 = 0$$ We'll assume that \$a\_n \ne 0\$ and \$a\_0 \ne 0\$. The solutions to this polynomial are [algebraic numbers](https://en.wikipedia.org/wiki/Algebraic_number). For example, take the polynomial $$x^4 - 10x^2 + 1 = 0$$ We have that \$x = \sqrt 2 + \sqrt 3\$ is a solution to this polynomial, and so \$\sqrt 2 + \sqrt 3\$ must be an algebraic number. However, most real numbers, such as \$\pi\$ or \$e\$ are not algebraic. Given any algebraic number \$x\$, it is possible to construct a polynomial \$p\$ such that \$p(x) = 0\$. However, this is not unique. For example, $$x^6 - 99x^2 + 10 = 0$$ also has a root \$x = \sqrt 2 + \sqrt 3\$. We define the *minimal polynomial* of an algebraic number \$x\$ to the be polynomial \$p\$ such that \$p(x) = 0\$ and the order of \$p\$ is minimal. With our example \$x = \sqrt 2 + \sqrt 3\$, there exists no such quadratic or cubic polynomial with \$x\$ as a root, as \$x^4 - 10x^2 + 1\$ is the minimal polynomial of \$x = \sqrt 2 + \sqrt 3\$. If the order of \$p\$ is \$n\$, we say that \$x\$ is an "algebraic number of order \$n\$". For example, \$\sqrt 2 + \sqrt 3\$ is of order \$4\$. --- For the purposes of this challenge, we'll only consider **real** algebraic numbers termed "[closed form algebraic numbers](https://en.wikipedia.org/wiki/Closed-form_expression#Closed-form_number)". These are algebraic numbers that can be expressed as some combination of addition, subtraction, multiplication, division and \$n\$th order radicals (for integer \$n\$). For example, this includes \$\varphi = \frac {1 + \sqrt 5} 2\$, and \$7\sqrt[3] 2 - \sqrt[10] 3\$, but not e.g. [roots of \$x^5 - x - 1 = 0\$](https://tio.run/##y00syUjNTSzJTE78/z@gKDOvJDo4P6csNboizlRBV6ECiA0VbG0VDGJj//8HAA), or \$\sqrt[\sqrt 2] 3\$ (\$n\$th roots are only allowed with integer \$n\$). You are to take a real algebraic number as input, with the guarantee that it can be constructed with our 5 operations, and output the order of the input. The order will always be a positive integer. You may take input in any form that exactly represents any closed form algebraic numbers. This could be as an exact symbolic number (if your language has these), a string unambiguously representing the composition of the 5 operations (e.g. `7*root(2,3)-root(3,10)`, `7*(2r3)-(3r10)` or even `sub(times(7, root(2, 3)), root(3, 10))`), and so on. **You may not input as floating point values**. Note that the format you choose should be unambiguous, so is likely to use e.g. parentheses for grouping/precedence. For example, `7*2r3-3r10` does not meet this requirement, as it can be interpreted in a number of ways, depending on the precedence of each command. In short, you may choose any input format - not limited to strings - so long as that input format can represent any closed form algebraic number exactly and unambiguously. Additionally, be mindful of [this](https://codegolf.meta.stackexchange.com/a/14110/66833) standard loophole about encoding extra information into the input format - this is fairly loose, but try not to use formats that contain more information than just the 5 standard operations. If your answer uses a builtin that takes an algebraic number as input and returns either the order of the number, or the minimal polynomial, please edit it into [this list of trivial answers](https://codegolf.stackexchange.com/a/240112/66833). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. --- ## Test cases I'm expressing the inputs here using Mathematica's `Surd[n, k]` function to represent \$\sqrt[k] n\$, along with `+`, `-`, `*` and `/` to represent \$+\$, \$-\$, \$\times\$ and \$\div\$ respectively. ``` input -> output 5/6 -> 1 Surd[4, 2] -> 1 Surd[2, 2] * Surd[2, 2] -> 1 (Surd[5, 2] + 1)*(Surd[5, 2] - 1) -> 1 (Surd[5, 2] + 1)/2 -> 2 (Surd[5, 2] + 1)*(Surd[5, 2] + 1) -> 2 Surd[2, 2] + Surd[3, 2] -> 4 Surd[(Surd[5, 2] + 1)/2, 2] -> 4 Surd[5, 5] - 2 -> 5 Surd[5, 5] + Surd[3, 7] - 2*Surd[2, 2] -> 70 ``` The polynomials for these cases are given by [Try it online!](https://tio.run/##y00syUjNTSzJTE78/z@gKDOvJNo3My8zNzEnID@nMi8/NzMxJ1pZR6EiNlZNQd9BoZpLAQhM9c10wIzg0qKUaBMdBaNYJL4RiK@ghcSBSGqABUzBstoKhppayAK6QAHsyvSNiNCuDdeO5ARtCMcYzX1YLEBVAJQyBbnICEMMYaI5WIEWwjau2v//AQ "Wolfram Language (Mathematica) – Try It Online") [Answer] # Trivial builtin answers ## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes ``` #~MinimalPolynomial~x~Exponent~x& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/Bfuc43My8zNzEnID@nMi8/NzMxp66izrWiID8vNa@krkLtf0BRZl5JdFq0qb5ZbCwXjBdcWpQSbaqjYBSrb6SgrWCob4QuaQSSBEqBOcYgDhbtprEKugpG2CUQWs3BqrQQxsbG/gcA "Wolfram Language (Mathematica) – Try It Online") Unsurprisingly, `MinimalPolynomial` returns the minimal polynomial of its input, and `Exponent` gets the highest exponent in this polynomial. We use a bit of infix notation (`a~f~b` is `f[a,b]`) to save a couple of bytes, and so this translates as ``` #~MinimalPolynomial~x~Exponent~x& Exponent[#~MinimalPolynomial~x,x]& Exponent[MinimalPolynomial[#,x],x]& ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 175 bytes ``` Cases[FactorList@g@#,{y_,_}/;Simplify[y/.x->#/.s->D]==0:>y~Exponent~x]& g@n_=x-n g[p_~s@o_~q_]:=Resultant[g@q,g@p/.x-><|Plus->z-x,Times->z/x,Divide->z*x,Surd->z^q|>@o,x]/.z->x ``` [Try it online!](https://tio.run/##pVBNS8NAEL33VywEepDdxEarUM2yYPXkoVhvyxpCm8SFfO9GNv3IX4/5MNqUIIK3eTNv3nszoSPf3dCRfONUHrCqB0e4gj45Gxlnz1xI4hMN7gsb2kfjbs3DJOBeQQtDVwhrhi4QXjLLulzgonxUSRy5kSwVm058EtmWQtHEp4ldChLbZWqzhfXiijyQTiSpT1Lok6RVuj@sgrzW2iEFX3noNqWh4JJ/8K1b1xcKrvNsW1dv6QGTGCpm6DuEVbXKeK2lAYSBRzXGwBQYBOwF7XYZnUNwwyAQtBFg9BoCs4WtDaN93@z7J3DIaxL@8Ocdf9ZyRkdo1gn0QX5RMP/n9GU0nJ0ddPV9UIf/nMsc9503Fw5no5wT/9vBQ5F5/m12rD4B "Wolfram Language (Mathematica) – Try It Online") Takes an expression as input, where: * \$p+q\$ is represented by `s[Plus][p, q]`. * \$p\ q\$ is represented by `s[Times][p, q]`. * \$p/q\$ is represented by `s[Divide][p, q]`. * \$\sqrt[n]p\$ is represented by `s[Surd][p, n]`. * There is no special form for \$p-q\$, because \$p-q\$ is just \$p+(-1)\times q\$. For example, \$\sqrt[5]5+\sqrt[7]3-2\sqrt[2]2\$ is represented by `s[Plus][s[Plus][s[Surd][5, 5], s[Surd][3, 7]], s[Times][-2, s[Surd][2, 2]]]`. The idea is constructing a (usually not minimal) polynomial using [resultants](https://en.wikipedia.org/wiki/Resultant), factoring it, and choosing the correct factor. The last step requires checking whether a expression is equal to zero. I'm not sure if `Simplify` is powerful enough for all possible inputs, but at least it works for all the testcases. [Answer] # Trivial builtin answers ## [Python](https://www.python.org) + [`sympy`](https://www.sympy.org/en/index.html), 78 bytes ``` from sympy import* x=symbols('x') f=lambda y:degree(minimal_polynomial(y,x),x) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bZDBasMwDIbveQpBD7XalLKUbGPQ0-477AWGu9iNwbY8R9niZ-mll-1h-gZ9myUhK4MWdJD4P30gHX5C4pr88fjdsl49nl90JAdNciGBcYEiL7Ju2887so2Yd3PM9NZKt6skpKdK7aNSwhlvnLRvgWzy5Iy0IuUd9jVZTzN4ltYC1wp069_ZkIcvwzVURmsVlWf4lLZVTRai8Sy0eJUD1JvKHO4R8RI0H5FFiesClnCB7nIorqACe2TsNv-zSMSDtURYDVu3giWMwyaHh5FaTEKcLvr71y8) ]
[Question] [ Your task, at the moment that you choose to accept it, is to write a program that, when given a string and a PCRE-regex, calculates the minimum Levenshtein distance to another string that matches the regex (fully). All strings, as well as the regexes, should be in the Latin-1 character set. This is `code-golf`, so the shortest program wins. The Levenshtein distance (or edit distance) between two strings is the *closeness* of two strings, measured in operations needed to go from one string to another. One operation is one insertion, one deletion, or one substitution. # Examples `a, ab+ -> 1` because `ab` matches `ab+` and `levenshtein(a, ab) = 1` `aaa, .* -> 0` because `aaa` matches `aaaa, ab+a -> 2` because `aba` matches and `levenshtein(aaaa, aba) = 2` `abcde, a.?b?.?a -> 2` because `abca` matches and `levenshtein(abcde, abca) = 2` [Answer] # [PHP](https://php.net/), 114 bytes ``` for($t=a,$r=INF;$c++<1e8;$t++)preg_match("/^$argv[2]$/",$t)&&($r>$l=levenshtein($argv[1],$t))?$r=$l+$c=0:0;echo$r; ``` [Try it online!](https://tio.run/##JcxNCsIwEEDhu5ShJKT0x5WYxuwEN15Aqkzj2AixDWPo9WPFzVt9vOhj7m3c@lxYQDJYAZvz5aTBKdV3tNeQlJKRabq/MTkviuYGyNN63Q3QFBUkWZYC@AjBBFpp/vhEr1n8TTf8gLTbFIICZ9pDq8n5BVjnnHF0D8pY29HWFr8 "PHP – Try It Online") This works with a smaller alphabet and some caveats, but passes the test cases: * current version only works with lowercase letters (will try to improve this point) * works by bruteforcing all strings using php strings increment * uses a counter: the result is output if no smaller levenshtein value is found for a matching string after 100000000 (1e8) string increments (this limit was arbitrarily set to have a result in TIO, as 1e9 times out - can be set up to 9e9 with same byte count) * following these points, current version will not be able to work if the input string is more than 100000000 (or up to 9e9) string increments from "a" [Answer] # [Crystal](https://crystal-lang.org), 129 bytes ``` require"levenshtein" def f(s,r,d=1/0,a="`")while(a=a.succ).size-s.size<d d=[d,Levenshtein.distance s,a].min if a[r]?==a end d end ``` [Try it online!](https://tio.run/##VY3BCsIwEETv@YoQL63GVO@G/IB/UApuky0N1FCzraI/H2PBipcdeDOzY@OTJhhSinibfUQx4B0D9RP6IJjDjncFySidPlYHCVpcRPno/YAFaFA0W1sq8i/c0yInx5yunTz/vijn80KwyElCo64@cN9xqGNjtAaGIVc@N43zRHlNgJC8gnZXlWxFsEC1/WffJGS8WXlrHS6GMq1RJpvpDQ "Crystal – Try It Online") This fulfills the task if support for lowercase alphabet is enough. Theoretically, this shouldn't have an upper limit on length - the bruteforcing loop stops when the current test string `a` becomes so long that its Levenshtein distance from input `s` can never be smaller than the currently found minimal distance `d`. However, in practice, even the last test case is too big for TIO. ]
[Question] [ **Step one** In a new google sheet insert an image into cell A1 with Insert > Image > Image In Cell **Step two** Create a formula to return TRUE (if the cell contains an image) and FALSE (if the image is missing) **Rules** Only vanilla formulas are allowed. The shortest code in bytes wins. [Answer] # 26 The shortest I've found, which I believe currently works, is: ``` =TYPE(A1)>64>ISFORMULA(A1) ``` [Answer] Try this... The way it is checking is if there is an image no data(Text) could be found so....: ``` =IF(ISTEXT(IFERROR(IMPORTDATA(A1),FALSE)),IMAGE(A1),"There is no Image there") ``` A1 = is the Image URL (https://....jpg) [Answer] ## 13 bytes ``` =TYPE(A1)=128 ``` The other answer is looking for other values. You asked for just a test true/false if an image in the cell. <https://support.google.com/docs/answer/3267375?hl=en-GB&sjid=11934302938886193323-NA> ]
[Question] [ # The task Given an ascii string, output a program in my esolang MAWP that outputs the inputted string when run. # Useful functions in MAWP ``` Numbers from 0-9: Pushes the number to stack M Takes the top two numbers off stack and pushes the sum to stack A Takes the top two numbers off stack and pushes the difference to stack (xyA = y-x) W Takes the top two numbers off stack and pushes the multiplied result to stack P Takes the top two numbers off stack and pushes the floored divided result to stack (xyP = yx) ; Takes top number off stack and prints it as an ascii char ``` # Test cases Input: `Hello, World!` Possible output: `89W;689MWA;269WW;269WW;1278WWA;159WA;48W;699WM;1278WWA;67W89WM;269WW;455WW;148WM;` Input: `codegolf` Possible output: `929MW;278WWA;455WW;1689MWA;1849MWA;1278WWA;269WW;689MW;` # Rules 1. There can be multiple solutions for each symbol, but the length must be minimal: for example, `04M5W5W;` is unacceptable while `45W5W;` is fine. 2. The stack starts with a 1 one it. 3. You may leave something on the stack 4. Your output may not print out other characters other than the string, and all of the character s must be given in the og order. 5. This is code-golf, so lowest byte score wins! # ASCII table for reference [![ascii table](https://i.stack.imgur.com/3xWoT.gif)](https://i.stack.imgur.com/3xWoT.gif) [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~276 266~~ 263 bytes *Saved 3 bytes thanks to @KevinCruijssen* ``` i=>[v=[],O='',[...2**29+'4'].map(F=x=>F[v[x]=+x]=x)].map(s=_=>v.map(x=>v.map(y=>[x+y,x*y,y-x].map((z,o)=>(!F[z]&&V.push(z))|(S=~~s[x]-~s[y])<s[z]|S==s[z]&F[x]<2?F[s[z]=S,z]=F[x]+F[y]+'MWA'[o]:0)),V=[])&&v.push(...V))&Buffer(i).map(n=>O+=F[n]+';')||O.replace(1,'') ``` [Try it online!](https://tio.run/##XVBNT4NAEL37K2wP7E5ZNkq8qB2MHogX0wMJPWyIIRQqZmUJWLIQ0r@OQ0kvHubzvXmZme@0S9usKetfrzKHfCpwKjFQHapE7JAxoaSU/mbjP7rsgSXyJ615iBaDUHXKJuiSWVj6LX5i0F1Se016ErNuL@ymF71nFyIfhAEM@CpUQ@I4saxP7RcfAEYe4fnckrBHvk9g2xJjjBDn6IQEbP2XUM0VRoLc3HJDorrsY//KlEme7gBETPuD43SLMp0QAzhvp6LIG17CZYkKg51L8xWNPjMYx51s8lqnWc7vBWMwZaZqjc6lNkde8PV7rrURt3vT6MNqDXDzD8/ofUejC4KmPw "JavaScript (Node.js) – Try It Online") ### MAWP interpreter Here is a simple MAWP interpreter I wrote to check the results. ``` function MAWP(code) { let stack = [ 1 ], out = ""; function assertStkSz(n) { if(stack.length < n) throw "stack error"; } [...code].forEach(c => { switch(c) { case 'M': assertStkSz(2); stack.push(stack.pop() + stack.pop()); break; case 'A': assertStkSz(2); stack.push(stack.pop() - stack.pop()); break; case 'W': assertStkSz(2); stack.push(stack.pop() * stack.pop()); break; case 'P': assertStkSz(2); stack.push(stack.pop() / stack.pop() | 0); break; case ';': assertStkSz(1); out += String.fromCharCode(stack.pop()); break; default : stack.push(+c); break; } }) return out; } ``` [Try it online!](https://tio.run/##jZLLbsIwEEX3fMUoG5JS3CbikeBSCaEuI1Vi4QVi4RqHpKR25DhFaptvT52HELRVYTPR3Llz7kjOK32nOVNJpodCbnlVRYVgOpECwgV5tpnRHPjsAaRcQ64p28Mc1uDC5hZkoU1jWbhn5sc9mudc6ZXerz5sYXYhiexmEaVc7HQMD2BkHSt5AKslcqWksjCUNWiNEKpjNyiS6omy2GYwf2xuAMgPia4Vp@sBGM059MP@7CzYc3B7LcqKPO7yM5nZDgzgpDO2F8XpHp/RFtfThpdp5HrazWXa8/W0u1MafMH930T8g@gaW/20gzmstErEDkVKvi1jqpbmWex/LtzyiBaphtnpRQN2bitNLR1TFNeFEnUU7pUVkyKXKUep3NnNr2f5AcETPwjJAnuTgJCuut7UJ0Zzx4GpI9@YgoCER30yJX7dt@7ReFzvGFuILcfp/Y4JPBOBu@XO3sW6/qj9dtMW2QxrWPUN "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~151~~ 150 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žQÇεÑÅs¸˜2∍DT‹N59‹iPi©'WªëP®P-®„WMJëài`9-Dgi…9MWJ©NUë®NX-'M««]JR•4ñ4₄¬[Ý•5äŽ6þbT„WM‡5äøJ•XDŒ•27вǝεDg46N44‹è‹i©NUëW≠i®NX-ì'A«]"19M29MW"16ǝIÇƵPαè';ý1õ.; ``` Not too happy with the byte-count, but it could be worse.. [Try it online](https://tio.run/##yy9OTMpM/f//6L7Aw@3nth6eeLi1@NCO03OMHnX0uoQ8atjpZ2oJJDMDMg@tVA8/tOrw6oBD6wJ0D6171DAv3Nfr8OrDCzITLHVd0jMfNSyz9A33OrTSL/Tw6kPr/CJ01X0PrT60OtYr6FHDIpPDG00eNbUcWhN9eC6Qa3p4ydG9Zof3JYWAzXnUsBAocniHF1AqwuXoJCBlZH5h0/G557a6pJuY@ZmYAN1weAXIIRDzwx91LsgEW3J4jboj0BIlQ0tfI6D9SoZmx@d6Hm4/tjXg3MbDK9StD@81PLxVz/r/f4/UnJx8HYXw/KKcFEUA) or [verify all ASCII characters](https://tio.run/##yy9OTMpM/f//6L7Aw@3nth6eeLi1@NCO03OMHnX0uoQ8atjpZ2oJJDMDMg@tVA8/tOrw6oBD6wJ0D6171DAv3Nfr8OrDCzITLHVd0jMfNSyz9A33OrTSL/Tw6kPr/CJ01X0PrT60OtYr6FHDIpPDG00eNbUcWhN9eC6Qa3p4ydG9Zof3JYWAzXnUsBAocniHF1AqwuXoJCBlZH5h0/G557a6pJuY@ZmYAN1weAXIIRDzwx91LsgEW3J4jboj0BIlQ0tfI6D9SoZmx@cGgbxTVmlfebg9QUlB4/B@TYVHbZMUlOxd/A6v0PkPAA). **Explanation:** I first tried to do the mapping of each printable ASCII character (integers in the range \$[32,126]\$) manually. With this, I've used the following strategy: 1) I've first determined all integers that can be formed by multiplying two single-digit integers: ``` (32) → 48W # (35) → 57W $ (36) → 66W ( (40) → 58W * (42) → 67W - (45) → 59W 0 (48) → 68W 1 (49) → 77W 6 (54) → 69W 8 (56) → 78W ? (63) → 79W @ (64) → 88W H (72) → 89W Q (81) → 99W ``` We can add or subtract a single digit from each of these numbers to form all integers in the range \$[32,90]\$: ``` ! (33) → [48W1M] / 257WA " (34) → 48W2M / [157WA] % (37) → [66W1M] / 358WA & (38) → 66W2M / 258WA ' (39) → 66W3M / [158WA] ) (41) → 58W1M / 167WA + (43) → [67W1M] / 259WA , (44) → 67W2M / [159WA] . (46) → [59W1M] / 268WA / (47) → 59W2M / [168WA] 2 (50) → [77W1M] / 469WA 3 (51) → 77W2M / 369WA 4 (52) → 77W3M / 269WA 5 (53) → 77W4M / [169WA] 7 (55) → 69W1M / 178WA 9 (57) → [78W1M] / 679WA : (58) → 78W2M / 579WA ; (59) → 78W3M / 479WA < (60) → 78W4M / 379WA = (61) → 78W5M / 279WA > (62) → 78W6M / [179WA] A (65) → [88W1M] / 789WA B (66) → 88W2M / 689WA C (67) → 88W3M / 589WA D (68) → 88W4M / 489WA E (69) → 88W5M / 389WA F (70) → 88W6M / 289WA G (71) → 88W7M / [189WA] I (73) → [89W1M] / 799WA J (74) → 89W2M / 799WA K (75) → 89W3M / 699WA L (76) → 89W4M / 599WA M (77) → 89W5M / 499WA N (78) → 89W6M / 399WA O (79) → 89W7M / 299WA P (80) → 89W8M / [199WA] R (82) → 99W1M S (83) → 99W2M T (84) → 99W3M U (85) → 99W4M V (86) → 99W5M W (87) → 99W6M X (88) → 99W7M Y (89) → 99W8M Z (90) → 99W9M ``` 3) When there are two options, we want to prioritize the ones containing a digit `1` (since those is already initially on the stack, and we could potentially remove later on). When one of the two numbers contains a `1` I've put it in square-blocks in the list above. If both or neither contain a `1` it's irrelevant which one we choose. 4) Now that everything below 91 is covered, we are left with the integers in the range \$[91,126]\$. I first determined all integers which could be formed by one single-digit integer multiplied by a two-digit integer in the range \$[10,18]\$, since 18 being 9+9 is the highest we could create: ``` [ (91) → 794MW ` (96) → 697MW b (98) → 795MW c (99) → 992MW f (102) → 698MW h (104) → 894MW i (105) → 796MW l (108) → 699MW p (112) → 797MW u (117) → 994MW w (119) → 798MW ~ (126) → 799MW ``` 5) And there are also some additional integers which can be formed by using three single digits outside of the ones above, which are edge cases in my program: ``` d (100) → 455WW x (120) → 869MW y (121) → 358WW } (125) → 555WW ``` 6) After that, we can use a similar strategy as we did in steps 2 and 3: ``` \ (92) → [794MW1M] / 4268WWA ] (93) → 794MW2M / 3268WWA ^ (94) → 794MW3M / 2268WWA _ (95) → 794MW4M / [1268WWA] a (97) → 697MW1M / 1795MWA e (101) → 455WW1M / 1698MWA g (103) → 698MW1M / 1894MWA j (106) → [796MW1M] / 2699MWA k (107) → 796MW2M / [1699MWA] m (109) → [699MW1M] / 3797MWA n (110) → 699MW2M / 2797MWA * o (111) → 699MW3M / [1797MWA] q (113) → [797MW1M] / 4994MWA r (114) → 797MW2M / 3994MWA s (115) → 797MW3M / 2994MWA t (116) → 797MW4M / [1994MWA] v (118) → 994MW1M / 1798MWA z (122) → [358WW1M] / 3555WWA { (123) → 358WW2M / 2555WWA | (124) → 358WW3M / [1555WWA] ``` The one with `*` behind it is the only edge case after all these steps, since `19M29MW` can be used that contains a 1, so is potentially shorter than both `699MW2M` and `2797MWA`. --- As for the actual code to implement these steps and encode the input: ``` žQ # Push all printable ASCII characters Ç # Convert it to an integer list in the range [32,127] ε # Map each integer to: Ñ # Get the divisors of the current integer Ås # Get the middle (if it's a square) or middle two integers ¸˜2∍ # If it's a square, duplicate that integer # (so we only have pairs of integers now) D # Duplicate the pair T‹ # Check for both whether they're a single digit (<10): y91‹i # If the integer we're mapping over is below 91: Pi # If both values in the pair are a single digit: © # Store the pair in variable `®` (without popping) 'Wª '# And append a "W" to the list ë # Else: P # Pop and take the product of the duplicated pair ®P # Take the product of pair `®` as well - # Subtract them from one another ® # Push pair `®` „WM # Push string "WM" J # Join the pair together, and then all three together ë # Else (the integer we're mapping over is above 90): ài # If either of the two integers is a single digit: ` # Push both separated to the stack 9- # Subtract 9 from the larger 2-digit integer Dgi # If it's now a single digit: …9MW # Push string "9MW" J # And join all three together © # Store this in variable `®` (without popping) NU # And store the map-index in variable `X` ë # Else: ® # Push the string from variable `®` N # Push the current map-index X- # Subtract the saved map-index of `X` 'M '# Push an "M" «« # Join the three together ] # Close all if-statements and map J # Join each inner list together to a single string ``` We now have the following list: ``` ["48W","148WM","248WM","57W","66W","166WM","266WM","366WM","58W","158WM","67W","167WM","267WM","59W","159WM","259WM","68W","77W","177WM","277WM","377WM","477WM","69W","169WM","78W","178WM","278WM","378WM","478WM","578WM","678WM","79W","88W","188WM","288WM","388WM","488WM","588WM","688WM","788WM","89W","189WM","289WM","389WM","489WM","589WM","689WM","789WM","889WM","99W","199WM","299WM","399WM","499WM","599WM","699WM","799WM","899WM","999WM","749MW","749MW1M","749MW2M","749MW3M","749MW4M","839MW","839MW1M","759MW","929MW","1010","929MW2M","689MW","689MW1M","849MW","769MW","769MW1M","769MW2M","939MW","939MW1M","1011","939MW3M","859MW","859MW1M","859MW2M","859MW3M","859MW4M","949MW","949MW1M","789MW","1012","1111","789MW3M","789MW4M","789MW5M","789MW6M","959MW"] ``` As you can see, it contains some errors like `"1010","1011","1012","1111"` for the edge cases [100,110,120,121] respectively as discussed earlier, which could be `"455WW","869MW","358WW","555WW"` instead; `"789MW6M"` for 125, which could be `"555WW"` instead; and `"789MW3M"` for 122, which could be `"358WW1M"` instead. So we fix those edge cases manually (except for `"1011"` since we already fix that edge case at the very end anyway): ``` R # Reverse the list •4ñ4₄¬[Ý• # Push compressed integer 1358555358869455 5ä # Split it into 5 equal-size parts: [1358,555,358,869,455] Ž6þ # Push compressed integer 1783 b # Convert it to binary: 11011110111 T„WM‡ # Transliterate "10" to "WM": "WWMWWWWMWWW" 5ä # Also split it into 5 equal-size parts: # ["WWM","WW","WW","MW","WW"] ø # Pair the two lists together J # And join each inner pair together: # ["1358WWM","555WW","358WW","869MW","455WW"] •XDŒ• # Push compressed integer 2149280 27в # Convert it to base-27 as list: [4,1,5,6,26] ǝ # Insert the strings at those indices in the reversed list ``` Then we'll change every case with `...2M` or higher to `x...A`: ``` ε # Map each string to: Dg # Get the length (without popping by duplicating first) N44‹ # Check if the map-index is below 44 # (1 if truthy; 0 if falsey) 46 è # Use it to index into 46 (6 if truthy; 4 if falsey) ‹i # If the length is smaller than that: © # Store the current string in variable `®` NU # And the map-index in variable `X` ë # Else: W # Get the smallest digit (without popping) ≠i # If it's NOT 1: ® # Push the string of variable `®` NX- # Push the map-index and subtract `X` ì # Prepend this digit in front of the string 'A« '# And append an "A" ] # Close the if-statements and map ``` We now have the following (still reversed!) list: ``` ["959MW","555WW","1555WWA","2555WWA","1358WWM","358WW","869MW","789MW","949MW1M","949MW","1949MWA","2949MWA","3949MWA","859MW1M","859MW","1859MWA","1011","939MW1M","939MW","1939MWA","769MW1M","769MW","849MW","689MW1M","689MW","1689MWA","455WW","929MW","759MW","839MW1M","839MW","1839MWA","2839MWA","3839MWA","749MW1M","749MW","999WM","899WM","799WM","699WM","599WM","499WM","399WM","299WM","199WM","99W","199WA","299WA","399WA","499WA","599WA","699WA","799WA","189WM","89W","189WA","289WA","389WA","489WA","589WA","689WA","188WM","88W","79W","179WA","279WA","379WA","479WA","579WA","178WM","78W","169WM","69W","169WA","269WA","369WA","177WM","77W","68W","168WA","159WM","59W","159WA","167WM","67W","158WM","58W","158WA","258WA","166WM","66W","57W","157WA","148WM","48W"] ``` Fix the final test case as discussed earlier: ``` "19M29MW" # Push string "19M29MW" 16ǝ # And insert it at index 16 ``` And then convert the input using this finished (still reversed) list: ``` I # Push the input-string Ç # Convert each character to its codepoint integer ƵP # Push compressed integer 126 α # Take its absolute difference with each codepoint integer è # Index those into the list we created ';ý '# Join them together with a ";" delimiter 1õ.; # And remove the very first "1" # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•4ñ4₄¬[Ý•` is `1358555358869455`; `Ž6þ` is `1783`; `•XDŒ•` is `2149280`; `•XDŒ•27в` is `[4,1,5,6,26]`; and `ƵP` is `126`. ]
[Question] [ # Introduction Little Jimmy is going trick or treating. He lives in an odd neighborhood: some houses give out candy, and some give out toothbrushes. Now, Jimmy does not want to get too many toothbrushes. He wants candy! You must help him get some. # Challenge Each street in Jimmy's neighborhood has a number. Each house on the street will give out either candy or toothbrushes. However, Jimmy's parents know he gets very hyper if he eats too much candy. To prevent this, they are only letting him go down one street in the neighborhood. Given a list of streets, you must output the street where Jimmy will get the most candy and the fewest toothbrushes. This means that, as said in the comments, even if one street gives out 500 candies and 1 toothbrush, it is worse than one that gives out 1 candy and no toothbrush. * The list of streets will be 2D. It will never be empty. Each street will be a list of truthy or falsy values. It might be empty. Falsy values represent a house that gives out toothbrushes, truthy ones represent houses that give out candy. * Your program must output the index of the street with the most truthy values and the fewest falsy ones, or the street that gives the most candy and the fewest toothbrushes. If all the streets have the same amount of candy and toothbrushes, you may output -1. It does not matter if the index is 0-based or 1-based. It can be stored as a string. The integer can be in any base. # Example I/O *Note: In these lists, `True` represents a truthy value and `False` a falsy one. `0` can be replaced with `1` if your language uses 1-indexing.* * `Streets: [[True,True,True],[False,False],[False]]` `Output: 0` * `Streets: [[False,True,True],[False,False],[True],[False]]` `Output: 2` * `Streets: [[],[False,False,True],[False]]` `Output: 0` * `Streets: [[True,True,False],[False,True,True],[True,False,True]]` `Output: -1` * `Streets: [[True,True,True,True,True,False],[True]]` `Output: 1` * `Streets: [[False, True],[False,True,True]]` `Output:1` # Rules This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! [Answer] # [Python 2](https://docs.python.org/2/), 58 bytes ``` lambda l:l.index(max(l,key=lambda s:(-s.count(0),sum(s)))) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHHKkcvMy8ltUIjN7FCI0cnO7XSFipVbKWhW6yXnF@aV6JhoKlTXJqrUawJBP8LijLzShTSNKKjQ4pKU3XgRKxOtFtiTnGqDpiE8WJjNbkQOiAKcGtBFkTViapUB7dChKNQ3IFiKUIaIoLFjQoQpQrIXKhgrOZ/AA "Python 2 – Try It Online") [Answer] # [R](https://www.r-project.org/), 52 bytes ``` function(l)order(lengths(l)-(m=sapply(l,sum)),-m)[1] ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jRzO/KCW1SCMnNS@9JKMYyNfVyLUtTiwoyKnUyNEpLs3V1NTRzdWMNoz9n6aRk1lcopGsEaIDhJo6CskabjpuQNpNU5MLLumGJhmCJg@TAitCkQEZ6waVhpkRAlaIZj6SGk3N/wA "R – Try It Online") Minimizes the number of toothbrushes, then maximizes the pieces of candy, since this is apparently what OP is asking. If we want to first maximize the amount of candy, then minimize the number of toothbrushes (seems more plausible…) it becomes # [R](https://www.r-project.org/), 51 bytes ``` function(l)order(m<--sapply(l,sum),lengths(l)+m)[1] ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jRzO/KCW1SCPXRle3OLGgIKdSI0enuDRXUycnNS@9JKMYqEI7VzPaMPZ/mkZOZnGJRrJGiA4QauooJGu46bgBaTdNTS64pBuaZAiaPEwKrAhFBmSsG1QaZkYIWCGa@UhGaGr@BwA "R – Try It Online") Computing the number of `TRUE`s in a list of vectors is easy with `sapply(l,sum)`. Computing the number of `FALSE`s is much less golfy, so I use `lengths` minus the number of `TRUE`s instead. [Answer] # Mathematica, 180 172 bytes ``` ToExpression[StringReplace[a,{"["->"{","]"->"}"," "->"=","True"->"-10^-9","False"->"1"}]];(If[Length[#]==1,#[[1]],-1]&@@Flatten[Position[#,Min[#]]]&/@{Total/@Streets})[[1]] ``` We assume the input is already stored as text in the variable *a*. If the reformatting code is neglected (input is already stored in the variable Streets) the length becomes 82 bytes. My solution maps the toothbrushes (1) + candy(-1e-9) onto the real line and finds the minimum. It will only work for streets that have a maximum of 1,000,000,000 toothbrush houses as is (but it can be easily modified to suit the max number of toothbrush houses.) Expanded code: ``` a := "Streets: [[True,True,False],[False,True,True],[True,False,True]]"; ToExpression[ StringReplace[ a, {"[" -> "{", "]" -> "}", " " -> "=", "True" -> "-10^-9", "False" -> "1"}]] b = (Total /@ Streets) c = Flatten[Position[b, Min[b]]] If[Length[c]==1,c[[1]],-1] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` ċþØ.N1¦ZM-¹L’$? ``` [Try it online!](https://tio.run/##y0rNyan8//9I9@F9h2fo@RkeWhblq3top8@jhpkq9v@PTnq4c4b1o4Y5Crp2Co8a5lofbuc63P6oaU3k///RXNHRhjpAGKsTbaBjACJjY3WAggYogoYICYiYDpIISD9YJ1SLIVgaLgWBEFOgRisYwpXHcsUCAA "Jelly – Try It Online") A monadic link taking a list of lists of Jelly booleans (0s and 1s). Returns the 1-indexed maximum list using the specified criteria, or -1 if there is more than one that is equal. The last 6 bytes are spent on converting multiple values into -1; if this could be dropped the answer would be 9 bytes. [Answer] # [J](http://jsoftware.com/), 19 bytes ``` 0{[:/:(-.,&(+/)-)@> ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DaqjrfStNHT1dNQ0tPU1dTUd7P5rcqUmZ@QDFdkqpCkYgqC1gYKBtQFE2AgsbAAWVgCJg2lkLerqIPUYwiCTgKZANBqCTfBz0lNIzKtUyMxLSa1QyCxWyM9WyEgtSoVoM0Q4AKpZwRBZBmIFSOo/AA "J – Try It Online") * `0 {` first element of... * `[: /:` the grade up of... (indices with smallest item first) * `(-.,&(+/)-)` the list of pairs `,` created by summing each of `&(+/)`: 1 minus an input item `-.` and the negative of an input item `-` * `@>` of each unboxed input item This turns each input item into a pair: ``` <number of false, -1 * number of true> ``` When we sort this list J will automatically sort first by element 1, then by element 2. Lower are numbers come first. ]
[Question] [ This is the robbers' thread, the cops' thread is [here](https://codegolf.stackexchange.com/questions/172219/polycops-and-robbers-cops-thread) --- A polyglot is a program, that without modification, can run in multiple languages. --- # Robbers' Challenge First, find a vulnerable cop's answer, then try to find languages that the submission works in, if you found any that weren't listed by the cop, then you just cracked their answer. Post an answer linking to the original answer and what languages you found it working on (it must do the same thing on each language). You can then leave a comment on their answer linking back to your answer on this thread. --- # Winning Most upvoted answer that actually does crack the cops' code wins [Answer] # [Foo](https://esolangs.org/wiki/Foo), [PotatoLatte's answer](https://codegolf.stackexchange.com/a/172577/76162) ``` puts "Hello World!" ``` [Try it online!](https://tio.run/##S8vP//@/oLSkWEHJIzUnJ18hPL8oJ0VR6f9/AA "Foo – Try It Online") Ah, the bane of cops and robbers, Foo. [Answer] # [Befunge-93](https://github.com/catseye/Befunge-93), [Shieru Asakotu's answer](https://codegolf.stackexchange.com/a/172234/76162) ``` '<?php '//'; #@ SPELL,WITH,ME, ,H,E,L,L,O, ,W,O,R,L,D,"'Hello, World!'" $a = "'Hello, World!'"; if ([]) console.log($a); //This should be an easy one to solve else { for ($i = 1; $i < strlen($a) - 1; $i++) echo($a[$i]); } // ?>' ``` [Try it online!](https://tio.run/##ZY1Ba8JAFITv@yumNrAJrl16Xq09NBAh0mKFHMRD1BcTWPZJVgWR/vb0FY/lwbzhY5jZUXMJRxoGPZ2f2hO0tdrh@R3fX3lZmmqxLswyNzCFyU0p9ym@El2J/zAjXZD3bFBx7w9PeqSSGjP8w051DdLNNlPYc4js6cXzMU3qzMHaddtFxJYv/oAdoQ6gOt7AgXBmSPpKinwk3BUa7pEmnYy8OsifIp57T@GvC5MHHI9lB7RvWegm6baZUz/KWszf9DD8Ag "Befunge-93 – Try It Online") Prints `'Hello, World!'`, quotes included. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), [Julia 0.4](http://julialang.org/), [R](https://www.r-project.org/), etc., [Cortex's answer](https://codegolf.stackexchange.com/a/179022/92069) ``` #| print("Hello, World!")# w|#(write-line "Hello, World!") ``` [Try Perl online!](https://tio.run/##K0gtyjH7/1@5hqugKDOvREPJIzUnJ19HITy/KCdFUUlTWaG8RlmjvCizJFU3JzMvVQFdwf//AA "Perl 6 – Try It Online") [Try R online!](https://tio.run/##K/r/X7mGq6AoM69EQ8kjNScnX0chPL8oJ0VRSVNZobxGWaO8KLMkVTcnMy9VAV3B//8A "R – Try It Online") [Try Julia 0.4 online!](https://tio.run/##yyrNyUz8/1@5hqugKDOvREPJIzUnJ19HITy/KCdFUUlTWaG8RlmjvCizJFU3JzMvVQFdwf//AA "Julia 0.4 – Try It Online") ]
[Question] [ Given positive integer `n` and `e`, knowing that `e<n` and that `n` is the product of two different odd primes(but the primes are not directly given to you), find such a positive integer `d` smaller than `n` that, for each integer `m`, (me)d ≡ m (mod n). Your program should handle `n` up to 24096 in 1TB space, but not necessary reasonable time. You can assume such a `d` exist. Sample Input: `n=53*61=3233, e=17` Sample output: `d=413` Note that your program will not be given the prime factor of `n`. Shortest code in bytes win. [Answer] # [Python 3](https://docs.python.org/3/), 77 bytes ``` def f(n,e):r=range(n);all(any(m-pow(m,e*d,n)for m in r)or print(d)for d in r) ``` [Try it online!](https://tio.run/##JcjBCoAgDADQX9lxCzvUDkHRxwhqCTplCNHXW9Tt8erdziLcu/MBAorxtOquVg6PQptNCa3cmMdaLszGD84IhaKQIQoovaoapaH71v3bA/LMbGBaqD8 "Python 3 – Try It Online") Direct translation of the requirement. `any(...)` becomes false when the smallest correct `d` is found, and `print(d)` returns `None`, making `all(...)` stop running. # 76 bytes, if unlimited memory is allowed ``` def f(n,e):r=range(n);all(any(m**(e*d)%n-m for m in r)or print(d)for d in r) ``` [Try it online!](https://tio.run/##JchBCoAgEADAr@wl2BU7lIeg6DGCWoKusnjx9VZ0G6b2dhc2YzgfICBrT7ucYvnyyHTYlNByx6wUeuVo4jlDKAIZIoPQqyqRGzr61v07AprVGA3LRuMB "Python 3 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 65 bytes ``` n,e=input() p=s=1 while n%~p:p+=1 while s%e:s-=p*n/~p+p print s/e ``` [Try it online!](https://tio.run/##PcdNCoAgEAbQvadwE/RjhLoIhLlNAwkxfaQRbby6tYg2Dx7uvO7iahXDFAVnbjsFSmTVtcaNtTQFAcP/1HBII6GXqWCAwhEl6zRxXej1O/arnQ33i5Gueue90XZ@AA "Python 2 – Try It Online") Finds a prime factor `p` of `n` to obtain the order `φ(n)=(p-1)(n/p-1)`. Then, solves the modular equation `d * e % φ(n) == 1` by counting up values `s` of the form `s = 1 + c * φ(n)` until a multiple of `e`is obtained. Since all expressions are arithmetical without exponents, only log-space is used. The code actually uses `p` to stand for one below the prime to save bytes on initialization. --- # [Python 2](https://docs.python.org/2/), 78 bytes ``` lambda n,e:pow(e,F(F(n))-1,F(n)) F=lambda n:sum(k/n*k%n==1for k in range(n*n)) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFPJ9WqIL9cI1XHTcNNI09TU9dQB0xzudnClFgVl@ZqZOvnaWWr5tnaGqblFylkK2TmKRQl5qWnauRpAVX/LyjKzCtRSNPQyswrKC3RAIoYGxkb6ygYmgMA "Python 2 – Try It Online") A direct expression using Dennis's [totient function implementation](https://codegolf.stackexchange.com/a/145316/20260). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes Thanks to *xnor* for -2 bytes! (pointing out `ÆṪ`, totient function) ``` ÆṪæi@ ``` [Try it online!](https://tio.run/##y0rNyan8//9w28Odqw4vy3T4//@/sZGx8X9DcwA "Jelly – Try It Online") Previously I used `Æf’Pæi@` at 7 bytes. ]
[Question] [ We are doing a PCG challenge at work, and I'm submitting answers in C#. This is a modification of the "M'Kay" challenge. My solution has been deemed correct by the requirements, I'm just trying to shrink it further if possible. > > A filler word is an apparently meaningless word, phrase, or sound that marks a pause or hesitation in speech. > > > Your task is to create a function that has a 30%-50% chance of adding a random filler word to a block of text after the punctuation marks , ; . ? and !; and when added is followed by the same punctuation. The same filler word must be used for each replacement within a single execution of the function. > > > If the filler word occurs after a sentence completing punctuation mark such as . ? or ! the filler word must have the first letter capitalized. > If the filler word occurs after a sentence pausing punctuation mark such as , or ; the filler word must be in lowercase. > > > Fillers: um, literally, you know, er, okay, right, ah, like > > > My submitted code: ``` string p(string i,int z=-1){string w="Um|Literally|You know|Er|Okay|Right|Ah|Like".Split('|')[i.Length %8],s="?,!;.",o="";foreach(var c in i){var x=s.IndexOf(c);o+=(z>0&&i[z]>'9'&&x>-1&&(1&z)<1?c+" "+(x%2>0?" "+w.ToLower():w):"")+c;z++;}return o;} ``` > > **Original input text:** We heard tales of Americans like Coast Guard Petty Officer Ashlee Leppert, who is here tonight in the gallery with Melania. Ashlee was aboard one of the first helicopters on the scene in Houston during Hurricane Harvey. Through 18 hours of wind and rain, Ashlee braved live power lines and deep water, to help save more than 40 lives. Thank you, Ashlee. > > > **With fillers added:** We heard tales of Americans like Coast Guard Petty Officer Ashlee Leppert, *okay*, who is here tonight in the gallery with Melania. Ashlee was aboard one of the first helicopters on the scene in Houston during Hurricane Harvey. *Okay*. Through 18 hours of wind and rain, Ashlee braved live power lines and deep water, *okay*, to help save more than 40 lives. Thank you, Ashlee. > > > Clarification comments welcome, I don't know what else I need to include. [Answer] > > > ``` > string ... s="?,!;." ... var x=s.IndexOf(c); > > ``` > > `s` is used only once, so could be inlined. --- > > > ``` > var x=s.IndexOf(c); ... &&x>-1&& ... c+" "+(x%2>0?" "+w.ToLower():w):"")+c; > > ``` > > Change `"?,!;."` to `",;?!."` and the test `x%2>0` can be simplified to `x<2`. Where in the spec does it require double-space after sentence-terminating punctuation? IMO you could lose the `" "+` inside the parentheses. --- Given the IMO ridiculous interpretation which they're allowing of "*random*", I don't see why you do such complicated stuff with `z`. Just use the character index modulo 3. A direct change to ``` string p(string i){int n=i.Length,j,x;string w="Um|Literally|You know|Er|Okay|Right|Ah|Like".Split('|')[n%8],o="";for(j=0;j<n;j++){var c=i[j];x=",;.?!".IndexOf(c);o+=(x>-1&&j%3<1?c+" "+(x<2?" "+w.ToLower():w):"")+c;}return o;} ``` gives a further nice saving. An alternative using Linq also saves a lot by exploiting fat arrow syntax, and would be cheaper if they give you free `using` statements: ``` using System.Linq;string p(string s)=>string.Join("",s.Select((c,i)=>{var w="Um|Literally|You know|Er|Okay|Right|Ah|Like".Split('|')[s.Length%8];var x=",;.?!".IndexOf(c);return(x>=0&&i%3<1?c+" "+(x<2?" "+w.ToLower():w):"")+c;})); ``` ]
[Question] [ Given a list of production rules and start symbol of a proper finite context-free grammar (CFG) of printable characters, your program or function must output its formal language (the set of all sentences which can be constructed from it). ## Task A context-free grammar is formally defined as a 4-tuple of a few parts. Here, they are defined for you to solve this challenge. For the purposes of the challenge, a production rule is of the form `{begin, {end-1, end-2, end-3, ..., end-n}}` or equivalent. The `begin` part is always one printable character (`0x20` to `0x7E`), and the `end-i` are all strings of printable characters. Your program will receive as input a list of production rules and a start symbol. The start symbol is a single printable character. An iteration takes an input list of strings and is defined as follows: To each string `s` in the input list, look at the first character `c` in it which is found as the `begin` of a production rule. To each `end-i` on the right side of that rule, add to the list the string `s` but where the first instance of `c` is replaced by the string `end-i`. Then remove the original string `s` if and only if there is a character `c`. The program would repeat applying iterations, beginning with the start symbol, until an iteration does not affect the list of strings, at which point it outputs the list of strings (with repeats removed). This is equivalent to the following pseudo-code: ``` rules = input() start_symbol = input() define iteration(string_list,rules): for each string in string_list: c = first char in string which is the first element of a rule in rules // ^^ This is a Mathematica builtin, right? ^^ if(c exists): ends = the second element of that rule for each end in ends: // replace the first instance of c with end. string_list.append(string.replace(c,end)) string_list.remove(string) // make sure you don't remove the original string if // there does not exist a c return string_list current_string = start_symbol // Clearly this is inefficient to apply iteration twice // but hey, this is code golf. As long as it runs in less than 60 seconds on TIO! while(iteration(current_string)!=current_string): current_string = iteration(current_string) print remove_repeats(current_string) ``` Note that you do not need to follow this exact pseudo-code as long as your program yields correct output. ## Example Given the start symbol `S` and production rules: ``` {S:{aE,bE,c}} {E:{ab,aC}} {C:{a,b,c}} ``` We do: ``` {S} // start {aE,bE,c} // apply first rule to the first element {aab,aaC,bab,baC,c} // apply second rule to the first and second element {aab,aaa,aab,aac,bab,baa,bab,bac,c} // apply third rule to the second and fourth elements {aab,aaa,aac,bab,baa,bac,c} // remove repeats ``` ## Input restrictions This should only matter to people who care. The CFG ... * has no recursion. * has no cycles. * has no unreachable symbols. * has no unproductive symbols. The list of production rules ... * may have productions resulting in an empty string. * may be taken in any format, as long as it encodes **only** a begin character and a list of alternatives as `end-i` for each rule. * has no duplicate `begin` characters. * has no duplicate `end` characters within a production rule ## Test Cases ``` start symbol, {rule1, rule2, ...}, expected output S, {S: {aE,bE,c}, E: {ab,aC}, C: {a,b,c}}, {aab,aaa,aac,bab,baa,bac,c} S, {S: {a,B}, B: {g,k}}, {a,g,k} A, {A: {B,C,D}, B: {c,d}, C:{b,d}, D:{b,c}}, {c,b,d} ~, {~: {`,^,/}, /:{`^,``}, ^:{``,```}}, {`,``,```,````} +, {A: {1,2,3}, +:{A,B,C}}, {1,2,3,B,C} ``` ## Notes * The input will be taken in *any convenient format* as long as it gives no information other than the production rules and start symbol. * The output should be given such that the list of strings as output is clearly encoded and unique. * Please specify what format your list of production rules are taken in. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in **each language** wins. Do not be discouraged from posting by answers in golfing languages. [Answer] # JavaScript, 118 bytes ``` m=>g=c=>(i=0,c=[...new Set([].concat(...c.map(n=>[...n].find(x=>k=m[o=x])?k.map(t=>n.replace(o,t,i=1)):n)))],i?g(c):c) ``` ``` f= m=>g=c=>(i=0,c=[...new Set([].concat(...c.map(n=>[...n].find(x=>k=m[o=x])?k.map(t=>n.replace(o,t,i=1)):n)))],i?g(c):c) print = x => console.log(JSON.stringify(x)) print(f({S:['a','B'],B:['g','k']})(['S'])) print(f({S:['aE', 'bE', 'c'], E:['ab', 'aC'], C:['a', 'b', 'c']})(['S'])) print(f({A:['B','C','D'],B:['c','d'],C:['b','d'],D:['b','c']})(['A'])) print(f({'~':['`','^','/'],'/':['`^','``'],'^':['``','```']})(['~'])) print(f({A:['1','2','3'], '+':['A','B','C']})(['+'])) ``` [Answer] # [Python 2](https://docs.python.org/2/), 124 bytes ``` def f(s,r,i=0): while s[i:]: if s[i]in r:return list(set(s[:i]+l+s[i+1:]for v in r[s[i]]for l in f(v,r))) i+=1 return[s] ``` [Try it online!](https://tio.run/##hY/NboMwEITP5SlWudjIVlPSm6UcgOQJekREzg9O3CKIDE1VRcmr091FkXJBPeyKGc03rM@//altFsNwqBw42emg/fItNhH8nHxdQVd4U5roxTv6LH0DwYSq/w4N1L7rZVfhFMaXqlYYUIkpXRvgApQsCGFdk3byokMcx9imlkkEY0/RlcM5@KaXM5i9fra@kU6KD6Hhitvg3q6FFjtae3HTINaju0Njm7OTjw7FxtSNfvNPKyYzpjPWR9Rfk2TKZMrJDJM5zuqJ3qM@PG658hmjXD3k9FV37r5zj8XkBmfO8JxgS9paNjZsWDbsZKF6OjbB7ALnnXlFfMovpzdwwfAH) ]
[Question] [ **This question already has answers here**: [Full Width Text](/questions/75979/full-width-text) (146 answers) Closed 6 years ago. **Challenge** An ascii string is made 'dank' when exactly one space is inserted between any two consecutive letters and all capital letters are replaced with lowercase ones. In this challenge I would like you to write a program that takes a string (not necessarily 'dank') as input and outputs a 'dank' version of that string. **Specification** Your program should take as input an ascii string of arbitrary length and output another ascii string. A string is classed as *dank* when it contains only spaces and lowercase letters such that there is exactly one space between any two consecutive letters. To make a string *dank* you'll have to strip all non-alphabetical characters, replace capital letters with their lowercase counterparts, then insert spaces between all the characters. **Example** ``` "aesthetic" > "a e s t h e t i c" "How are you?" > "h o w a r e y o u" "drop // top" > "d r o p t o p" ``` **Winning criterion** Code golf so the shortest code in bytes wins. g o o d l u c k [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~6~~ 5 bytes -1 byte thanks to Erik ``` láSðý ``` Explanation: ``` l Convert to lowercase á Remove all non-alphabetic characters S Get characters as array ðý Join by spaces ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/5/DC4MMbDu/9/z@lKL9AQV9foSS/AAA "05AB1E – Try It Online") [Answer] # [Python 3.5](https://docs.python.org/3.5/), ~~46~~ ~~49~~ 47 bytes ``` print(*[i for i in input().lower()if'`'<i<'{']) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQys6UyEtv0ghUyEzD4gKSks0NPVy8stTizQ0M9PUE9RtMm3Uq9VjNf//T0wtLslILclMBgA "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒlfØaK ``` A monadic link taking and returning lists of characters (or a program that prints the result). **[Try it online!](https://tio.run/##y0rNyan8///opJy0wzMSvf///6/kkuiXraCgEB0LJHxTc1OLFZUA "Jelly – Try It Online")** ### How? ``` ŒlfØaK - Main link: list of characters, s Œl - convert to lowercase (vectorises) Øa - yield lowercase alphabet: "abcdefghijklmnopqrstuvwxyz" f - filter keep K - join with spaces - if running as a program implicit print ``` [Answer] # [Decimal](//git.io/Decimal), 92 bytes ``` 91D31030012090D415D56112032D41D625230012122D416D5291D5230012097D417D5291D52301212032D301291D ``` Whew, that was fun. Thanks for the challenge - it helped me develop Decimal into a fully working language. (While writing this, I realized a few flaws. Just bugs and such.) Ungolfed: ``` 91D 310 300 ; input to stack, duplicate 12090D ; push CHAR 'Z' to stack 415D ; compare <, pop values used, push result 5 ; if truthy 61 ; put result into memory 12032D ; push CHAR 32 to stack 41D ; math +, pop values used, push result 62 ; pop memory to stack 5 ; endif 2 ; pop 300 ; duplicate DSI 12122D ; push CHAR 'z' to stack 416D ; compare >, pop values used, push result 5 ; if truthy 291D ; pop, restart 5 ; endif 2 ; pop 300 ; duplicate DSI 12097D ; push CHAR 'a' to stack 417D ; compare <, pop values uesd, push result 5 ; if truthy 291D ; pop, restart 5 ; endif 2 ; pop 3012 ; print, pop 12032D3012 ; push CHAR ' ', print, pop 91D ``` [Try it online!](https://tio.run/##RYuxCoAwDER/RXeFJLUt3TP4B87SFhSqBf/dOaYiuN17d5dy3I@1iARkg2AAkCAAT2jZOlQwpMCOLL0lUmPHlvTxOQhenf9dm7VjS6pE5lxKHbqlXiX191nHuMYtPw) [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~16~~ 5 + 1 (`-S` flag) = 6 bytes *Thanks to obakaron for saving 10 bytes* ``` ;v fE ``` [Try it online!](https://tio.run/##y0osKPn/37pMIc31/38l9/z8FAWf0uRsRSUF3eD/AA "Japt – Try It Online") [Answer] # [Perl 6](http://perl6.org/), 18 bytes ``` {m:g/<:L>/.Str.lc} ``` `m:g/<:L>/` produces a list of all of the letters in the input string; `.Str` converts the list into a string with a space between each element; and `.lc` converts the string to lower case. [Answer] # Pyth, 6 bytes ``` jd@Gr0 ``` [Try it here!](http://pyth.herokuapp.com/?code=jd%40Gr0&input=%22Dank+memes%21%22&debug=0) [Answer] # [shortC](//git.io/shortC), 40 bytes ``` c;AO;~c;c=G)!isalpha(c)?:R"%c ",tolower(c ``` Conversions in this program: * `A` -> `int main(int argc, char **argv){` * `O` -> `for(` * `G` -> `getchar()` * `R` -> `printf(` * Auto-inserted closing `));}` [Try it online!](https://tio.run/##K87ILypJ/v8/2drR37ou2TrZ1l1TMbM4MacgI1EjWdPeKkhJNVlBSackPye/PLVIA6jUIzUnJ19HITy/KCdFEQA) [Answer] # PHP, 68 Bytes ``` <?=chunk_split(preg_replace("#[^a-z]#","",strtolower($argn)),1," "); ``` [Try it online!](https://tio.run/##JczBCoJAEIDhe0@xjB1W2JDOVl59BzMZtsmVxBlmV6SiZzeh43/4PwmynioJsnuwEvpgG0CKKVAaPDioeTGoZF48V1velcUUhUks0GLco/ZT/qkum3H2YZ6eXZRxSFaU@k5JRvRkIWtueHi32QaAi0kTj7yQ2v@eu6MDA3m5kg8M1wnK7/oD "PHP – Try It Online") ## PHP, 70 Bytes ``` <?=join(" ",str_split(preg_replace("#[^a-z]#","",strtolower($argn)))); ``` [Try it online!](https://tio.run/##JcxBCsIwEIXhvacIUxcRKj1A1W57h1rLEMemUjLDJFJUPHsN@nY/PD7xsh4a8bK5sRI6bztAislTmhyU0PJiUMk8@dHkvCqLqSqTWKDHuEUdw@7dnLJxvPMULBgoY9IhyjwlK0rjoCQzOrJQdBfcv/oiO79T4pkXUvtX8uqVnGc4B6g/6xc "PHP – Try It Online") or ``` <?=preg_replace(["#[^a-z]#","#.(?=.)#"],["","$0 "],strtolower($argn)); ``` [Try it online!](https://tio.run/##JcxBCsIwEIXhvacIUxcRKj1A1W57h1rLEMemUjLDJFJUPHsN@nY/PD7xsh4a8bK5sRI6bztAislTmhyU0PJiUMk8@dHkvCqLqSqTWKDHuEUdw@7dnLJxvPMULBgoY9IhyjwlK0rjoCQzOrJQdBfcv/oiO79T4pkXUvtX8uqVnGc4B6g/6xc "PHP – Try It Online") [Answer] # C, 65 bytes ``` c;f(){for(;~c;c=getchar())!isalpha(c)?:printf("%c ",tolower(c));} ``` How it works: * `c` declares an integer `c`, and sets it to 0 by default. * `for(;~c;` declares a loop that will only continue if performing a bitwise NOT on `c` is true. NOT will return false only if `c` is EOF (meaning there is no more input). * `c=getchar()` reads a character from input into `c`. * `!isalpha(c)?:` checks if `c` is in the alphabet. If so... * `printf("%c ",tolower(c));` prints the character in lowercase, then a space. [Try it online!](https://tio.run/##S9ZNT07@/z/ZOk1Dszotv0jDui7ZOtk2PbUkOSOxSENTUzGzODGnICNRI1nT3qqgKDOvJE1DSTVZQUmnJD8nvzy1CCihaV37PzcxMw9khAaI45Gak5OvoxCeX5SToggA) [Answer] # [Retina](https://github.com/m-ender/retina), 14 bytes ``` T`Llp`ll_ \B ``` [Try it online!](https://tio.run/##K0otycxL/P8/JMEnpyAhJyeeK8aJS@H//8TU4pIMoFwyl0d@uUJiUapCZX6pPVdKUX6Bgr6@Qkl@AQA "Retina – Try It Online") This is so simple I don't even need a header to run multiple testcases. All uppercase letters are lowercased, lowercase letters are also lowercased for consistency, and everything else is deleted. Then spaces are inserted between every pair of letters. [Answer] ## JavaScript (ES6), 53 bytes ``` s=>[...s.toLowerCase().replace(/[^a-z]/g,'')].join` ` ``` Sometimes the straightforward way is the shortest... Here are a few successively more fun versions using array comprehensions (only works in Firefox 30+): ``` s=>[for(x of s.toLowerCase())if('`'<x&x<'{')x].join` ` s=>[for(x of s)if(parseInt(x,36)>9)x.toLowerCase()].join` ` s=>[for(x of s)if((x=parseInt(x,36))>9)x.toString(36)].join` ` ``` If we can assume the input contains at least one letter, this will work for 42: ``` s=>s.toLowerCase().match(/[a-z]/g).join` ` ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~55~~ ~~50~~ ~~53~~ 50 bytes *-3 bytes thanks to ETHproductions.* ``` lambda s:' '.join(i for i in s.lower()if'`'<i<'{') ``` [Try it online!](https://tio.run/##TcyhDsIwEAZgz1P87lqzJUgygkFgeIMJCrtmB1uvaUuWhYcvKDL7iS@uZdSwr/7Y18nN98EhHwjUPFWCEXhNEEhAbiZdOBkrnm7USUcfsjUmCQXekONcRi7yILv740UXuMRY9X3a@pA0om1RNG757MILV545/@Yv "Python 2 – Try It Online") ]
[Question] [ ## Challenge Given the equation of a line and the coordinates of the vertices of a shape, output the coordinates of the shape when reflected across the given line. ## Further Information The line's equation will be given with a `y` and an `x` separated by an equals sign (there may not always be a `y` and an `x`). Some examples: ``` y=x y=5.0 y=2.4x x=6.6 y=2.0x+5.0 x=2.0y ``` The equation will always be supplied as a string. The line will *always* be linear. The equation will only contain `+`s or `-`s and any multiplication will be before an `x` or a `y`. The `*` is not used however, and the number will be placed directly before the variable. A `0.0` is never used in the equation because there is no need for it to be shown. The coordinates will be an array of length `n>2` of arrays of length `2`. Outputted coordinated must also be in a similar array. No numbers supplied will be greater than `(2^32)-1` or less than `-((2^32)-1)`. All supplied numbers will be floats, and the output is expected to be the same. The program may either be a full program or a function (a function may be easier for passing the coordinates). ## Example ``` Input: y=5.0 [(0.0,0.0),(0.0,4.0),(5.0,0.0),(5.0,4.0)] Output: [(0.0,10.0),(0.0,6.0),(5.0,10.0),(5.0,6.0)] Input: x=3.5y [(1.14,2.04),(4.16,5.86),(6.02,0.86),(4.2,2.44)] Output: [(2.05,-1.13),(6.63,-2.78),(5.57,2.45),(4.86,0.15)] ``` ## Winning The shortest program in bytes wins. [Answer] # მƧƎ ɈqiɿɔƧɒvɒႱ, ~~54~~ ~~47~~ ~~88~~ ~~65~~ ~~60~~ 67 bytes **JavaScript ES6** I've updated to the new question specifications. ``` (a,b)=>b.map(l=>([y,x]=l,l[g=a[0]>'x']+=l[g]-eval(a.slice(2))*2,l)) ``` I've defined variables x and y to their corrosponding value so we can eval the expression to get the value. Using `[x,y]=l`, we can easilt set x to `l[0]` and y to `l[1]` ``` (a,b)=>b.map(l=>([x,y]=l,l[a[0]<'y'|0]+=eval(a.slice(2)),l)) ``` Broken up: ``` (a,b)=> // Function with args: a and b b.map(l=> . Loops through b ( l[ // Gets x or y depending on condition a[0]<'y'|0 // x returns 0, y returns 1 ] += // plus... eval( // evaluate the following expression a.slice(2).replace( // Replace the input expression /x|y/g, // Match 'x' and 'y' l=> `*l[${l<'y'|0}]`) // Multiple previous value by corresponding value ) ,l)) // Returns new coordinates ``` --- The old version which didn't expect variables on the right-hand side, **(47 bytes)** ``` (a,b)=>b.map(l=>(l[a[0]<'y'|0]+=+a.slice(2),l)) ``` Running it (second example): ``` [[2.05, -1.13], [6.63, -2.78], [5.57, 2.45], [4.86, 0.15]] ``` ]
[Question] [ Write the shortest parser for the grammar: ``` M -> M + n | n ``` * Output must be some representation of a structured value representing the concrete syntax tree produced by the input `n+n+n`. * The code to produce the textual output from the structured value is not necessary. * The code to read/validate input is not necessary. * Solution is anything that can somehow be called; a function, an object, doesn't matter. * How your solution receives input (currying character-by-character, whole-string, some kind of input reader) does not matter. For example a bottom-up parser (Javascript, 284 characters): ``` function M(d){function c(a){throw"unexpected "+a;}function f(a){if("+"==a)return b.push(a),e;if(null==a)return b;c(a)}function e(a){if("n"==a)return b.push(a),b=[b],g;c(a)}function g(a){if("+"==a)return b.push(a),e;if(null==a)return b;c(a)}var b=[];if("n"==d)return b.push(d),f;c(d)}; ``` When called: ``` M('n')('+')('n')('+')('n')(null) ``` will return an array that in JSON-notation looks like this: ``` [["n", "+", "n"], "+", "n"] ``` --- Edit for the uninitiated in parsing: This is one of those questions where making a program produce the correct output is easy but the form of the program is essential for up-boats. ``` M -> M + n | n ``` Means that `M` consists of a previous `M`, a plus sign and a literal `"n"`. Or good `M` is a single `"n"` literal character. There are several way of approaching this challenge, I'll describe my own solution, which is called bottom-up parsing. Character by character: ``` Stack Incoming Character Action on stack n n + reduce "n" to M M+ n M+n + reduce "M + n" to M M+ n M+n EOF reduce "M + n" to M M ``` The twist in this question is that the simplest form of parsers called "recursive-descent" parsers won't work because the grammar is left-recursive and that throws a recursive-descent parser into an infinite loop. [Answer] ## Ruby, 51 bytes ``` f=->s{s.split(/(\+)(?=n$)/).map{|t|t['+n']?f[t]:t}} ``` This seems weirdly cumbersome. It can be called like `f['n+n+n']`. [Answer] # CJam, 13 15 If I have understood what did you mean by "the code to validate input is not necessary" correctly: ``` {'+/{[\"+"@]}*} ``` ### Example ``` {'+/{[\"+"@]}*}:T; "n+n+n" T` N "n+n+n+n" T` ``` Output: ``` [["n" "+" "n"] "+" "n"] [[["n" "+" "n"] "+" "n"] "+" "n"] ``` Or if I have to check the grammar: # CJam, 24 ``` {'+/_"n"a-L@{[\"+"@]}*?} ``` [Answer] # Augeas, 42 ``` module A=let rec l=[key"n".(del"+""+".l)?] ``` Example usage, by adding: ``` test l get "n+n+n" = ? ``` and launching: ``` $ augparse a.aug Test result: a.aug:2.0-.22: { "n" { "n" { "n" } } } ``` Due to the bidirectional nature of Augeas lenses, the provided code also manages the reverse transformation, e.g. by using: ``` test l put "n" after clear "n/n/n" = ? ``` then launch augparse: ``` $ augparse a.aug Test result: a.aug:2.0-.38: "n+n+n" ``` [Answer] # Pyth, ~~20~~ 13 bytes ``` L.U[b\+Z)cz\+ ``` Took me forever to shorten it, but I did! I changed pretty much the entire algorithm. Defines a function `y` that takes one string argument. [Live demo with 3-byte test harness and test cases.](https://pyth.herokuapp.com/?code=L.U%5Bb%5C%2BZ)cb%5C%2B%0Ayz&input=n%2Bn&test_suite=1&test_suite_input=n%0An%2Bn%0An%2Bn%2Bn&debug=1) ## Original ``` ?tJu?qH\n+GH,GHzkJ]J ``` [Live demo and test cases.](https://pyth.herokuapp.com/?code=%3FtJu%3FqH%5Cn%2BGH%2CGHzkJ%5DJ&input=n&test_suite=1&test_suite_input=n%0An%2Bn%0An%2Bn%2Bn&debug=1) ]
[Question] [ A typing speed test loads up a dictionary of words, and gives you one to type: `pinball`. You, with your fast but inaccurate fingers, type in `pinbnal`. Darn it! Make a program that will print out a random word from a dictionary, then ask for the user to type this word back, and finally return whether or not they got the word right. The catch is: the program must accept minor typos. Accept a typo if it has only one of the following: * one letter is repeated in the input 1 or 2 more times. Only accept the letter if it is directly adjacent to a letter it is next to. * one letter in the word is repeated 1 time. * 2-4 of the letters in the input are scrambled. Some acceptable typos of the word `pinball` are: `pingball pinbala pinbanll` Some unacceptable typos: `pibnannl maxwell pinbalgl` Shortest code wins. Good luck. [Answer] # Mathematica 179 Edit: As Primo correctly notes, the following does not adhere to the constraint of pardoning only those intrusions from QWERTY neighbors. DL distance, of course, has nothing to do with distance on a keyboard. Oh, well. I'll leave up my response, which someone with more patience will easily better. --- Code ``` d = DictionaryLookup[]; i = d[[RandomInteger@{1, Length@d}]];o = InputString["Type: " <> i]; Print["in: ", i, "\nout: ", o, "\n", Switch[i~DamerauLevenshteinDistance~o, 0, "perfect", 1, "ok", _, "wrong"]] ``` --- Explanation 1. `d = DictionaryLookup[]` stores a built-in dictionary of 92 k English words in `d`. 2. `i = d[[RandomInteger@{1, Length@d}]]` selects a random word and stores it in `i`. 3. `o = InputString["Type: " <> i];` opens a dialog window (see figure) with the prompt "Type [i]." 4. `i~DamerauLevenshteinDistance~o` computes the Damerau-Levenshtein distance beween the requested word and the word typed by the user. If the DL distance = 0, "perfect"; if the DL distance = 1, "ok"; otherwise, "wrong". ![tureen](https://i.stack.imgur.com/3Z00x.png) --- Test Results For the first 7 tests, the input string, i, was manually set to "pinball". The results were as desired with the exception of "pinbalgl", which was considered acceptable because it returns a DL distance value of 1. > > in: pinball > > out: pinball > > perfect > > > in: pinball > > out: pingball > > ok > > > in: pinball > > out: pinbala > > ok > > > in: pinball > > out: pinbanll > > ok > > > in: pinball > > out: pinbannl > > wrong > > > in: pinball > > out: maxwell > > wrong > > > in: pinball > > out: pinbalgl > > ok > > > in: tureen > > out: turen > > ok > > > in: feeder > > out: feedr > > ok > > > in: tarmacs > > out: tarmax > > wrong > > > [Answer] ## Python 2, ~~634~~ ~~581~~ ~~568~~ 565 bytes ``` import random s="aszaqwsxdswedcfderfvgfrtgbhgtyhnjhyujmkjuikiopolkmnbvcx" s+='z'+s[::-1] d={} for j in range(len(s)-1):d[s[j]]=d.get(s[j],"")+s[j+1] v=random.choice(open("d","r").read().split()) u=list(raw_input(v+':')) v=list(v) e=sorted i=n=r=b=0;l=len(v);g=1 q=any([v[:j]+e(v[j:j+4])+v[j+4:]==u[:j]+e(u[j:j+4])+u[j+4:]for j in range(l-3)]) while i<l*g: g*=i<len(u) if v[i]!=u[i]: if any([0<=i<l and u[i]in d[v[i+c]]for c in-1,0]):n+=1;g-=(b and u[i]!=b);b=u[i];del u[i] elif u[i]in v:r+=1;del u[i] else:g=0 else:i+=1 print'good'if q+g*(n+2*r<3)else'bad' ``` It took a heck of lot of bytes to meet every single little special case and exception that this problem called for, and that's reflected in the size. There's probably some optimizations I'm missing, but I'm just happy that I met all the requirements. To run it, put your list of lowercase words in a file called `d` in the same directory and just run. It should be clear how this works once you know what each variable is: * `s`: a String of adjacent keys used to construct `d` * `d`: a Dictionary encoding a graph of key adjacencies, according to the keyboard i'm using right now. Lines 1 through 4 set this up. * `v`: the random word, first as a string, then as a list of characters * `u`: the User input, as a list of characters * `e`: the `sortEd` built-in * `i`: the Index into the correct word * `n`: the number of times an incorrect character that is Next to a correct character appears * `r`: the number of times an incorrect character that is in the word Repeats * `g`: whether the input is currently believed to be Good * `l`: the correct Length of the word * `q`: whether some shuffling of four adjacent letters in the user input would yield the correct word * `j`: a temp used in the creation of `q` The important parts are: * the for at the top, which maps each letter in `s` to the next character. At the end, each lowercase letter is mapped to a string containing all letters adjacent on the keyboard (some with several repeats, but it doesn't matter). * the line where q is evaluated, which basically just sorts each set of four adjacent characters in both the input and correct word while leaving the rest of the lists alone. If sorting any such part results in both lists being the same, this is an allowed typo according to rule 3 * the while loop, which iterates over both strings, looking for mismatches. Where one is found, it determines whether its of type 1 or type 2, preferring the former since we're allowed more type 1 errors than type 2 errors. The numbers of errors of type 1 and 2 are counted in `n` and `r` respectively. Errors which don't fall into either of these categories set `g` to 0 which breaks the loop. Notice the `g-=(b and u[i]!=b);b=u[i]`. This checks that this type 1 error involved the same character (saved in `b`) as last time (if there was a last time). This is because the first rule allows us to repeat the *same* character 1 or 2 times, but not two different characters. * the final line outputs good if and only if `q` OR (`g` AND (`n<3` AND `r==0`) OR (`r<2` AND `n==0`) ). Type 3 errors are mutually exclusive with the other types, but it is possible to have both type 1 and 2 in the same input. The condition is complex to allow one or the other but not both. NB: this program will NOT accept "pinbala" as a correct spelling of "pinball", as it does not fall into any of the three described typo categories, as pointed out by [ceased to turn counterclockwis](https://codegolf.stackexchange.com/questions/6540/lenient-typing-test#comment13759_6540) ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/2211/edit). Closed 8 years ago. [Improve this question](/posts/2211/edit) Create a small acceptably efficient JS CSS selector engine. Please post size of script, and function to call preferable $(selector,context) style. EDIT: All major browsers support `document.querySelectorAll` which makes this question irrelevant. [Answer] Funny, I just made one of these. It is quite efficient because it compiles selectors. I don't know if it's IE6-compatible but it should be, I think. It supports CSS3 too - bonus points? :) ``` if(![].indexOf)Array.prototype.indexOf=function(a,i){i=i||0;while(i<this.length)if(this[i++]===a)return i-1;return-1}; String.prototype.startsWith=function(s){return this.length>=s.length&&this.substring(0,s.length)===s}; String.prototype.endsWith=function(s){return this.length>=s.length&&this.substring(this.length-s.length)===s}; var Sprint = { Error: function(m) { this.message = m; this.toString = function() { return this.message; }; }, getAllElementsIn: function(element) { var r = []; var f = function recurse(l, arr) { from(l).each(function(k, v) { if(v.nodeType === 1) { arr.push(v); recurse(v, arr); } }); }; f(element, r); return r; }, getAllElements: function() { return Sprint.getAllElementsIn(document.documentElement); }, getSiblings: function(element) { return element.parentNode ? from(element.parentNode).where(function(k, v) { return v.nodeType === 1; }).toArray() : [element]; }, getInfo: function(selector) { var r = {ATTR: {}, CLASS: [], PSEUDO: []}; var quotes = '\'"', nestable = '(){}', inAttribute = false, escaped = false, currentQuotes = null, currentNested = [], nonchar = /^[^a-zA-Z0-9_\-]$/, lastSplitter = null, i = -1, c, s = ''; while(++i < selector.length) { c = selector.charAt(i); if(escaped) { escaped = false; } else if(c === '\\') { escaped = true; continue; } else if(currentQuotes) { if(currentQuotes === c) { currentQuotes = null; } } else if(quotes.indexOf(c) > -1) { currentQuotes = c; } else if(currentNested.length) { if(nestable.indexOf(currentNested[currentNested.length - 1]) + 1 === nestable.indexOf(c)) { currentNested.pop(); } } else if(nestable.indexOf(c) > -1) { currentNested.push(c); } else if(nonchar.test(c)) { if(lastSplitter) { switch(lastSplitter) { case '#': r.ID = s; break; case '.': r.CLASS.push(s); break; case '[': case ',': if(inAttribute) { var j; if((j = s.indexOf('=')) > -1) { r.ATTR[s.substring(0, j)] = s.substring(j + 1); } else { r.ATTR[s] = true; } } break; case ':': r.PSEUDO.push(s); break; } } else { r.TAG = s; } if(c === ']') { inAttribute = false; } else if(c === '[') { inAttribute = true; } lastSplitter = c; s = ''; continue; } s += c; } if(lastSplitter) { switch(lastSplitter) { case '#': r.ID = s; break; case '.': r.CLASS.push(s); break; case '[': case ',': if(inAttribute) { var j; if((j = s.indexOf('=')) > -1) { r.ATTR[s.substring(0, j)] = s.substring(j + 1); } else { r.ATTR[s] = true; } } break; case ':': r.PSEUDO.push(s); break; } } else { r.TAG = s; } return r; }, compileSingle: function(info) { var f = 'var t=l.nodeName?l.nodeName.toLowerCase():"",i=l.id?l.id.toLowerCase():"",c=l.className?" "+l.className.toLowerCase()+" ":"",s=Sprint.getSiblings(l),ss=from(s).where(function(k,v){return v.nodeName?v.nodeName.toLowerCase()===t:false;}).toArray(),si=s.indexOf(l),ssi=ss.indexOf(l);return '; if(info.TAG && info.TAG !== '*') { f += 't===\'' + info.TAG.toLowerCase().replace(/[\\']/g, function(x) { return '\\' + x; }) + '\'&&'; } if(info.ID) { f += 'i===\'' + info.ID.toLowerCase().replace(/[\\']/g, function(x) { return '\\' + x; }) + '\'&&'; } if(info.CLASS) { for(var i = 0; i < info.CLASS.length; i++) { f += 'c.indexOf(\' ' + info.CLASS[i].toLowerCase() + ' \')>-1&&'; } } if(info.PSEUDO) { for(var i = 0; i < info.PSEUDO.length; i++) { var p = info.PSEUDO[i], j, v = ''; if((j = p.indexOf('(')) > -1) { v = p.substring(j + 1, p.length - 1); p = p.substring(0, j); } switch(p) { case 'first-child': f += '!si'; break; case 'first-of-type': f += '!ssi'; break; case 'nth-child': // TODO: Implement all nth-*** selectors. break; case 'nth-of-type': break; case 'last-child': f += 'si===s.length-1'; break; case 'last-of-type': f += 'ssi===ss.length-1'; break; case 'nth-last-child': break; case 'nth-last-of-type': break; case 'only-child': f += 's.length===1'; break; case 'only-of-type': f += 'ss.length===1'; break; case 'disabled': f += 'l.disabled'; break; case 'enabled': f += '!l.disabled'; break; case 'checked': f += 'l.checked'; break; case 'empty': f += '!l.childNodes.length'; // TODO: Maybe restrict to elements (t 1) only? break; case 'not': f += '!Sprint.isMatch(\'' + v.replace(/\\'/g, function(x) { return '\\' + x; }) + '\')(0,l)'; break; default: throw new Sprint.Error("Unrecognized pseudo-class \"" + p + "\"."); } f += '&&'; } } if(info.ATTR) { from(info.ATTR).each(function(k, v) { var c = k.charAt(k.length - 1); f += 'l.getAttribute(\'' + ('$^*~|'.indexOf(c) > -1 ? k.substring(0, k.length - 1) : k).replace(/\\'/g, function(x) { return '\\' + x; }) + '\')'; if(typeof v === 'string') { v = v.replace(/\\'/g, function(x) { return '\\' + x; }); switch(c) { case '$': f += '.endsWith(\'' + v + '\')'; break; case '^': f += '.startsWith(\'' + v + '\')'; break; case '*': f += '.indexOf(\'' + v + '\')+1'; break; case '~': f += '.split(\' \').indexOf(\'' + v + '\')+1'; break; case '|': f += '.split(\'-\').indexOf(\'' + v + '\')+1'; break; default: f += '===\'' + v + '\''; } } f += '&&'; }); } if(f.substring(f.length - 2) !== '&&') { // It matches anything. f = 'return true '; } return new Function(['l'], f.substring(0, f.length - 2) + ';'); }, compileTree: function(selector) { var t = Sprint.tokenizeSelector(selector), i = -1, j, splitters = ', >~+'; while(++i < t.length) { if(splitters.indexOf(t[i]) > -1) { j = i; while(--j >= 0 && t[j] === ' ') t[j] = null; j = i; while(++j < t.length && t[j] === ' ') t[j] = null; } } return from(t).where().select(function(k, v) { return k % 2 ? v : Sprint.compileSingle(Sprint.getInfo(v)); }).toArray(); }, matchSingleTree: function(element, tree) { if(!tree.length) { return true; } if(!tree[tree.length - 1](element)) { return false; } for(var i = tree.length - 3; i >= 0; i -= 2) { switch(tree[i + 1] || ' ') { case ' ': while(true) { if(!(element = element.parentNode)) { return false; } if(tree[i](element)) { break; } } break; case '>': if(!(element = element.parentNode) || !tree[i](element)) { return false; } break; case '+': while(true) { if(!(element = element.previousSibling)) { return false; } if(element.nodeType === 1) { if(!tree[i](element)) { return false; } else { break; } } } break; case '~': while(true) { if(!(element = element.previousSibling)) { return false; } if(tree[i](element)) { break; } } break; } } return true; }, matchTree: function(element, tree) { var c = []; for(var i = 0; i < tree.length; i++) { if(tree[i] === ',') { if(Sprint.matchSingleTree(element, c)) { return true; } c = []; } else { c.push(tree[i]); } } return Sprint.matchSingleTree(element, c); }, tokenizeSelector: function(selector) { var quotes = '\'"', nestable = '(){}[]', escaped = false, currentQuotes = null, currentNested = [], tokens = [], splitters = ', >~+', i = -1, c, s = ''; while(++i < selector.length) { c = selector.charAt(i); if(escaped) { escaped = false; } else if(c === '\\') { escaped = true; continue; } else if(currentQuotes) { if(currentQuotes === c) { currentQuotes = null; } } else if(quotes.indexOf(c) > -1) { currentQuotes = c; } else if(currentNested.length) { if(nestable.indexOf(currentNested[currentNested.length - 1]) + 1 === nestable.indexOf(c)) { currentNested.pop(); } } else if(nestable.indexOf(c) > -1) { currentNested.push(c); } else if(splitters.indexOf(c) > -1) { tokens.push(s); tokens.push(c); s = ''; continue; } s += c; } tokens.push(s); return tokens; }, isMatch: function(selector) { var f = Sprint.compileTree(selector); return function(key, element) { return Sprint.matchTree(element, f); }; }, select: function(selector) { return from(Sprint.getAllElements()).where(Sprint.isMatch(selector)).toArray(); }, selectIn: function(selector, element) { return from(Sprint.getAllElementsIn(element)).where(Sprint.isMatch(selector)).toArray(); } }; function from(x) { if(!x) { throw new Sprint.Error("null or undefined passed to Sprint:from()."); } var r = { keys: [], values: [] }; if(x.length) { for(var i = 0; i < x.length; i++) { r.keys.push(i); r.values.push(x[i]); } } else if(x.childNodes) { return from(x.childNodes); } else { for(var y in x) { if(x.hasOwnProperty(y)) { r.keys.push(y); r.values.push(x[y]); } } } r.length = r.keys.length; r.where = function(f) { if(f) { if(typeof f === 'string') return this.where(new Function(['k', 'v'], 'return ' + f + ';')); var r = {}; for(var i = 0; i < this.length; i++) { if(f(this.keys[i], this.values[i])) { r[this.keys[i]] = this.values[i]; } } return from(r); } else { return this.where(function(k, v) { return v; }); } }; r.select = function(f) { var r = {}; for(var i = 0; i < this.length; i++) { r[this.keys[i]] = f(this.keys[i], this.values[i]); } return from(r); }; r.each = function(f) { for(var i = 0; i < this.length; i++) { f(this.keys[i], this.values[i]); } }; r.first = function() { return this.values[0]; }; r.last = function() { return this.values[this.length - 1]; }; r.splitBy = function(f) { if(typeof f === 'function') { var r = [], c = {}; for(var i = 0; i < this.length; i++) { if(f(this.keys[i], this.values[i])) { r.push(c); c = {}; } else { c[this.keys[i]] = this.values[i]; } } r.push(c); return from(r); } else { return this.splitBy(function(x) { return x === f; }); } }; r.limit = function(f) { var r = {}, i = -1; if(typeof f === 'function') { while(++i < this.length && f(this.keys[i], this.values[i])) { r[this.keys[i]] = this.values[i]; } } else { while(++i < Math.min(this.length, f)) { r[this.keys[i]] = this.values[i]; } } return from(r); }; r.after = function(f) { var r = {}, i = -1; if(typeof f === 'function') { while(++i < this.length && !f(this.keys[i], this.values[i])) { } while(++i < this.length) { r[this.keys[i]] = this.values[i]; } } else { if(f < this.length) { i = f - 1; while(++i < this.length) { r[this.keys[i]] = this.values[i]; } } } return from(r); }; r.toArray = function() { return this.values; }; return r; } ``` You use it like so: ``` Sprint.selectIn("mySelector", element); ``` Or ``` Sprint.select("mySelector") ``` . The code is 6.89KB minified and 2.26KB gzipped. ]
[Question] [ # Challenge Create a 3D word puzzle where the cube's dimensions match the length of the input word. The uppercase word (A-Z) must be validly placed within the cube in one of the fixed orientations: horizontally, vertically, or diagonally. The program should randomly place the hidden word and fill the rest of the cube with random letters. **Input** ``` WORD ``` **Output** ``` Display the cube (n x n x n) layer by layer, where n is the WORD's length. ``` # Examples **UP** [![UP](https://i.stack.imgur.com/wAscW.png)](https://i.stack.imgur.com/wAscW.png) **AND** [![AND](https://i.stack.imgur.com/X3tXk.png)](https://i.stack.imgur.com/X3tXk.png) **DOWN** [![DOWN](https://i.stack.imgur.com/KQVV4.png)](https://i.stack.imgur.com/KQVV4.png) **APPLE** [![APPLE](https://i.stack.imgur.com/1tU4J.png)](https://i.stack.imgur.com/1tU4J.png) **ORANGE** [![ORANGE](https://i.stack.imgur.com/mDmvf.png)](https://i.stack.imgur.com/mDmvf.png) **CODEGOLF** (Can you find it?) ``` N Y R Z O F K G Y G B V E T P M O J F K Y O O K O Z N Q F A R P M X E T N O I Y F H C U O F Z A G V A V O O F B B V K U O V L F W Y L W U H H K Z M Z X D R K Q G D D A B I D F P Y G U I D L I J Y D O M D Q W F H B Q Q N B B T A C F J Q L K H R Y R Y B Z Q L F C D Z B Z W L E A J O F F J Z O X Q G A R C W N N W Y Z S U S G E V T A C F K F E O R O N V K D G Z N W O P L I W W J L C U K L Z Q M A G C M R Q E F M O I O K T K T U A U S E X A Y K C D N J D V G E S G X O F P T S F I H Z B X E X U T X R Q G V P Q O B H F C J P Y A P I Z G R X N A A W Z H A Z H V Q X T E T B Z A Q A V I Z H G D E H N J L G G W V K A O Q U S G N K M M X R G Z B Q K R Y O R I O J C Q K C P F F U D R M U J G E K B F A A C I K G P O B M N E M P M B K X X T V B V N Z O R P K N Q N J B M D M L R C O U C F A O H U H R E P M L E T B F R Y W J S U C Y A N M X S W E C C X C U F U V Q U H J C Z W Y E J S Z D C U I R F Z C H D I M M C W F W G N I I Z U C X W Q M C O N Y O W K X E Z J U G Y U W Q V V C N B T A T E Z W C X Z E O W Z N S C J P V X X ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~226~~ ~~213~~ ~~227~~ ~~222~~ 219 bytes ``` from random import* def f(w): W=len(w);G=eval('[[[chr(randint(65,90))'+f"for _ in' '*{W}]"*3);l,a,b=map(randrange,(W,W,15)) for n in range(W):G[[n,l][b&2>0]][[a,n][b!=4]][[a,n,n,W-n-1][b//4]]=w[::b%2or-1][n] return G ``` [Try it online!](https://tio.run/##jZDBToQwEIbvPMW4ibbF4sKuayKbejLhaLKXHprGgBS3BAqpKDHGZ8eWZePBi9M0/f9pvplO@8/h2JntNFW2a8HmpnSHbvvODmFQqgoqPJI0AM4aZZzcZ0x95A1GQoiXo8We0GbAdzt6HxOCrqtV1Vl4Bm0QoPCLf8tVuCX7hua0YG3ez4Tbr4piTjlNdoQE4BnjGJhvMCdpJoShjRTF1eYhllKInBrnLtjtYtzikYkSl1yvXZKNIk2Ly01nfc7IAKwa3q2BbHpTqsQJCc4vW7oksZ/MxQgMEH86PKLZHpz1Y8/GM/qXOf3CwvnorR8feYlu6k4bpxdxELUUWpK5Rv2nBjk1WApE/wxEph8 "Python 3 – Try It Online") * *-13 bytes* by replacing `randint` with `randrange` * *+14 bytes* by implementing the reverse of a word * *-5 bytes* by creating a `b` variable to store `d`, `o` and `i`, and by using `eval` * *-3 bytes* by removing the `randrange` alias, and inlining the `r` variable A function that receives a word \$w\$ and returns a 3x3x3 matrix composed of lists. To see where the word is, change `chr(65+g(26))` to `chr(97+g(26))`. --- **How does it work?** The `g`enerator stores an instance of the [`random.randrange`](https://docs.python.org/3/library/random.html#random.randrange) function. The `r`ange stores the numbers from 0 to until the length of the `w`ord, exclusive. We initialize the `G`rid to random uppercase letters (`chr(65+g(26))`). We initialize three variables with random values: * `l`ayer: define the index of the layer the word will be written (UP: layer 1, APPLE: layer 2); this variable is ignored if the word is spread across layers * `a`xis: define the index of the axis the word will be written (AND: axis 1, DOWN: axis 0, APPLE: axis 0); this variable is ignored if the word is set diagonally * `b` a 4-bits integer, where + if the first bit is 0, the word will be put right-to-left (in reverse); otherwise, left-to-right + if the second bit is 0, the word will spread across layers (see AND, DOWN and ORANGE test cases); otherwise, it will be contained in a single layer (see UP and APPLE test cases) + if the third and fourth bits are `00`, the word will be set horizontally (AND and DOWN test cases); if `01`, the word will be set vertically (APPLE test case); if `10`, the word will be set diagonally-forward (UP and ORANGE test cases); if `11`, the word will be set diagonally-backward (see CODEGOLF test case). Then, for each character of the `w`ord, we update the `G`rid doing some arithmetic based on `l`, `a` and `b`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 56 bytes ``` W⁼⌊υ⌈υ«≔⁻E³‽⁺²Lθ²υ≔EθEυ⎇‹μ⁰⎇⊕μ⁻⊖Lθλλμυ»EθEθ⭆θ§⁺θ‽α⌕υ⟦κμξ ``` [Try it online!](https://tio.run/##TU9La8MwDD6vv0JHGTwY3bGnQjcotKy0gx1GDyYxiZmtNn50KWW/3ZPTsMwgLH3oe6hqla9Oyub83RqrAV@6pGzArSHjksMkJGxVP/ZCwG32sAzBNFRWEi@qMz5L2CuqTw53lqG5hI2mJrbYMYMF5lxJLCYmc7qie8Yk4V17Uv6KGx0COglPYsLWVHntNEVdoytRBs@VntDJSYIdyw2uxfFntvOG4n9H/g6RwWYclnFNte7v0bu/S1SReDVUl4ifXywqoT@K4S1y/njbr/Ljxf4C "Charcoal – Try It Online") Link is to verbose version of code. Enter the word in lower case if you want to make it obvious where it ended up. Explanation: ``` W⁼⌊υ⌈υ« ``` Repeat until a suitable word placement is found. ``` ≔⁻E³‽⁺²Lθ²υ ``` For each axis, either select a fixed index from `0` to the length of the word, or `-1` to spread the word in the forward direction along that axis, or `-2` to spread it in the reverse direction (so for example `-2, -2, -2` would result in the word written in reverse along the main diagonal). ``` ≔EθEυ⎇‹μ⁰⎇⊕μ⁻⊖Lθλλμυ ``` Use the randomly selected indices to generate a list of coordinates of each letter of the word. ``` »EθEθ⭆θ§⁺θ‽α⌕υ⟦κμξ ``` Output the cube, but selecting the letter from the word instead of a random letter if the current coordinates are from the selected list. [Answer] # C (gcc), ~~655~~ ~~542~~ ~~446~~ 437 bytes *-105 bytes, thanks to @ceilingcat* To disable the word hint, change `w[i]|32` to `w[i]|0`. ``` #define r rand() f(w,s)char*w;{char*u=calloc(s*s,s);int x,y,z,a,b,c,p,i=s/2,l,m,n;if(r%2)for(;i--;)w[i]^=w[s+~i]^=w[i]^=w[s+~i];do for(x=r%s,y=r%s,z=r%s,a=r%3-1,b=r%3-1,c=r%3-1,p=a|b|c,i=0;i<s&&p;p*=l>=0&m>=0&n>=0&l<s&m<s&n<s)l=x+i*a,m=y+i*b,n=z+i++*c;while(!p);for(i=s;i--;)u[((x+i*a)*s+y+i*b)*s+z+i*c]=w[i]|32;for(;y=++i<s*s*s;)u[i]=u[i]?:65+r%26;for(;y<s;y+=puts(""))for(z=0;z<s;z+=printf(" "))for(x=0;x<s;)putchar(u[x++*s*s+y*s+z]);} ``` [Try it online!](https://tio.run/##TVJda@MwEHzPr/D5aJAshaYJl4fbqEe59PJSklAofTA@cBS7FdiKsRz8kaR/PV3JKdTGs6sdDRrtWo7epLxcfu6SVOnEK70y1jtCBympuaHyPS6DGo4uHoSMs2wviQkMcqB05TW85R2P@ZZLXnAlzO2EZzznGlRKypsJTfclATUaAa1DFf0XdWjYR598W8Ju79mdjShvDG8ddg5jxOnojm@vUV5jIeLT9iTxyDGouRkOCygCkd2L8TC3oC1kSOT46bmhmWiYCmKeixbjlmvRMcVYIKF@V1lCfhQUrAW8Q@/3EBLiJDQwzGlsgqJARs79aTpxCmgFY@ghwNfKVCQs/Pk9@8WwBbPrprmBloniUBni@9Q1pkPzHdY7rJfYzpT43pVqkGqQoiiw3SeHsEG3xnqxNiIK54uCPFaaGHocePgYN7tK5QkZUwqu1k8wjMTRf9n43H9YLRAX69eVXWw2T48Y188Pq6VN/q4Xj8v10z//3Kv76c2N6pJ96tW3X0k4jkB9u8zRCFOVWaKJbQwFe6pX4WzvIkgJUrJoScUdaX@d8@B8@QQ) ]
[Question] [ # Code Golf Challenge Given a string of 10 characters: `'abcdefghij'` I want to format it in this pattern and print it in the console in a minimum number of characters: `(abc) def-ghij` My solution: ``` print(f"({s[0:3]}) {s[3:6]}-{s[6::]}") ``` [Answer] # [Python 3](https://docs.python.org), 35 bytes ``` print(f"({s:.3}) {s[3:6]}-{s[6:]}") ``` **[Try it online!](https://tio.run/##K6gsycjPM7YoKPpfrGCroJSYlJySmpaekan0v6AoM69EI01Jo7rYSs@4VlOhujja2MostlYXyDCziq1V0vz/HwA "Python 3.8 (pre-release) – Try It Online")** Uses the solution from the question but saves three bytes: 1. removes a redundant `:` in the final slice `s[6::]`, and 2. uses the `precision` specifier (`.`) of the `format_spec` (the bit after the `:` in `{...:...}`) which is overloaded for string types to give a prefix so `{s[0:3]}` -> `{s[:3]}` -> `{s:.3}` [Answer] # [Python](https://www.python.org), 36 bytes *slightly improved version of your f-string (see also Jonathan Allan's comment), wrapped in a function* ``` print(f"({s[:3]}) {s[3:6]}-{s[6:]}") ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwZo025zE3KSURIViq5ilpSVpuhY3VQqKMvNKNNKUNKqLo62MY2s1FYAMYyuz2FpdIMPMKrZWSROidn2ahlJiUnJKalp6RmYWTHTBAggNAA) --- # [Python](https://www.python.org), 37 bytes *without format strings* ``` print("("+s[:3]+")",s[3:6]+"-"+s[6:]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwZo025zE3KSURIViq5ilpSVpuhY3VQuKMvNKNJQ0lLSLo62MY7WVNJV0iqONrcyATF2QoJlVrCZE8fo0DaXEpOSU1LT0jMwsJajoggUQGgA) uses that `print` inserts a space between arguments --- # [Python](https://www.python.org), 39 bytes *C-style format string* ``` print("(%s%s%s) %s%s%s-%s%s%s%s"%(*s,)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwZo025zE3KSURIViq5ilpSVpuhY31QuKMvNKNJQ0VItBUFMBQutCKNViJVUNrWIdTU2o8kAlJaX8vFSFpMqSVIWc_Lz01CIrLoQRIO26YE3F0VbGsTrF0cZWZiDKzCpWU5MLqJmLK01DKTEpOSU1LT0jM0sJavCCBRAaAA) printing characters separately is slightly shorter than spiting string in 3 parts [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 46 bytes ``` "($($a[0..2])) $($a[3..5])-$($a[6..9])"-join'' ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0lDRUMlMdpAT88oVlNTAcwx1tMzjdXUBbPN9PQsYzWVdLPyM/PU1f///w8A "PowerShell – Try It Online") The output is a little weird, if someone can suggest a fix to that it would be much appreciated! ]
[Question] [ I've looked and could not find a post for this, if there is one, I'll remove it quick! [Related](https://codegolf.stackexchange.com/questions/9276/c-replace-aes-fips-197-subbytes-table-by-constant-time-code) and [also related](https://codegolf.stackexchange.com/questions/48052/decrypting-a-block-of-aes) The goal is (hopefully) clear: create the shortest code (in bytes) that implements the AES256 ECB cipher mode. Either convert the result to Base64 or output a array of bytes. The input contains two parts. The first part is the stuff to encrypt, and the second part (separated by newlines) is the secret key. You do not need to [decrypt it](https://codegolf.stackexchange.com/questions/48052/decrypting-a-block-of-aes)! ## Test cases! **Input:** ``` AES Encryption! averygoodsecretpasswordthatsgood ``` **Output:** ``` VBWQy7umRdabP1xs2y1Oqg== ``` You may output as an array of bytes too, if you wish. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 90 bytes *Disclaimer: even with clean ungolfed code, don't use ECB mode for anything serious unless you're 100% certain its weaknesses are acceptable for your use case.* Expects `(string)(key)` and returns an array of bytes. ``` s=>k=>[...(c=require('crypto').createCipheriv("aes-256-ecb",k,"")).update(s),...c.final()] ``` [Try it online!](https://tio.run/##XY3BTsMwEETvfEXwJbaU7AFBL8iVUtQv6BFxcJ11ahq87q4T1K8PhiPHmXl68@lWJ55jLn2iEbdgN7H7q92/A4D2lvG2REbder7nQq0Bz@gKvsV8QY6rVg6lf3rZ9ejPqrt2ShkDSx4ro8V01eIhxORmbT62obFN0Go4nppj@jNGSo/KVMuKfJ@IRsF6ULIT@SYey8UV@a2VeX3wlIRmhJkmPfzLhyUEZAhMX3WDQqfCMU26PTvB3XNrzPYD "JavaScript (Node.js) – Try It Online") ]
[Question] [ Maximillian is the chief commander of the Great Greek Army and he is leading his forces into a crucial war with Spain. If all the enemy soldiers stand in a straight line incrementally marked starting from position `1`, and a particular soldier at position \$i\$ dies, the soldiers at position \$2i\$ and \$2i+1\$ die as well. This happens in a cascading manner and so, a major part of troops can be killed by just killing one person. By retrospection, Maximillian realizes that this also means that if the soldier marked \$1\$ (standing at the head of the troops) is killed and then the entire army is defeated. This however is not an easy task as the commander of the Spanish leads the Spanish troops and stands at the head of the troops. When one cascading set of deaths is completed, the remaining troops re-align; filling in the missing gaps and the death rule applies to the new positions. Let there be \$N\$ soldiers in the enemy's camp marked as \$1,2,3,..., N\$. Maximillian identifies a list of \$K\$ individuals by their marked numbers, who will be executed in a sequential manner. Output the list of soldiers left in the enemy camp in increasing order of their marked values. --- **Input Specification:** `input1:` `N`, number of soldiers in the enemy camp `input2:` `K`, number of soldiers to be killed `input3:` An array of soldiers numbered between `1` to `N` who will be killed sequentially in the mentioned order **Output Specification:** Output an array of numbers that belong to soldiers who are alive at the end​ (in increasing order). If all are dead, then output `{0}`. --- **Test Case 1** ``` input1: 7 input2: 1 input3: {1} ``` ``` Output: {0} ``` **Explanations:** The soldiers can be represented in the following way: [![enter image description here](https://i.stack.imgur.com/GrRKg.png)](https://i.stack.imgur.com/GrRKg.png) When Soldier `{1}` is killed, then `{2,3}` die. When `{2,3}` die, `{4,5,6,7}` die. **Test Case 2** Example 2: ``` input1: 7 input2: 2 input3: {2,7} ``` ``` Output: {1,3,6} ``` **Explanations:** The soldiers can be represented in the following way: [![enter image description here](https://i.stack.imgur.com/sIiJC.png)](https://i.stack.imgur.com/sIiJC.png) When Soldier - `{2}` is killed, then `{4,5}` die. They do not have any troops at \$2i\$ and \$2i+1\$. The new representation becomes: [![enter image description here](https://i.stack.imgur.com/NXeI5.png)](https://i.stack.imgur.com/NXeI5.png) This is `code-golf` so the shortest code in bytes wins. --- ## References: * <https://www.hackerearth.com/practice/data-structures/advanced-data-structures/segment-trees/practice-problems/algorithm/comrades-iii/> * <https://www.hackerearth.com/practice/data-structures/advanced-data-structures/fenwick-binary-indexed-trees/practice-problems/algorithm/spartans-leonidas-vs-xerxes-monk/> [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` Ḥ,‘$€F>ÐḟðƬF⁴R¤ḟ ``` [Try it online!](https://tio.run/##ATEAzv9qZWxsef//4bikLOKAmCTigqxGPsOQ4bifw7DGrEbigbRSwqThuJ////9bMiw3Xf83 "Jelly – Try It Online") ``` Ḥ,‘$€F>ÐḟðƬF⁴R¤ḟ Main Link ðƬ While the results don't reach a fixed point Ḥ Double each value (killed soldier) , $ Pair with € each value ‘ itself incremented F Flatten the result Ðḟ Filter out (remove) elements that are > Greater than the right argument (the number of soldiers) F Flatten the accumulated list of killed soldiers ḟ Filter; remove the killed soldiers from ⁴R¤ [1, 2, ..., N], the list of all soldiers ``` [Answer] # [Python](https://www.python.org), ~~125~~ ~~124~~ 119 bytes *-1 byte thanks to @The Thonnu* ``` def f(n,k,A):*B,=range(n+1);g=lambda d:d<len(B)and g(2*d+1)|g(2*d)|B.pop(d);[g(B.index(x))for x in A];print(B[1:]or[0]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY5BDoIwEEWv0uUMViJsMCALeo2GRc20SNRp02DEhJu4YaMrL-RtNBp2P-8t3r8_w204eJ7nx2Vw6-37StYJByyPssEyUbKOhjsLvMqw6uqTOe_JCCppd7IMCg2T6CBP6Oun38BJpcEHIKx0ByrtmewII6LzUYyiZ9G0VYg9D6B0VrY-6k2L__zLQSFzqXNZLGh59gE) Uses the array representation of a binary tree, then recursively removes the given element and the associated children of that element for each item in `A`. [Answer] # [Scala](https://scala-lang.org/), 211 bytes Modified from [@97.100.97.109's answer](https://codegolf.stackexchange.com/a/259863/110802) Golfed version, [Try it online!](https://tio.run/##RY9Na8MwDIbv@RU6SlswbS@FZC7Et8E@DmOn0oMXf9Sb5xTHjIyQ357ZHWM6SOIR78ursZdersPbu@4TPEoXYF6VNmAwNPch1R/X3jUPbkzHvJ6Iz18ygvgnHDeQBgjE0lBgW/QWVVFS8xpc4rMzgOpOMK@DTWeaLe5u1O2W2utCreCCXWTqz6jqJ@frfFmWtmNmiFpmOvFDthTMBaWnZ4MTEbWX6ELyAZ3BP@fDlgRL0nnQftRQ4uCGaFkBSqrP/CDKaMcGuhjl9/ElZQ97ogZKTuAwV5DL4L6GXf2rz3NPlPlSLdX6Aw) ``` def f(n:Int,k:Int,A:List[Int])={var B:List[Int]=(0 to n).toList;def g(d:Int):Unit={if (d<B.length){g(2*d+1);g(2*d);B=B.patch(d,Nil,1);}};A.foreach(x=> g(B.indexOf(x)));println(if(B.length>1)B.tail else List(0))} ``` Ungolfed verison: ``` object Main { def f(n: Int, k: Int, A: List[Int]): Unit = { var B: List[Int] = (0 to n).toList def g(d: Int): Unit = { if (d < B.length) { g(2 * d + 1) g(2 * d) B = B.patch(d, Nil, 1) } } A.foreach(x => g(B.indexOf(x))) println(if (B.length > 1) B.tail else List(0)) } def main(args: Array[String]): Unit = { f(7, 2, List(2, 7)) } } ``` ]
[Question] [ **This question already has answers here**: [Golf a mutual quine](/questions/2582/golf-a-mutual-quine) (17 answers) Closed 4 years ago. # Challenge Create 2 programs A and B * The output of program A is exactly program B * The output of program B is exactly program A * Neither program should depend on inputs to yield the correct output * A and B are not identical programs * A and B are of different programming languages * Neither program may be equivalent to itself in the other language. For example, if the chosen languages are C and C++, the C++ program must not be a valid and equivalent C program, else the "inter-language" requirement is redundant A solution should include: * The program source, as well as a [Try it online (tio.run)](https://tio.run/#) link for both programs # Scoring The score for a solution is: * The length of the shortest program + * The combined length of the names of both programming languages, as they appear on tio.run The reason for this unusual scoring is because this constitutes the combined length of the minimum information necessary to communicate your solution. --- This is my first post to Code Golf. Any edits to this post to increase clarity or appropriate vocabulary are welcome. [Answer] # [><>](https://esolangs.org/wiki/Fish) and [Gol><>](https://github.com/Sp3000/Golfish), 18 bytes + 3 + 6 = 27 ``` '3d*:5-0@o~r{?H>o< ``` [Try it online!](https://tio.run/##S8sszvj/X904RcvKVNfAIb@uqNrewy7f5v9/AA "><> – Try It Online") and ``` "3d*:5-0@o~r{?H>o< ``` [Try it online!](https://tio.run/##S8/PScsszvj/X8k4RcvKVNfAIb@uqNrewy7f5v9/AA "Gol><> – Try It Online") Both output the same program, but with the first character flipped between `'` and `"`. Neither program is equivalent to itself in the other language, since the behaviour of `@` differs. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes + 8 = score 21 ``` “Ṿ;⁾v`+/ŒṘ”v` ``` [Try it online!](https://tio.run/##ASEA3v9qZWxsef//4oCc4bm@O@KBvnZgKy/FkuG5mOKAnXZg//8 "Jelly – Try It Online") # [RAD](https://bitbucket.org/zacharyjtaylor/rad) ``` '“Ṿ;⁾v`+/ŒṘ”v`' ``` [Try it online!](https://tio.run/##ASEA3v9yYWT//yfigJzhub474oG@dmArL8WS4bmY4oCddmAn//8 "RAD – Try It Online") A Jelly quine that wraps itself in single quotes, such that the resultant RAD program simply prints the original Jelly program back out. Thanks to @JoKing for golfing the language name for the second program! ]
[Question] [ Let me know if this task has already been posed. I haven't found it when I looked. --- ### Input * ***master sequence \$\ X = x\_1\dots x\_n\$***: sequence of characters, eg. \$\rm international\$ * ***subsequence \$\ Y = y\_1\dots y\_m\$***: sequence of characters, eg. \$\rm intl\$ ### Output Number of possible mappings \$\mu: [1\dots m] \rightarrow [1\dots n]\$ of positions in subsequence to positions in the master sequence, such that for all \$j\in[1\ldots m]\$: 1. \$y\_j = x\_{\mu(j)}\$, viz. an occurrence of a character in the subsequence maps to an occurrence of the same character in the master sequence 2. \$\forall\ i \lt j:\ \mu(i) \lt \mu(j)\$, viz. the mapping preserves mutual position of character occurrences. In the example above, there are 3 possible mappings: * \$\rm\underline{int}ernationa\underline{l}\$ * \$\rm\underline{in}terna\underline{t}iona\underline{l}\$ * \$\rm\underline{i}nter\underline{n}a\underline{t}iona\underline{l}\$ ### Rules Lowest average asymptotic time complexity with respect to \$n+m\$ wins. If it helps you, you can assume the input is a sequence of bytes (values 0-255). ### Test cases ``` master sequence, subsequence -> number of possible mappings international, intl -> 3 aaabbb, ab -> 9 aaabbb, aabb -> 9 only one, onl -> 1 none, en -> 0 ``` [Answer] # [Ruby](https://www.ruby-lang.org/), \$\mathcal{O}(nm)\$ I think I got the analysis for this right. Should be \$\mathcal{O}(nm)\$ because for each of the \$n\$ characters in the master sequence, it goes through at most \$m\$ steps to check each character of the subsequence (if they are all the same character). It's also optimized to try to be \$\Omega(n+m)\$ best case complexity, which occurs if all the characters in the subsequence are unique. ``` def submap master, sub subIndex = Hash.new{ |hash, key| hash[key] = [] } sub.chars.map.with_index do |c, i| subIndex[c] << i end subCount = [0] * sub.length master.chars do |c| indices = subIndex[c] indices.reverse_each do |i| subCount[i] += i > 0 ? subCount[i-1] : 1 end end return subCount[-1] end ``` [Try it online!](https://tio.run/##dZHPToQwEIfvPMWE066yBK5mVw9e9BlIY1qo0iw73dASJOKz4/QPWSXx0gz9fvN1JvSDmJalke9gBnHhV7hwY2Wfuc8E3PmKjfyEE7xw0@Yoxy@YWyozOMtpBldWVDFKVAy@k9CU1y3vTU7CfFS2fVNe0miY6wzUTKGbu6oZHI@g6FJiEwXPekDrnAWDO2/sJH7Y1uEwYngiOIOQHlG1NNT1S@3JLqIoOZT7vNEjWr0r9t4QR/IOv21sqBSLYJ2p8gkG96eYfYQCnjb4UDJ4gNK3up3Ws5d26PEWplxCZLkO1qw/IFVI2yG3SiPv0sxfdGnyJ8M5F0I4yMX/iIoN1NhNoFE6TPWGYiQS0@UH "Ruby – Try It Online") ## Explanation Define the function \$f(X\_i,Y\_j)\$ as the number of occurrences of the subsequence \$Y\_j=y\_1...y\_j\$ in the sequence \$X\_i=x\_1...x\_i\$. In this situation, it can be shown that $$f(X\_i,Y\_j)=\begin{cases} f(X\_{i-1},Y\_j) & \text{if } x\_i\ne y\_j,i > 1\\ 0 & \text{if } x\_i\ne y\_j, i=1\\ f(X\_{i-1},Y\_j)+f(X\_{i-1},Y\_{j-1}) & \text{if } x\_i=y\_j,j > 1\\ \sum\_{k=1}^i [x\_k = y\_j] & \text{if }j=1 \end{cases}$$ That is, if the subsequence is 1 character long, count how many there are in the master sequence. If \$x\_i=y\_j\$, add the number of times the subsequence \$Y\_{j-1}\$ occurred previously in \$X\_{i-1}\$, as that is the number of times you can find this subsequence using this specific position \$x\_i\$. Otherwise, ignore the character and only look at the sequence before \$x\_i\$, that is, \$X\_{i-1}\$. With that, we write our code. ``` def submap master, sub # Minor optimization: Map the characters to indices. This way, we don't have # to go through the subsequence every time, which gives the best case scenario # a complexity of O(n+m) if all characters in Y are unique. subIndex = Hash.new{ |hash, key| hash[key] = [] } # Initialize hash with default value [] sub.chars.map.with_index do |c, i| # For each character in Y subIndex[c] << i # Add the index to the hash for that char. end subCount = [0] * sub.length # Initialize the previous results f(X, Y_j). master.chars do |c| # For each character in X indices = subIndex[c] # Look up the indices for that character indices.reverse_each do |i| # For each index (in reverse order) subCount[i] += i > 0 ? subCount[i-1] : 1 # Increment f(X, Y_j) by f(X, Y_{j-1}). end end return subCount[-1] # Return f(X, Y_m). end ``` [Answer] # [Python 3](https://docs.python.org/3/), \$O(n^m)\$ ``` def submappings(master, sub): if len(sub) == 0: return 1 count = 0 for i, c in enumerate(master[:len(master)-len(sub)+1]): if c == sub[0]: count += submappings(master[i+1:], sub[1:]) return count ``` [Try it online!](https://tio.run/##hY4xDoMwDEV3TmFlIoJKRd2QOAlicKhpI4GDQhg4PXVKQR2oOvn7@/nb4xKejm/reqcOptkMOI6WH1M64BTI59HTZQJgO@iJ09hCVcE1egCewuwZCmlaN3MAmYjunAebQwuWgXgeyGOgT2RdxpxN68uemRWN3iLlUBsviFtfm83b07Pq5MfaZkXZvD@tRejkeOu9tI7ecki/95QY5BmDdYy9yiEavdI6OWER0RijcoXmLyH1B@O4X8AxCXXIc5I3iljm6ws "Python 3 – Try It Online") For each character in the subsequence, it looks through (what's left of) the master sequence for it, and moves onto the next one, counting how many combinations there are. I've made a version that also counts the number of comparisons. ``` def submappings(master, sub): if len(sub) == 0: return 1, 0 count, ops = 0, 0 for i, c in enumerate(master[:len(master)-len(sub)+1]): ops += 1 if c == sub[0]: rec = submappings(master[i+1:], sub[1:]) count += rec[0] ops += rec[1] return count, ops ``` [Try it online!](https://tio.run/##hY/NboUgEEb39ykmrCTSRNKdiU9iXIDFlkQHgri4T29nhP4sbLpi5nD4ZojP/BHw9Tzf3AL7YTcTo8f3vdnMnl1SzGT/APALrA4bbmEYoGMGkFw@EoJW0FE/hwOzghB3IKOwJSTwCmbwCA6PzSWTXU0fe44stXz5im/1JEs6B7UD6KuhBWaeTMrYTUXgBQjeLD76VvfTtf5Ihaz6tSFn0jtKqbTOYaaZ1V/9fOeMyWNufo8RBFxCk31AswoFDFYh5ePGNcZYa4USxv5r0PmHE3B9QkBH1nd5b2KxHNL9@Qk "Python 3 – Try It Online") ]
[Question] [ This wasn't originally intended for code-golf, just as a little debugging routine to roughly visualize something "goofy" going on in a model of some (irrelevant here) physical process. But when I saw how surprisingly short it was, compared to my expectations, I just wondered if it can be further shortened. And that's primarily with respect to #statements (rather than #chars just by shortening variable names). So, the function's `void asciigraph ( double *f, int n )` where `f[]` contains `n` doubles representing values of some more-or-less continuous function to be illustrated/graphed on your terminal. My implementation is below, along with a test driver, whose output is below that. Can you do better/shorter?... ``` #include <stdio.h> #include <math.h> /* --- entry point --- */ void asciigraph ( double *f, int n ) { int row=0,nrows=24, col=0,ncols=78; double bigf=0.0; for ( col=0; col<n; col++ ) if ( fabs(f[col]) > bigf ) bigf = fabs(f[col]); for ( row=0; row<nrows; row++ ) { double yval = bigf*((double)(nrows/2-row))/((double)(nrows/2)); for ( col=0; col<ncols; col++ ) printf("%c",(yval*f[(col*(n-1))/(ncols-1)]>=yval*yval? '*':' ')); printf("\n"); } } /* --- end-of-function asciigraph() --- */ #ifdef TESTDRIVE int main ( int argc, char *argv[] ) { double f[999], pi=3.14159; /* stored function to be graphed */ int i=0, N=511; /* f[] index */ void asciigraph(); for ( i=0; i<N; i++ ) { double x = 2.0*pi*((double)i)/((double)(N-1)); f[i] = .5*sin(2.*x+pi/3.) + 1.*sin(1.*x+pi/2.); } asciigraph(f,N); } /* --- end-of-function main() --- */ #endif ``` [Try it online!](https://tio.run/##bVLRjpswEHzPV6xSVTEOMYG76C4lpH@QH6A8EIPJSsRGQNJUVX69dO3jGk5XHrzLeD073rFcVVIOX1DL@lKUsOv6Ao047WcP6Jz3J0KGq8EC8k4iVm3enIBBYS7HugSufEDdgwYPfs/A5fS15mey9jWFLomefZCmtv8UuuTlNabC8fwRK5WsxdpCyrRE7EpjG3baheUSvJklRUXbKj92TKWEZx7s3Xlq7ULyYfPB6MTENuycIpdaVqf4n5Rf17wmDkvFGXsDPeZOBNGKgucFn3DP9fmfdnvXj/oBmpbmo9j8q5z7zPbjKmVUwplehZbenaI02ydu2y7fYcEX3xaweO/1zvJDz70Y7oTdBzv3c46aRNg0bytJUz/lLXDKr2k23na8q0q3223mQ4PJkwifw802tswBh643bVmAumjZo9HQGziW4FwnmAcPj5EchUOyCcMYJh9xKGqHuihvb/Xu8cDk@bCJOWgHhrsDLZ8tuZEfkVjzBh@O4NSFgx3b6ECKGZWLDe9Qs0jw27LB4El4sIRQODAcwUiMc5tIUv7BEd2HP1LVedUNq/r8Fw "C (gcc) – Try It Online") Compile it (for linux) as `cc -DTESTDRIVE asciigraph.c -lm -o asciigraph` and then the sample output is ``` ****** ** ******** **** ********* ***** ********** ****** *********** ******* ************ ******** ************* ********* ************* ********** ************** *********** *************** ************ **************** ************* ****************************************************************************** ********************************************* ******************************************* ***************************************** ********************* ***** ***************** ************ ******** ``` So, the eleven lines comprising asciigraph() above can be reduced two ways: **(a)** just "syntactically compressing" the code (e.g., put the final `}` on the same line as the final statement), or **(b)** by finding a niftier algorithm than mine, which compares each f-value to the yval "level line" (in which case maybe your algorithm wouldn't need to find that bigf at all). Obviously (I'd think it's obvious), the "niftier algorithm" approach is what I'm more interested in. Replacing the test driver with the following will yield a moving wave: ``` int main ( int argc, char *argv[] ) { double f[999], pi=3.14159; /* stored function to be graphed */ double t=0.0, dt=0.05, w1=16.,w2=3.; int Nt=50; int i=0, N=511; /* f[] index */ void asciigraph(); while ( --Nt > 0 ) { for ( i=0; i<N; i++ ) { double x = 2.0*pi*((double)i)/((double)(N-1)); f[i] = .75*sin(2.*x+pi/3.+w1*t) + 1.*sin(1.*x+pi/2.+w2*t); } system("sleep 0.25; clear"); asciigraph(f,N); t += dt; } } /* --- end-of-function main() --- */ ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~164 167~~ 162 bytes ``` r,c;void asciigraph(f,n,b,y)double*f,b,y;{for(b=0,r=n;r--;)b=fmax(b,fabs(f[r]));for(;++r<24;puts(""))for(y=b-b/12*r,c=0;c<78;)putchar("* "[y*f[c++*~-n/77]<y*y]);} ``` [Try it online!](https://tio.run/##VVHbbqswEHzPV6zSF9vcAm2URoZ@Qn4A8WAbnKyUGGRIFVSln166kJ6ec/bBWo/GszNrEx2NmZ7QmfO1biDvhxrb@PS2@gtd1HAiZPKhke8t1qB6g3j0qjsxG7pQhyOv26s@N8LOF/lhW890sQl94aSPIsl1YS/qxnRole6ZLX3FuZxZMgh8nr3I7jr0bL3mfAbHQkc6STNBE4uNNPnuVXJimJPybC1gXY7CliYIxGfkkt2uykcxVlzeJ3QDXBQ6YDC3yh9NCPMzENS/lxVw@FgBPOyCLff7fRVCh8VznL6k270EqkRAP7S@qcFenRmwdTC0oBtYMhMsEtKYB1Ah5YRDsU3T5e2fIg1L49DVze3BX1YH/y6PS4Ip8OyWcgLmBzqC4Mfkr80bFJDFG9GhYOyBceTJb88OUcoXMZIrsSJ6vBU9OpbF4hZ0mDzHHAJI4wVMf8As5hLuK/j/Pw@L0H36Mvasjv0UnS/f "C (gcc) – Try It Online") Thanks to @Arnauld for -4 and @JohnForkosh for the bugfix. Slightly golfed less ``` r,c; void asciigraph(f,n,b,y)double*f,b,y;{ for(b=0,r=n;r--;) b=fmax(b,fabs(f[r])); for(;++r<24;puts("")) for(y=b-b/12*r,c=0;c<78;) putchar("* "[y*f[c++*~-n/77]<y*y]); } ``` ]
[Question] [ Make a quine. Simple enough, except it has to be a palindrome and accept input. Now, any side of a palindromic quine is one half of it. For example, one side of the hypothetical quine AAAA is AA. One side of AAAAA is AA (the center symbol is ignored). Your job is to make a quine like this that accepts input. If the input is the whole quine, then the quine prints the left side of itself. If the input is either side of the quine then the quine prints itself. Of course, with quines with an odd number of symbols the center symbol is ignored. If the input is anything other than the cases specified, the program must do nothing. This is code golf, so the shortest submission wins. [Answer] # [Haskell](https://www.haskell.org/), ~~350~~ ~~346~~ 342 bytes ``` main=interact f;f s|s==l++r=l|s/=l,s/=r=[]|1<3=l++r;r=reverse l;l=q++shows q['-'];q="main=interact f;f s|s==l++r=l|s/=l,s/=r=[]|1<3=l++r;r=reverse l;l=q++shows q['-'];q="--"=q;]'-'[q swohs++q=l;l esrever=r;r++l=3<1|][=r=/s,l=/s|l=r++l==s|s f;f tcaretni=niam"=q;]'-'[q swohs++q=l;l esrever=r;r++l=3<1|][=r=/s,l=/s|l=r++l==s|s f;f tcaretni=niam ``` * Prints its left half with itself as input: <https://tio.run/##7ZAxCoUwEESvEmwsoohYxjlJSBEkYvhrJNnwbXJ3f8gd7H4zsMPsY5jD8scRPc9pfYAP2SW7ZbGrXXBhgKRMoMITaKiSoE2Z16X5KiG5r0vsBClClJKP62YRdT/2RkV0r0DHsUNUpp46Cr6vg6WMqGHhuL2iQqQkLOtcjK74iQeqUgjNRy3RyuTNJpeDR/D2fAX63/WdXX8> * Prints itself with its left half as input: [Try it online!](https://tio.run/##1ZAxCoUwEESvEmwsoohYxjlJSBEkYvhrJNnwbXJ3f8gdLH4zMMPuY5jD8scRPc9pfYAP2SW7ZbGrXXBhgKRMoMITaKiSoE2Z16XlKiG5r0vsBClClJKP62YRdT/2RkV0r0DHsUNUplodBd/XwVJG1GPhuL2iQqQkLOtcjK74iQeqUggtRy3RyuTNJpeDR/D2fAX6V7v@AA "Haskell – Try It Online") * Prints itself with its right half as input: [Try it online!](https://tio.run/##1Y4xCoQwEEWvEmwsoohYxn@SkCJIxLBjJBlZm9w9G3IHi20@zOfP4x2WP46olNP6AB9ul@x2i13tgjMDJGUCZZ5AQ40EbfK8Lq1XCcl9XWInSBGilHxcD4uo@7E3KqJ7BTqOHaIy9dRR8HMdLGVEHQvH7RUVIiVhWedsdMVPPFCNTGg9qkSTuTeb3B08grfnK9BS/kj2Bw "Haskell – Try It Online") * Prints nothing with anything else as input: [Try it online!](https://tio.run/##tY5BCsQgFEOvIt3MwpZSurT/JOJCyu8o82vRL1MGvLsj3qGbQELyiLP8QaJaT@sD@JAx2T2LQx2CCwOQlAmo8Aw0NkmgTVm2tecqQcIvJkZBiiBKye66WUT9ml5GRRgegU7TAFGZZnUUfF@OpYzQygK5T6FBpCRYt6UY3fAzj9SkEPQc2ol@Ju82YQ4egrfnI9Babfhl58NbIDH@AQ "Haskell – Try It Online") *Edit: -8 bytes thanks to [Ørjan Johansen](https://codegolf.stackexchange.com/users/66041/%c3%98rjan-johansen)! Also changed to a version which does not need `(<>)`.* [Answer] # Javascript, ~~224~~ 200 bytes Prompts for input. I shaved off some bytes by using ES6 features. Still can probably be golfed a lot more. ``` (f=_=>{a=prompt();s=`(f=${f})()/`;r=[...s].reverse().join('');return a==s||a==r?s+r:a==s+r?s:""})()//)()}"":s?r+s==a:r+s?r==a||s==a nruter;)''(nioj.)(esrever.]s...[=r;`/)()}f{$=f(`=s;)(tpmorp=a{>=_=f( ``` ]
[Question] [ This is similar to the alignment used in word. ### Task 3 inputs: A 1 line string, a positive integer `k`, and direction (left or middle or right) Your job is to insert new lines(`\n`) and spaces in the string such that every line has `k` characters in it and aligned to the direction given. ### Rules The words must not be split(unless their length is greater than `k`) Direction can be taken as any 3 unique characters(must be mentioned). Any format and order of input is valid(must be mentioned). Input will only have alphabetical characters of any case(and spaces). There will not be any trailing or leading spaces in the input and will have only 1 space between words. Output can be either a string on one line as is in examples or multiple lines. **If the direction is left:** There should not be any spaces in left of the line and only 1 space between words. **If the direction is right:** There cannot be any spaces to the right of the line and only 1 space between words. **If the direction is middle:** There cannot be any spaces to the left or right of a line and an equal number of spaces between words on one line. In case the word length is shorter than `k` and only 1 word can fit in 1 line, then spaces on the right is allowed. If more than 2 words can fit in one line but they cannot be divided keeping number of spaces equal, words will shift to next line to keep number of spaces equal. ### Test Cases ``` input: 'Hello World',6,right output: ' Hello\n World' input: 'Hello World',7,left output: 'Hello \nWorld ' input: 'Hello World',7,middle output: 'Hello \nWorld ' input: 'This is a test case',5,middle output: 'This \nis a\ntest \ncase ' input: 'This is a test case',5,left output: 'This \nis a \ntest \ncase ' input: 'For example',1,left output: 'F\no\nr\ne\nx\na\nm\np\nl\ne' #The space is removed as the next word is in a newline. input: 'Hello Worlds How are you',5,left output: 'Hello\nWorld\ns How\nare \nyou ' input: 'qwert asdfghjkl zxcvbnm',7,middle output: 'qwert \nasdfghj\nkl \nzxcvbnm' input: 'ab abcdefg',6,middle output: 'ab \nabcdef\ng ' input: 'This is code golf so shortest code wins',10,middle output: 'This is\ncode golf\nso \nshortest \ncode wins' input: 'Credit to Jo for this case',13,middle output: 'Credit to\nJo for this\ncase ' ``` **This is code-golf so shortest code wins** [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~195 186 177~~ 132 bytes *-41 bytes thanks to nwellnhof!* ``` {->\b,\c{$!={!c*(b-$0.comb)/($0-1||1)+1};S:g{[(\S+)[\s|$]<?{b>=$0.ords&&.$!%%1}>]+|(\S**{b})}=$0.join(' 'x.$!).fmt("%{b*c||-b}s ")}} ``` [Try it online!](https://tio.run/##jY/BTsJAEIbvPMVACu0WWtsYMRHBg4khXjHxQDnsbrdQbBncrQK2@@x1qyYSDcbsnPb/ZuabrZDZsM4P0EtgDHXpTSI2iHhptcdlm7sO86zA55gzcuZYgRdWVUj6oR7Nrpbl3IlmfTKPVGUtrm9KNhkbFmWsej3fane7oZ4s@pWBXLdkmugmXmO6cWyw94YgfpIXTqdbMpdXlce0anWI1vWopegBEseeiixDeESZxTZxhoOQnIguB94fWfAdPaxSBaYoFEIVwKkSBrn4D3K84Q4liD3Nt1mThae2K5jiDqgUcMCXX0Oed0IWQFWcLFfrpwze9vyVbfJTyhxjAUvMElAIaoXyU6/53aUb1XgEx323UsRpAQXCPUJihItm0Nc54fkxSoGa@vk@RIxv/Q4 "Perl 6 – Try It Online") Anonymous code block that takes input curried, e.g. `f('text')(length, direction)`. Uses the values `-1,0,1` as left, middle and right respectively. [Answer] # [Python 2](https://docs.python.org/2/), ~~245~~ ~~243~~ ~~237~~ ~~225~~ 221 bytes ``` import re s,k,d=input() s=filter(bool,re.split('(\w{%d})| '%k,s)) while s:l,s=max((j,s[i:])for i in range(len(s)+1)for x in range(d&1or k)for j in[(-~x*' ').join(s[:i])]if[k,0][d|(i<2)]<=len(j)<=k);print'%*s'%(-(d|1)*k,l) ``` [Try it online!](https://tio.run/##hZJBj9MwEIXv/hWjSsV2cFdNV4BUmtMCWnHhgsQh5JDGk8SJEwfbS7JQ@OvFSVcssAcknz7PjN974@He16bfnTWWXkCnpNQowKqq9pBALLZiExNy8@HNW0hWq9VZdYOxHiwSJ1ohE9UPd55x4pJSaY@WHY3RwuKVG7TyjLLP4/e1/MFPQNetcJyTsVYawe21cEmXT4w1wqVqn/HSWFCgerB5XyHT2DPHn8cLnx65fBYH0C64CThlm59TRIHyq8ao0JPuVcYzVaat2GapPDF12PHskMwDG35IWv56sKr3dB05umYbJk8xj1qh@XnhQDc02m1JsEsITljAYj@COD7TW9TawCdjtaTipViCIn/TV2IO8wm8ZEvox1o5CCcHj85DkTuk4sX/ri8j3wXPOOXdoAOMn77j4NaMkFuEe3P32PZlxLCz3MmyqptWw7ep@Hrsuz9V5UfIj4XEsppt/SumMBKhMroEZ8DV4Qcs2mY6qt4FLdvfPTcWpfLgDbw3MC/Jz0MuPuLrh7Jf "Python 2 – Try It Online") Takes `left, middle, right` as `1,0,-1` ]
[Question] [ **This question already has answers here**: [Modular multiplicative inverse](/questions/140357/modular-multiplicative-inverse) (25 answers) Closed 6 years ago. In this thread we use 32-bit signed integers (assuming the usual [two's complement](https://en.wikipedia.org/wiki/Two%27s_complement)). For simplicity I shall call this type Int32. The range is from `-2147483648` through `2147483647`. Any two values can be successfully multiplied (the result is an Int32 as well) since we use multiplication without overflow checking (we only keep the 32 least significant bits of the product). For example, we have: ``` 2147483647 * 2 == -2 ``` and so on. If your language does not have native support for 32-bit signed integers (with two's complement), you must emulate it. Your task is to solve the equation: ``` a * x == b ``` where `a` and `b` are given as input, and it is assumed that `a` is an odd number (i.e. least significant bit is `1`). You output an Int32 value. * The input to your program shall be two Int32 values `a` and `b`, and `a` will be odd * The output must be one Int32 value such that (if we call the output `x`) `a*x == b` * You do not have to handle invalid input; in particular, if the argument `a` is an even number, it does not matter what your code does * Code golf **Test cases:** ``` Input Output 1,42 42 3,126 42 5,5 1 -3,126 -42 3,-126 -42 -3,-126 42 2147483647,-2 2 2147483647,2 -2 2147483647,666 -666 3,0 0 3,1 -1431655765 3,2 1431655766 -387907419,1342899768 1641848792 348444091,1076207126 -1334551070 10,14 irrelevant (illegal input) ``` In the last case `[a,b]==[10,14]`, even if there is a solution `x = -1717986917` (not unique, `x = 429496731` also works), you do not have to handle that case (`10` is not odd). [Answer] # [Python 3](https://docs.python.org/3/), 39 bytes ``` lambda a,b,h=2**31:(a**~-h*b+h)%(2*h)-h ``` This is a theoretical solution that will take a *long* time unless **a = 1**. It uses the Euler-Fermat theorem to determine the modular inverse of **a**. ### Alternate version, 47 bytes ``` lambda a,b,h=2**31:(pow(a,h-1,2*h)*b+h)%(2*h)-h ``` This does exactly the same, but in a more efficient manner. [Try it online!](https://tio.run/##XY/NasMwEITP7VPspURyV0UrbfRjSJ@kF4liFEhsEwwhlDy7a8WmhVx2vp2BXWa8TWXo7dzBAb7mUzrn7wQJM5aDaRpLrRiHq0hYFKFpimzye5FvoqIqczdcYAmzhGMPgpCNRBAWybgKe9xXUX@GRbWR@kdD7DlYxx6VeTKed@e2O3p7tIpZTwYftWeKSJZNiNG78Mg5MLOOhKS9M9rXx@3ry3g59pPY/bSk77BO9VmB7ruPpdo5TUs5yAjdQ6WU8y8 "Python 3 – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 44 bytes ``` a->b->{for(int i=0;;i++)if(a*i==b)return i;} ``` [Try it online!](https://tio.run/##nZIxb4MwEIX3/IobcVNbYFwbRGGs1KFTxqqDIRCZEIPARIoifjt1Jeo1EOmGJ933fE93ruVV4rYrdX08z0UjhwG@pNL3HcBgpFEF1JYgo1ENqUZdGNVq8rGI909tylPZv66DFpFlUEAKs8RZjrN71fae0gZU6ieJ2u@Rqjz5otI0R31pxl6DSqY5sYFsdWPe2ExLtGurjnCxcb2D6ZU@ff@ARH/RAQ63wZQX0o6GdLZlGu0VRHZdc/MCtAhGEUoe0eE/HVC@An9DTjyG8cbHHY7X8XirgQZMsCjkTDgjfcr2nIvzTVvwN51vC0xXLTcSsS9YELsRIaNRHAserZnFIsaYH7vfGPiCU1@4Q027af4F "Java (OpenJDK 8) – Try It Online") -12 bytes by using a currying lambda thanks to Kevin Cruijssen [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 36 bytes ``` Mod[#2PowerMod[#,-1,m=2^32],m,-m/2]& ``` [Try it online!](https://tio.run/##XY1PC4JAEMXvfoolwUPM0s7stH8Ogl8g6B4GUkoeNkGEDuJntzWloNP7zXvDe6EaHnWohvZWzU0@n7r7JaVz96r7D4JECDldNZUQQIYDldl87tvnEDOxE3uxA9EsnMaPaOSLEVlkoigKMSYjAtMEyagBySxwhOMi8mvouLKS/CEhW3basAVJf8b/bczWo7ahVWitdNYry@gBNZPz3hr3ydkxs/IIqKwhZbdhVIA8JdP8Bg "Wolfram Language (Mathematica) – Try It Online") ]
[Question] [ **This question already has answers here**: [Fluctuating ranges](/questions/74855/fluctuating-ranges) (20 answers) Closed 6 years ago. Take an input list **L** containing positive integers, and insert the least amount of integers into the sequence, so that you make it a continuous one. ### Example: ``` L = 4 2 6 1 Out: 4 3 2 3 4 5 6 5 4 3 2 1 ``` The input and output formats are optional. ### Test cases: ``` L = 1 Out: 1 L = 10 4 Out: 10 9 8 7 6 5 4 L = 13 13 Out: 13 13 L = 3 6 Out: 3 4 5 6 L = 4 4 1 1 4 4 Out: 4 4 3 2 1 1 2 3 4 4 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")... You know the rules. [Answer] # Builtin ### Husk: ``` … ``` [Try it online!](https://tio.run/##yygtzv7//1HDsv///0eb6BjpmOkYxgIA "Husk – Try It Online") I bet this builtin exists in more than one language, so I made this a community wiki, just add in more languages where this is a builtin if you know them! [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes ``` ⊆.s₂ᵇ-ᵐ~ṡᵐ∧ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FXm17xo6amh1vbdR9unVD3cOdCIPWoY/n//9EmOiY6hkAIpGP/RwEA "Brachylog – Try It Online") It's long and slow but at least it's declarative… ### Explanation ``` ⊆. ∧ The Input is an ordered subset of the Output s₂ᵇ Take all substring of 2 consecutive elements in the Output -ᵐ Take the subtractions of all those substrings ~ṡᵐ They must all be valid "ṡigns" (i.e 1, 0 or -1) ``` [Answer] # Mathematica, 72 bytes Another approach using `ReplaceAll`. ``` #//.{(p={a___,b_,c_,d___})/;b>c+1->(f={a,b,b-#,c,d}&)@1,p/;b<c-1->f@-1}& ``` ]
[Question] [ *This is the robbers' post. The cops' is [here](https://codegolf.stackexchange.com/q/140863/58826).* Your challenge is to take a cop's post and find an input that the regex matches but the program returns a falsey value. Once you have cracked a cop's post, comment in a link to your crack. (If you don't have enough rep to comment, please say so, and someone will do it for you.) The robber with the most cracks wins. ## Example Let's say a cop's regex is (all of the flavors): ``` /^[0-9]$/ ``` And the program is (JS): ``` x=>Boolean(parseInt(x)) ``` Than a valid crack would be `0`, because the regex matches `0` but `0` is falsey. [Answer] # [Python 3, pperry](https://codegolf.stackexchange.com/a/140865/70424) ``` İ ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P03BViEnMTcpJVEh0SonNU8jUS8nvzy1SENTU8HWVsGQq6AoM69EI01D6cgGJU3N//8B) The lower case variant `i̇` of this character is created by a an `i` and a ċȯṁḃi̇̇ṅi̇̇ṅġ ḋȯṫ which results in a length of 2. [Answer] # [Python](https://docs.python.org/2/), [ppperry](https://codegolf.stackexchange.com/a/140870/73819) ``` \n ``` [Try it online!](https://tio.run/##LYoxDoAgDAB3X1EnIDEMfsAf@AITQwwGBlpSuvD6GpXtcne1SyJcVW@mAlQjByGGXCqxAJKcOpjjAq23qXLGv1hzoHFDcPQlyJUsG7vN3pkFvgy5vTPshFH1AQ "Python 2 – Try It Online") `.` doesn't match newline by default. [Answer] # [JavaScript, ThePirateBay](https://codegolf.stackexchange.com/a/140895/73026) Solution: `😩` [Try it online!](https://jsfiddle.net/36x66tck/) [Answer] # Java, [Roman Gräf](https://codegolf.stackexchange.com/questions/140863/the-greedy-regex-cops#140912) ``` is.is.is.is. ``` [Try it online!](https://tio.run/##dVHBTsMwDD23X2FVHNJNy4kLmxAHxA0QYojLNqSs80pGmlSJOzamfvto2jAYMCmSFfu952d7JdZiYErUq8XbxV4WpbEEqybJK5KK90bxz5wSOucWlwoz8rW4rOZKZpAp4RzcCalhF0ch6UhQE9ZGLqBoSmxMVup8MgNhc5d6ZDTOhNZowYV4CRrfIWTZeOsICy51OvLYlg5kntBRgwwcrnFDt1Ij61Adx1TEywZPSrPkwZrcimIICfRBuvB9FkouWCeXnuQ@Yo6bIUDgtt8/zDr@PfXcGIVCHzPCBDr1o1ukymrQvBCUvaJj1gM7tWh/Uu7I/EGwXSbZrQ/Rtb8GXxp7Lwpk3fJqyHwbdrPJsCRpNGDr4svGUiiHLfDbGtkK/x0utG0NN4dIXtiVdCmbiMHHrD@d8nR3XvPeWTLaR3G9l44f3ic "Java (OpenJDK 9) – Try It Online") Most things which match the regex crack it, so I'm not sure if the regex is what was intended ]
[Question] [ The Straddling Checkerboard is a method for converting letters to numbers and was part of a pencil an paper cipher known as [VIC](https://en.wikipedia.org/wiki/VIC_cipher#Straddling_checkerboard) To convert letters to numbers first you have to make a checkboard like this: ``` 0 1 2 3 4 5 6 7 8 9 --------------------------------------- E T A O N R I S 2 | B C D F G H J K L M 6 | P Q # U V W X Y Z . ``` Is a 10 x 3 table filled with 28 different simbols and two blanks on the first row. The labels of second and third row are the position of the blanks on the first one. To cipher a message you have to replace each letter with the column label. If it is not on the first row, prepend row label: ``` G -> 24 O -> 4 L -> 28 F -> 23 ``` The extra simbols `#` and `.` are used to escape numbers and to indicate full-stop. # Task ## Input: * 0 to 26 unsorted unique letters (key) * 4 digits, #1 != #2 and #3 != #4 * Alphanumeric message to be encoded ## Output: * Digits representing the encoded message ## Implementation: The table will be filled with the 26 character recived by input. If lengh is less than 26, the remaining spaces will be filled with the missing letters in alphabetical order. The first two integers represent the blank spaces on the first row (and labels for second and third row).Next two integers represent the position of `#` and `.` on the third row. > > ### Example: > > > **Input:** codeglf , 4 6 8 9 , "programming puzzles are gr8." > > > Yields this table: > > > > ``` > 0 1 2 3 4 5 6 7 8 9 > ------------------- > c o d e g l f a > 4| b h i j k m n p q r > 6| s t u v w x y z # . > > ``` > > **Output:** 47491549945454246547727777637094935496886869 > > > **Note1:** Spaces are not encoded and not included in the output. **Note2:** Original message may contain letters, numbers, spaces and . (assume same capitalisation as the key) **Note3:** If there is a number in the original message you have to output the corresponding code number for `#` followed by the number then another `#` code (68 in the example) and then continue with the letters. > > ### Example2: > > > **Input:** toearly , 2 8 6 1 , "wake up at 06.am" > > > > ``` > 0 1 2 3 4 5 6 7 8 9 > ------------------- > t o e a r l y b > 2| c d f g h i j k m n > 8| p . q s u v # w x z > > w a k e u p a t # 0 6 # . a m > 87 4 27 3 84 80 4 0 86 0 6 86 81 4 28 > > ``` > > **Output:** 87427384804086068681428 > > > [This](https://codegolf.stackexchange.com/questions/89062/write-a-vic-cipher-encoder) is the complete VIC cipher question. [Answer] ## JavaScript (ES6), 236 bytes ``` (k,s,t,h,d,m)=>m.replace(/./g,c=>1/c?c>' '?''+t+h+c:'':(c=a.indexOf(c))>9?''+(c>19?t:s)+c%10:c,l=[...'zyxwvutsrqponmlkjihgfedcba'].filter(c=>k.search(c)<0),i=0,a=[...Array(30)].map((_,n)=>n-s&&n-t&&n-h-20?n-d-20?k[i++]||l.pop():'.':'')) ``` Creates the checkboard `a` (except for the `#`, which is special-cased), then replaces letters and `.` in the message with the appropriately translated index while digits are prefixed with the code for `#`. [Answer] # PHP>=7.1, 226 Bytes ``` for([,$c,$a,$b,$d,$e,$t]=$argv,$c.=join(preg_grep("#[^$c]#",range(a,z)));$p<30;)$x[in_array($y=["",$a,$b][$p/10].$p++%10,[$a,$b,$b.$d,$b.$e])?"__#."[$m++]:$c[$i++]]=$y;for(;a&$w=$t[$k++];)echo is_numeric($w)?$x["#"].$w:$x[$w]; ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/e73dec2c734a998b4c5003a720d49c754a3c4bb7) Expanded ``` for([,$c,$a,$b,$d,$e,$t]=$argv #short variables in input array ,$c.=join(preg_grep("#[^$c]#",range(a,z))) # join the rest of alphabet ;$p<30;) # loop 30 times $x[in_array($y=["",$a,$b][$p/10].$p++%10 # is actual position reserved? ,[$a,$b,$b.$d,$b.$e]) # reserved positions ?"__#."[$m++] # set reserved positions with chars underscore instead spaces to avoid encoding :$c[$i++]] # set alpabetic characters =$y; # make encoding array for(;a&$w=$t[$k++];) # loop through string which shall be encoded echo is_numeric($w) ?$x["#"].$w # printing for digits :$x[$w]; #printing for the other characters ``` [Answer] # [R](https://www.r-project.org/), ~~286 281~~ 261 bytes Bit horrible looking and I am sure there is room for improvement, but I wanted to make sure I was doing it correctly before really getting into it. Have changed it a bit to use 2 arrays and handle the numbers differently. Hopefully this makes it easier to golf. Implemented as an unnamed function that take 4 parameters - `k` the key for the table - `x` a vector containing the row name integers - `y` a vector containing the "#",'.' locations - `s` the string to encode ``` function(k,x,y,s){W=which S=strsplit P=paste0 L=letters m=rep(NA,40) m[c(1:10,x+11,y+31)]=c(0:9,'','','#','.') m[is.na(m)]=c(d<-el(S(k,'')),L[-W(L%in%d)]) i=t(outer(c(P(x[2],y[1]),'',x),0:9,P));cat(sapply(el(S(gsub(' ','',s),'')),function(x)i[W(m==x)]),sep='')} ``` [Try it online!](https://tio.run/nexus/r#PY9Na8MwDIbv/hWFUSxRNcRtGWs3H3YPo9BDDiGH1HESs3wROyxh7LdnbgYDCR306nlQbe5DNszAG@2qLrccWSGXYmyVM10LnzTRTBa/Y/lVGVWxm7RusH1tHLvKPrNOhyyStXZOD5Y1ctA9fLzTKUTWJArERYQ07YSgeXcUmEoF4eVMnK/15Dvgj6SxQZtBswbyt72u4ebdnCNSlOxjiLam3eaYIjPSQTd6Gyi4wpQcUpoTkeIDOCE96FfEV5U5sFnf1zOssNKOd@Cb1Wvxj/z/5YQmiaGRcvIGsrqXfv@zFMBVl@uyLjgpONEz@vFCZ3/utHWmLTciCA5BcOS4/AI "R – TIO Nexus") I have loaded the library `methods` in TIO example to get `el()` to work, however this is not required on my version of R. ]
[Question] [ **This question already has answers here**: [Balanced Ternary Converter](/questions/41752/balanced-ternary-converter) (20 answers) Closed 6 years ago. Mr Seckington is a mobile grocer. He drives his van door-to-door selling his produce all around the nearby villages. Mr Seckington needs a method to weigh the produce he is selling so he knows how much to charge his customers. Because space is at such a premium on his van, he uses an interesting sequence of weights on his scale that minimizes the amount weights he needs to measure any integer number of grams. [![enter image description here](https://i.stack.imgur.com/ngSci.png)](https://i.stack.imgur.com/ngSci.png) The weights (in grams) are all powers of 3, i.e 1, 3, 9, 27, 81... He puts what he is weighing on the left side of the scale and he can put weights on either side of the scale to measure a desired weight with integer granularity. For example if he wants to weigh out 2 grams of peppercorns, he will put a 1g weight on the left side, a 3g weight on the right side, and then he can load the peppercorns onto the left side until the scale balances. Similarly if he wants to weigh out 30g of chocolate chips, he'll put 3g + 27g weights on the right side and load chocolate chips onto the left side until the scale balances. Given a positive integer weight as input, output two lists - one with the weights that must go on the left side of the scale and the other with the weights that must go on the right side. It should be clear from the output which is the left-side list and which is the right-side list. E.g. always ordering `left`, then `right` is fine. The ordering within the lists doesn't matter. You should be able to support inputs at least up to 88,573 (31+32+...+310). ``` Input -> Output 1 -> {}, {1} 2 -> {1}, {3} 3 -> {}, {3} 4 -> {}, {1 ,3} 5 -> {1, 3}, {9} 6 -> {3}, {9} 7 -> {3}, {1, 9} 8 -> {1}, {9} 9 -> {}, {9} 10 -> {}, {1, 9} 13 -> {}, {1, 3, 9} 14 -> {1, 3, 9}, {27} 20 -> {1, 9}, {3, 27} 100 -> {9}, {1, 27, 81} ``` [Harold Seckington](http://www.helmdon.com/history/reminiscense_harold_seckington.htm) really did have a mobile grocery in the village that I grew up in. However, I made up the bit about him using a ternary system of weights. [Answer] # [MATL](https://github.com/lmendo/MATL), 39 bytes ``` `x3:H-@Z^3@:q^*!tXsG=~}1MZ)Xzt0>&)_Xh&D ``` The output lists are in reversed order. Each list is actually a column array of numbers (square brackets, semicolon as separator). In MATL, as in MATLAB and Octave, an array with a single number is the same as a number, so in that case the corresponding list doesn't have enclosing brackets. [Try it online!](https://tio.run/nexus/matl#@59QYWzloesQFWfsYFUYp6VYElHsbltXa@gbpRlRVWJgp6YZH5Gh5vL/v6ExAA "MATL – TIO Nexus") Or [verifiy all test cases](https://tio.run/nexus/matl#S4jw@p9QYWzloesQFWfsYFUYp6VYElHsZVtXa@gbpRlRVWJgp6YZH5Gh5vI/1iXkvyGXEZcxlwmXKZcZlzmXBZcll6EBl6Exl6EJlxGQYWAAAA). ### How it works This keeps testing sets of weights of increasing size: the set `{1}`, then `{1, 3}`, then `{1, 3, 9}`, ... This is done with a `do...while` loop. For any such set, containing `k` different weights, all possible distributions of those weights are tested. A distribution of weights is defined by a vector of `k` numbers, where each number may be `-1`, `0`, `1`, meaning that the corresponding weight is on the left side, unused, or on the right side. For each distribution, the sum is compared with the target weight. This is done in a vectorized manner, using 2D arrays. If for a given set of weights there is a distribution of those weights that matches the target, the solution has been found. [Answer] # Python2 - ~~109~~ 102 bytes Thought it might be fun to do it without a base conversion builtin. ``` a=[[],[],[],[]];r=input()+3**12;e=0;i=1 while r:c=r%3+e;a[c]+=[i];e=c>1;r/=3;i*=3 print a[2],a[1][:-1] ``` [Answer] ## JavaScript (ES6), ~~113~~ … ~~76~~ 75 bytes Returns an array of two arrays `[ [left_side], [right_side] ]`. ``` f=(n,x=!(r=[[],[]]),i=1)=>n+x?f(n/3|0,(x+=n%3)>1,i*3,x%3&&r[2-x].push(i)):r ``` ### Test cases ``` f=(n,x=!(r=[[],[]]),i=1)=>n+x?f(n/3|0,(x+=n%3)>1,i*3,x%3&&r[2-x].push(i)):r console.log(JSON.stringify(f( 1))); // -> {}, {1} console.log(JSON.stringify(f( 2))); // -> {1}, {3} console.log(JSON.stringify(f( 3))); // -> {}, {3} console.log(JSON.stringify(f( 4))); // -> {}, {1 ,3} console.log(JSON.stringify(f( 5))); // -> {1, 3}, {9} console.log(JSON.stringify(f( 6))); // -> {3}, {9} console.log(JSON.stringify(f( 7))); // -> {3}, {1, 9} console.log(JSON.stringify(f( 8))); // -> {1}, {9} console.log(JSON.stringify(f( 9))); // -> {}, {9} console.log(JSON.stringify(f( 10))); // -> {}, {1, 9} console.log(JSON.stringify(f( 13))); // -> {}, {1, 3, 9} console.log(JSON.stringify(f( 14))); // -> {1, 3, 9}, {27} console.log(JSON.stringify(f( 20))); // -> {1, 9}, {3, 27} console.log(JSON.stringify(f(100))); // -> {9}, {1, 27, 81} ``` [Answer] ## Batch, 178 bytes ``` @echo off set l= set r= set/aw=%1,p=1,g=w%%3 goto %g% :2 set l=%l% %p% goto 0 :1 set r=%r% %p% :0 set/ap*=3,w+=1,w/=3,g=w%%3 if %w% gtr 0 goto %g% echo(%l% echo(%r% ``` ]
[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/108860/edit). Closed 7 years ago. [Improve this question](/posts/108860/edit) ### Background You work for the police force as a programmer. A villain has planted a bomb in the city, luckily the police force has captured both him and the bomb. The bomb is really complicated to disarm, however it has a password input to disarm it. The villain, being cocky, has told you that there was no way you'd find the password as you'd take X time to brute force it. You notice that the keyboard can only input english letters (lower and upper case) and digits. ### Task Assuming you can try Y passwords per second, and that the brute force character order would be `a-z A-Z 0-9`, you are to create either a full program or a function that takes as input both X (in seconds) and Y (passwords/second) and outputs the villain's password. X can be a float but Y will always be an integer. **(X\*Y should always be an integer)** Your code has to solve the problem using math instead of relying on trying several options or creating huge arrays and simply indexing them with X\*Y. ### Example in JS ``` var c="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; var b=62; function num(x){ var n=0; while(x>=0){ x-=Math.pow(b,++n); } return n; } function reduce(x, n){ while(--n>0){ x-=Math.pow(b,n); } return x; } function pass(x, y){ x=x*y; x--; var p=[]; var n=num(x); x = reduce(x, n); do{ var t=x%b; x=(x-t)/b; p.unshift(t); }while(x>0); return ("a".repeat(n)+p.map(f=>c[f]).join``).substr(-n); } ``` Assuming my code is correct here are some example outputs. **(If there are any errors please tell me so that I can correct them)** ``` pass(0.000, 1000); // "" or anything that won't be mistaken for a password pass(0.001, 1000); // "a" pass(0.002, 1000); // "b" pass(0.027, 1000); // "A" //A password that would take a year to brute force at 1000 passwords/second pass(3600*24*365, 1000) // "HzmZmr" ``` My code is awful and ungolfed but it's only to serve as an example. Since this is code-golf shortest answer in bytes wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ×ḃ62ịØWŒs ``` **[Try it online!](https://tio.run/nexus/jelly#@394@sMdzWZGD3d3H54RfnRS8f///40NTY3NDAwM/hsCCQA)** ### How? ``` ×ḃ62ịØWŒs - Main link: X, Y × - multiply X by Y ḃ62 - convert to bijective base 62 (uses modulo arithmetic under the hood) ị - index into (1-based) ØW - word yield -> "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_" Œs - swap case ``` [Answer] # [Python 2](https://docs.python.org/2/), 121 bytes ``` x,y=input() r=range;b=map(chr,r(97,123)+r(65,91)+r(48,58)) i=int(x*y) p=b[i%62] while i/62>0:i=i/62-1;p=b[i%62]+p print p ``` [Try it online!](https://tio.run/nexus/python2#PYzBCoMwEAXv@YpcCklM6SbRVCvpj4gHLVIDVpbFUv36NL30NjBvXtr1EeKK701IRoGG9Tm1Y3gNKB4zaRLNVRvrZEHCV7oxPyhrXdVSspjDTezqkAzD2MWTtz37zHGZeLx4e4dbXmQ4m/bvC2RIOeOYUuc8gLKlcvmaGwDovw "Python 2 – TIO Nexus") This basically calculate the `x*y` in base 62 For a recursive solution at 125 bytes ``` x,y=input() r=range;b=map(chr,r(97,123)+r(65,91)+r(48,58)) f=lambda i:(f(i/62)if~-i/62>0else'')+b[i%62-1] print f(int(x*y)+1) ``` [Try it online!](https://tio.run/nexus/python2#Fcy9DoIwFEDhnadgMdxbSuwPVNDUFyEMRVttAg2pmMDiqyNs33BytoWu2ofpOwMmUUcTXvbW69FM8HhHGqG5UC4k5hFURRt@oKxpVSMmTg9m7J8m9Vdw4M9KoHe/4sCd2eFjswzzvvUnJQreJVP0YU73MMywkBVzjtvWSsUYESWR@z7ljLHuDw "Python 2 – TIO Nexus") ]
[Question] [ Given two input integers, `a >= 4` and `b >= 2`, output an ASCII square of size `a x a`. The twist is the square must be constructed of `b` `3 x 3` squares formed like the following: ``` ### # # ### ``` You can use any ASCII printable character (except whitespace) to construct the smaller squares. I'm using `#` for visibility and consistency. The first `b` square is always placed in the upper-left, and the remaining `b` squares must be as evenly spaced as possible, going clockwise, around the larger square. The overall `a x a` square size is calculated in characters based on the center of the `b` squares. Here's an example for `a=7` and `b=3`. Note the numbers around the outside are not part of the output, just used to illustrate the construction. ``` 1234567 ### 1 # # 1 2 ### ### 2 3 # # 3 4 ### 4 5 5 6 ### 6 7 # # 7 ### 1234567 ``` The first `b` square is placed in the upper-left corner. In the remaining possible areas on the perimeter of `a x a`, we need to place two more `b` squares. Note how the smaller squares are staggered -- how they're spaced as evenly as possible around the larger square. If a potential `b` square could be in one of two spaces, your code can pick either and does not need to be deterministic. Here's another diagram explaining the spacing. I've drawn the `a` square with `-+|` and marked the center of the smaller `b` squares with `*`. If we count clockwise around the outside of the `a` square, we have 7 characters between the first and second centers `-----+|`, 7 between the second and third `|||+---`, and again 7 between the third and first `-+|||||`. This lines up mathematically as well, since we have `24` total characters making up the `a` square, minus `3` for the center of the `b` squares, must mean we have `7` characters between the centers. And, since the upper-left `b` square is fixed, this is the most evenly spaced arrangement possible. ``` 1234567 ### 1 #*-----+ 1 2 #|# #|# 2 3 | #*# 3 4 | #|# 4 5 | | 5 6 |### | 6 7 +-*---+ 7 ### 1234567 ``` ### Input * A two integers [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963), `a >= 4` and `b >= 2`. * You can take the input in either order -- your choice. * The input is guaranteed to be such that no `b` squares will overlap. ### Output The resulting ASCII art representation of the squares. ### Rules * Leading or trailing newlines or whitespace are all optional, so long as the characters themselves line up correctly. * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * If possible, please include a link to an online testing environment so people can try out your code! * [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 (note these are just examples, and depending upon how your code rounds the placement you may have slightly different output) ``` a=4, b=4 ###### # ## # ###### ###### # ## # ###### a=4, b=2 ### # # ### ### # # ### a=7, b=4 ### ### # # # # ### ### ### ### # # # # ### ### a=5, b=3 ### # # ### ### # # ###### # # ### a=7, b=3 ### # # ### ### # # ### ### # # ### a=7, b=5 ### ### # # # # ### ### ### ### # ##### # #### #### ### ``` [Answer] # Befunge, ~~240~~ 232 bytes ``` < vp62:&p01*4p00:-1& -1<v3!-2\*g04!:::p04p03-\g00:%g00\/g00:/g62*g01\1: p:|>0g*+\1-!00g*+2+\::1-!40g*\3-!30g*+\2-!00g*+9+ # >00g3+:00pv g00p05-\g00:<v+g06%3:\!!-4::-1p07\<90p06-\g00:< $55+,1-:!#@_^>\3/50g+7+g2%*70g+\:#^_$!3g,>1-:#^_ ``` [Try it online!](http://befunge.tryitonline.net/#code=PCB2cDYyOiZwMDEqNHAwMDotMSYKLTE8djMhLTJcKmcwNCE6OjpwMDRwMDMtXGcwMDolZzAwXC9nMDA6L2c2MipnMDFcMToKcDp8PjBnKitcMS0hMDBnKisyK1w6OjEtITQwZypcMy0hMzBnKitcMi0hMDBnKis5KwojID4wMGczKzowMHB2CmcwMHAwNS1cZzAwOjx2K2cwNiUzOlwhIS00OjotMXAwN1w8OTBwMDYtXGcwMDo8CiQ1NSssMS06ISNAX14+XDMvNTBnKzcrZzIlKjcwZytcOiNeXyQhM2csPjEtOiNeXw&input=NyAz) **Explanation** There are two parts to this. The first part is mostly handled by the loop on lines 2 and 3, which calculates the positions of each block by dividing the route around the main square (of length `(a-1)*n4`) into *b* segments. For each division, *d*, in that length, we determine the *x* and *y* coordinates with: ``` side = d/(a-1) // which side of the square (0 = top, 1 = right, 2 = bottom, 3 = left) off = d%(a-1) // the offset along that side, in a clockwise direction roff = a-1-off // the reverse of that offset x = (side==0)*off + (side==2)*roff + (side==1)*(a-1) y = (side==1)*off + (side==3)*roff + (side==2)*(a-1) ``` i.e. depending on which side of the square we're on, the coordinate value will either be the offset along that side, the reverse offset, the width of the square, or zero. We use those coordinates to write a 1 into the lower half of the Befunge playfield to mark the spot for later output. The second part, writing out the final pattern of squares, is handled by the triple loop on lines 5 and 6. We're looping over the y and x coordinates, and then for each point, we need to check if we've marked a spot in any of the surrounding 8 locations. This is achieved with a simple loop over a range of 9, basically summing the values it encounters in the playfield. In Python it would look something like this: ``` total = sum(playfield[y+i/3][x+i%3] * (i != 4) for i in range(9)) ``` The multiplication by `i != 4` is so that we exclude the centre point in the range. If this total is greater than 0 we need to output a `#`, otherwise we output a space. To avoid any branching, we simply use `!total` as an index into a character "table" (the `#` at the start of line 3) to determine the character to output. [Answer] ## C, ~~350~~ ~~302~~ 253 ``` i,j,x,y,a,b,c;main(){scanf("%d%d",&a,&b);a+=3;char*s,o[a*a];for(;c<a;)sprintf(o+c++*a,"%*s\n",a-1,"");for(;i<b;){x=y=0;for(j=(a-4)*i++*4/b;j--;)y>0&!x?y--:y>a-5?x--:x>a-5?y++:x++;s=o+y*a+x;s[2]=s[1]=*s|=3;s+=a;s[2]=*s|=3;s+=a;s[2]=s[1]=*s|=3;}puts(o);} ``` Ungolfed: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int i,j,x,y,a,b,c; main(int n, char** v) { a = atoi(v[1])+3; b = atoi(v[2]); char o[a*a-a], *s; for (; c < a-1; c++) { sprintf(o+c*a, "%*s\n",a-1," "); } for (; i < b; i++) { x=y=1; for(j=(a-4)*i*4/b;j--;){ // Set the number of steps from 1,1 if(y>1&x<2) y--; // We are on the left wall else if(y>a-4) x--; // We are on the bottom else if(x>a-4) y++; // We are on the right wall else x++; // We are on the top } s = o+(y-1)*a+x-1; // Find the output position bcopy("#x#",s,3); s+=a; bcopy("# #",s,3); s+=a; bcopy("#y#",s,3); } printf("%s\n", o); } ``` This compiles with gcc under linux. Windows might substitute `<windows.h>` for the `<stdlib.h>` and `<stdio.h>` includes. **Explanation** We initialize the output string to an array of newline-terminated rows. `sprintf` takes care of null-terminating the string. We descend into a nested group of ternary operators to determine the wall. We then write out the square. We start each square counting from (1,1). This is less efficient but saves a few bytes over the step method. It also avoids rounding errors in integer division. ]